@koinzhang/paseo-plugin-customize 0.2.1 → 0.4.0

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.
@@ -0,0 +1,60 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import type { PluginHandlerContext } from "@getpaseo/plugin/server";
4
+ import type { ProviderVersion } from "../shared/contracts.ts";
5
+ import type { ProviderId } from "../shared/providers.ts";
6
+
7
+ const execFileAsync = promisify(execFile);
8
+ type Diagnostic = PluginHandlerContext["paseo"]["providers"]["diagnostic"];
9
+ type VersionRunner = (command: string, args: string[], options: { timeout: number; maxBuffer: number }) => Promise<{ stdout: string }>;
10
+
11
+ /** Local binaries only; package runners could install software while probing. */
12
+ const VERSION_BINARIES: Record<ProviderId, string> = {
13
+ claude: "claude", codex: "codex", cursor: "cursor-agent", copilot: "copilot", opencode: "opencode", pi: "pi", omp: "omp",
14
+ cline: "cline", "codebuddy-code": "codebuddy", gemini: "gemini", goose: "goose", grok: "grok", kilo: "kilo",
15
+ kiro: "kiro-cli", kimi: "kimi", "qwen-code": "qwen", traecli: "traecli",
16
+ };
17
+
18
+ /** Accept version output, not arbitrary numbers in diagnostic errors or paths. */
19
+ export function parseProviderVersion(provider: ProviderId, output: string): string | null {
20
+ const text = output.trim();
21
+ if (provider === "opencode") {
22
+ return /^(?:opencode\s+)?v?(\d+\.\d+\.\d+(?:-[\da-z.-]+)?(?:\+[\da-z.-]+)?)$/i.exec(text)?.[1] ?? null;
23
+ }
24
+ if (text.length > 200 || /\b(?:error|failed|failure|unknown|unavailable)\b/i.test(text)) return null;
25
+ // Product prefixes, e.g. codex-cli / @tencent/tclaude / omp/, and
26
+ // suffix labels, e.g. 2.1.0 (Claude Code). Date-based Cursor builds also fit.
27
+ return /^(?:[a-z@][a-z\d@._/-]*(?:[ \t]+[a-z][a-z\d._-]*)*[ \t/]+)?v?(\d+\.\d+\.\d+(?:-[\da-z.-]+)?(?:\+[\da-z.-]+)?)(?:[ \t]+\([a-z][a-z \t-]*\))?$/i.exec(text)?.[1] ?? null;
28
+ }
29
+
30
+ export async function detectProviderVersion(
31
+ provider: ProviderId,
32
+ diagnostic?: Diagnostic,
33
+ run: VersionRunner = execFileAsync,
34
+ hostTimeoutMs = 5000,
35
+ ): Promise<ProviderVersion> {
36
+ if (diagnostic) {
37
+ let timer: ReturnType<typeof setTimeout> | undefined;
38
+ try {
39
+ const response = await Promise.race([
40
+ diagnostic(provider),
41
+ new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error("Provider diagnostic timed out")), hostTimeoutMs); }),
42
+ ]);
43
+ const row = /^\s*Version:[ \t]*(.*)$/m.exec(response.diagnostic)?.[1];
44
+ const version = row ? parseProviderVersion(provider, row) : null;
45
+ if (version) return { version, source: "host" };
46
+ } catch {
47
+ // Older hosts and unavailable providers can still have a usable PATH CLI.
48
+ } finally {
49
+ if (timer !== undefined) clearTimeout(timer);
50
+ }
51
+ }
52
+ try {
53
+ const { stdout } = await run(VERSION_BINARIES[provider], ["--version"], { timeout: 3000, maxBuffer: 32 * 1024 });
54
+ const version = parseProviderVersion(provider, stdout);
55
+ if (version) return { version, source: "cli" };
56
+ } catch {
57
+ // Missing binaries, timeout and failed version commands do not fail a scan.
58
+ }
59
+ return { version: null, source: "unknown" };
60
+ }
@@ -17,6 +17,7 @@ import {
17
17
  } from "../scan-kit.ts";
18
18
  import type { Entry, Scope } from "../../shared/contracts.ts";
19
19
  import { opencodeExternalSkillSwitch } from "../compatibility.ts";
20
+ import { fmBool } from "../frontmatter.ts";
20
21
 
21
22
  function configDir(ctx: ScanContext): string {
22
23
  const xdg = ctx.env.XDG_CONFIG_HOME?.trim();
@@ -54,6 +55,8 @@ export function scanOpencode(ctx: ScanContext): Entry[] {
54
55
  const noClaudePrompt = noClaude || truthy(ctx.env.OPENCODE_DISABLE_CLAUDE_CODE_PROMPT);
55
56
  const noClaudeSkills = noClaude || truthy(ctx.env.OPENCODE_DISABLE_CLAUDE_CODE_SKILLS);
56
57
  const externalSkills = opencodeExternalSkillSwitch(ctx.env);
58
+ const version = ctx.providerVersion?.version;
59
+ const v2 = version != null && Number(version.split(".")[0]) >= 2;
57
60
 
58
61
  const configs: Array<{ file: string; scope: Scope; data: Record<string, unknown> }> = [];
59
62
  for (const file of configFiles(globalDir)) {
@@ -147,25 +150,39 @@ export function scanOpencode(ctx: ScanContext): Entry[] {
147
150
  // Skills ------------------------------------------------------------------
148
151
  const permissions: Array<[string, string]> = [];
149
152
  for (const { data } of configs) {
150
- const skill = isRecord(data.permission) ? data.permission.skill : undefined;
151
- if (typeof skill === "string") permissions.push(["*", skill]);
152
- else if (isRecord(skill)) for (const [pattern, action] of Object.entries(skill)) if (typeof action === "string") permissions.push([pattern, action]);
153
+ if (v2) {
154
+ for (const rule of Array.isArray(data.permissions) ? data.permissions : []) {
155
+ if (isRecord(rule) && rule.action === "skill" && typeof rule.resource === "string" && typeof rule.effect === "string") {
156
+ permissions.push([rule.resource, rule.effect]);
157
+ }
158
+ }
159
+ } else {
160
+ const skill = isRecord(data.permission) ? data.permission.skill : undefined;
161
+ if (typeof skill === "string") permissions.push(["*", skill]);
162
+ else if (isRecord(skill)) for (const [pattern, action] of Object.entries(skill)) if (typeof action === "string") permissions.push([pattern, action]);
163
+ }
153
164
  }
154
165
  const skills = (root: string, scope: Scope, external = false, claude = false) => {
155
166
  for (const skill of findSkills(root, { recursive: true, maxDepth: 6 })) {
156
167
  const base = skillEntry(skill, root, scope);
157
168
  const tags = [...(base.tags ?? []), ...(claude ? (["legacy"] as Entry["tags"]) : [])];
158
- const permission = skillPermission(permissions, skill.name);
169
+ const permission = skillPermission(permissions, v2 ? path.basename(skill.dir) : skill.name);
170
+ const metadata = skill.doc.data.metadata;
171
+ const noAutoinvoke = isRecord(metadata) && fmBool(metadata, "opencode/autoinvoke") === false;
172
+ const permittedTags = permission === "ask" ? [...tags, "ask" as const] : tags;
159
173
  if (external && !externalSkills.enabled) {
160
174
  sink.add({ ...base, tags, status: "disabled", reason: { code: "env", value: externalSkills.disabledBy } });
161
175
  } else if (claude && noClaudeSkills) {
162
176
  sink.add({ ...base, tags, status: "disabled", reason: { code: "env", value: noClaude ? "OPENCODE_DISABLE_CLAUDE_CODE" : "OPENCODE_DISABLE_CLAUDE_CODE_SKILLS" } });
163
177
  } else if (permission === "deny") {
164
- sink.add({ ...base, tags, status: "disabled", reason: { code: "config", value: `permission.skill: deny` } });
178
+ sink.add({ ...base, tags, status: "disabled", reason: { code: "config", value: v2 ? "permissions: skill deny" : "permission.skill: deny" } });
179
+ } else if (noAutoinvoke && v2) {
180
+ sink.add({ ...base, tags: permittedTags, status: "manual", reason: { code: "frontmatter", value: "metadata.opencode/autoinvoke: false" } });
181
+ } else if (noAutoinvoke && !version) {
182
+ sink.add({ ...base, tags: permittedTags, status: "pending", reason: { code: "frontmatter", value: "metadata.opencode/autoinvoke: false (requires OpenCode >=2; version unknown)" } });
165
183
  } else {
166
- // OpenCode 1.18 advertises discovered skills automatically. Claude/Cursor
167
- // `disable-model-invocation` does not make one manual-only here.
168
- sink.add({ ...base, tags: permission === "ask" ? [...tags, "ask"] : tags, status: "auto" });
184
+ // OpenCode ignores other agents' `disable-model-invocation` switches.
185
+ sink.add({ ...base, tags: permittedTags, status: "auto" });
169
186
  }
170
187
  }
171
188
  };
@@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "nod
3
3
  import { tmpdir } from "node:os";
4
4
  import path from "node:path";
5
5
  import { after, test } from "node:test";
6
- import type { Entry } from "../shared/contracts.ts";
6
+ import type { Entry, ProviderVersion } from "../shared/contracts.ts";
7
7
  import type { ProviderId } from "../shared/providers.ts";
8
8
  import { PROVIDER_IDS } from "../shared/providers.ts";
9
9
  import { mcpPreview, scanProvider } from "./handlers.ts";
@@ -25,8 +25,8 @@ function fixture(name: string, files: Record<string, string>): { home: string; p
25
25
  return { home, project };
26
26
  }
27
27
 
28
- function scan(provider: ProviderId, fx: { home: string; project: string }, env: Record<string, string> = {}): Entry[] {
29
- return scanProvider(provider, fx.project, { home: fx.home, env, platform: "linux" });
28
+ function scan(provider: ProviderId, fx: { home: string; project: string }, env: Record<string, string> = {}, providerVersion?: ProviderVersion): Entry[] {
29
+ return scanProvider(provider, fx.project, { home: fx.home, env, platform: "linux", providerVersion });
30
30
  }
31
31
 
32
32
  function find(entries: Entry[], category: Entry["category"], name: string): Entry {
@@ -133,6 +133,51 @@ test("opencode: discovered skills stay automatic despite foreign manual-only fro
133
133
  assert.equal(find(entries, "mcp", "m").status, "disabled");
134
134
  });
135
135
 
136
+ test("opencode: v2 metadata controls model discovery only for verified v2 versions", () => {
137
+ const fx = fixture("opencode-autoinvoke", {
138
+ "project/.opencode/skills/native/SKILL.md": skill("native", "metadata:\n opencode/autoinvoke: false\n"),
139
+ "home/.config/opencode/skills/global/SKILL.md": skill("global", 'metadata:\n opencode/autoinvoke: "false"\n'),
140
+ "project/.agents/skills/shared/SKILL.md": skill("shared", "metadata:\n opencode/autoinvoke: false\n"),
141
+ "project/.claude/skills/legacy/SKILL.md": skill("legacy", "metadata:\n opencode/autoinvoke: false\n"),
142
+ "project/.opencode/skills/automatic/SKILL.md": skill("automatic", "metadata:\n opencode/autoinvoke: true\n"),
143
+ "project/.opencode/skills/foreign/SKILL.md": skill("foreign", "disable-model-invocation: true\n"),
144
+ "project/.opencode/skills/top-level/SKILL.md": skill("top-level", "opencode/autoinvoke: false\n"),
145
+ });
146
+ for (const version of ["2.0.18", "2.0.0-beta.1", "3.0.0", "1.18.32", null]) {
147
+ const entries = scan("opencode", fx, {}, { version, source: version ? "cli" : "unknown" });
148
+ const expected = version == null ? "pending" : version.startsWith("1.") ? "auto" : "manual";
149
+ for (const name of ["native", "global", "shared", "legacy"]) {
150
+ const entry = find(entries, "skills", name);
151
+ assert.equal(entry.status, expected, `${version}: ${name}`);
152
+ if (expected !== "auto") assert.match(entry.reason?.value ?? "", /metadata\.opencode\/autoinvoke: false/);
153
+ }
154
+ for (const name of ["automatic", "foreign", "top-level"]) assert.equal(find(entries, "skills", name).status, "auto");
155
+ }
156
+ });
157
+
158
+ test("opencode: deny and external-directory switches override v2 manual discovery; ask remains tagged", () => {
159
+ const fx = fixture("opencode-v2-permissions", {
160
+ "project/.opencode/skills/secret/SKILL.md": skill("Display Label", "metadata:\n opencode/autoinvoke: false\n"),
161
+ "project/.opencode/skills/ask/SKILL.md": skill("ask", "metadata:\n opencode/autoinvoke: false\n"),
162
+ "project/.opencode/skills/allowed/SKILL.md": skill("allowed"),
163
+ "project/.agents/skills/shared/SKILL.md": skill("shared", "metadata:\n opencode/autoinvoke: false\n"),
164
+ "project/opencode.json": JSON.stringify({ permissions: [
165
+ { action: "skill", resource: "*", effect: "deny" },
166
+ { action: "skill", resource: "a*", effect: "allow" },
167
+ { action: "skill", resource: "ask", effect: "ask" },
168
+ { action: "read", resource: "secret", effect: "allow" },
169
+ ] }),
170
+ });
171
+ const entries = scan("opencode", fx, { OPENCODE_DISABLE_EXTERNAL_SKILLS: "1" }, { version: "2.0.18", source: "host" });
172
+ assert.equal(find(entries, "skills", "Display Label").status, "disabled");
173
+ assert.match(find(entries, "skills", "Display Label").reason?.value ?? "", /permissions: skill deny/);
174
+ assert.equal(find(entries, "skills", "ask").status, "manual");
175
+ assert.ok(find(entries, "skills", "ask").tags.includes("ask"));
176
+ assert.equal(find(entries, "skills", "allowed").status, "auto");
177
+ assert.equal(find(entries, "skills", "shared").status, "disabled");
178
+ assert.equal(find(entries, "skills", "shared").reason?.code, "env");
179
+ });
180
+
136
181
  test("pi: recursive skills, no rules / mcp", () => {
137
182
  const fx = fixture("pi", {
138
183
  "project/AGENTS.md": "# Agents\n",
@@ -1,12 +1,13 @@
1
1
  import { closeSync, lstatSync, openSync, readdirSync, readSync, statSync } from "node:fs";
2
2
  import path from "node:path";
3
- import type { Category, Entry, ReasonCode, Scope, Status, Tag } from "../shared/contracts.ts";
3
+ import type { Category, Entry, ProviderVersion, ReasonCode, Scope, Status, Tag } from "../shared/contracts.ts";
4
4
  import { firstLine, fmString, parseFrontmatter, type Frontmatter } from "./frontmatter.ts";
5
5
 
6
6
  export interface ScanEnv {
7
7
  home: string;
8
8
  env: Record<string, string | undefined>;
9
9
  platform: NodeJS.Platform;
10
+ providerVersion?: ProviderVersion;
10
11
  }
11
12
 
12
13
  export interface ScanContext extends ScanEnv {
@@ -9,21 +9,21 @@ import { readSnapshot, SCAN_REFRESH_MS, snapshotFile, writeSnapshot } from "./sc
9
9
  test("saved scans survive a new read, expire after ten minutes, and reject corrupt snapshots", () => {
10
10
  const directory = mkdtempSync(path.join(tmpdir(), "customize-snapshot-"));
11
11
  const scannedAt = "2026-01-01T00:00:00.000Z";
12
- const result = { provider: "codex" as const, projectRoot: "/project", home: homedir(), entries: [], compatibility: null, scannedAt };
12
+ const result = { provider: "opencode" as const, projectRoot: "/project", home: homedir(), entries: [], compatibility: null, providerVersion: { version: "2.0.18", source: "host" as const }, scannedAt };
13
13
  const time = Date.parse(scannedAt);
14
14
  try {
15
15
  writeSnapshot(result, directory);
16
16
  assert.equal(statSync(directory).mode & 0o777, 0o700);
17
- assert.deepEqual(readSnapshot("codex", "/project", { directory, now: time + SCAN_REFRESH_MS - 1 }), { snapshot: result, stale: false });
18
- assert.deepEqual(readSnapshot("codex", "/project", { directory, now: time + SCAN_REFRESH_MS }), { snapshot: result, stale: true });
19
- assert.equal(readSnapshot("codex", "/other", { directory }).snapshot, null);
20
- const file = snapshotFile("codex", "/project", directory);
17
+ assert.deepEqual(readSnapshot("opencode", "/project", { directory, now: time + SCAN_REFRESH_MS - 1 }), { snapshot: result, stale: false });
18
+ assert.deepEqual(readSnapshot("opencode", "/project", { directory, now: time + SCAN_REFRESH_MS }), { snapshot: result, stale: true });
19
+ assert.equal(readSnapshot("opencode", "/other", { directory }).snapshot, null);
20
+ const file = snapshotFile("opencode", "/project", directory);
21
21
  assert.equal(statSync(file).mode & 0o777, 0o600);
22
- assert.equal(JSON.parse(readFileSync(file, "utf8")).version, 2);
23
- writeFileSync(file, JSON.stringify({ version: 1, result }));
24
- assert.equal(readSnapshot("codex", "/project", { directory }).snapshot, null);
22
+ assert.equal(JSON.parse(readFileSync(file, "utf8")).version, 5);
23
+ writeFileSync(file, JSON.stringify({ version: 4, result }));
24
+ assert.equal(readSnapshot("opencode", "/project", { directory }).snapshot, null);
25
25
  writeFileSync(file, "broken json");
26
- assert.equal(readSnapshot("codex", "/project", { directory }).snapshot, null);
26
+ assert.equal(readSnapshot("opencode", "/project", { directory }).snapshot, null);
27
27
  } finally {
28
28
  rmSync(directory, { recursive: true, force: true });
29
29
  }
@@ -7,7 +7,7 @@ import { scanRpc, type ScanResult } from "../shared/contracts.ts";
7
7
  import type { ProviderId } from "../shared/providers.ts";
8
8
 
9
9
  export const SCAN_REFRESH_MS = 10 * 60_000;
10
- const SNAPSHOT_VERSION = 2;
10
+ const SNAPSHOT_VERSION = 5;
11
11
  const MAX_SNAPSHOT_BYTES = 10 * 1024 * 1024;
12
12
  const SnapshotSchema = z.object({ version: z.literal(SNAPSHOT_VERSION), result: scanRpc.output });
13
13
 
@@ -0,0 +1,146 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { after, test } from "node:test";
6
+ import type { Entry, Status } from "../shared/contracts.ts";
7
+ import { entryTokens, estimateTokens, withTokens } from "./tokens.ts";
8
+
9
+ const base = realpathSync(mkdtempSync(path.join(tmpdir(), "customize-tokens-")));
10
+ after(() => rmSync(base, { recursive: true, force: true }));
11
+
12
+ function fixture(name: string, files: Record<string, string>): string {
13
+ const root = path.join(base, name);
14
+ for (const [rel, content] of Object.entries(files)) {
15
+ const file = path.join(root, rel);
16
+ mkdirSync(path.dirname(file), { recursive: true });
17
+ writeFileSync(file, content);
18
+ }
19
+ mkdirSync(root, { recursive: true });
20
+ return root;
21
+ }
22
+
23
+ function entry(category: Entry["category"], file: string, extra: Partial<Entry> = {}): Entry {
24
+ return { id: `${category}|${file}`, category, scope: "project", name: path.basename(file), path: file, dir: path.dirname(file), source: file, status: "auto", tags: [], ...extra };
25
+ }
26
+
27
+ const SKILL = "---\nname: deploy\ndescription: Ship the service safely\n---\n\n## Steps\n\nRun the release script and verify the health check.\n";
28
+
29
+ test("tokens: script-aware heuristic counts ASCII, CJK and other non-ASCII", () => {
30
+ assert.equal(estimateTokens(""), 0);
31
+ assert.equal(estimateTokens("a".repeat(400)), 100);
32
+ assert.equal(estimateTokens("中".repeat(15)), 16);
33
+ assert.equal(estimateTokens("こんにちは"), 6);
34
+ assert.equal(estimateTokens("é"), 1);
35
+ assert.equal(estimateTokens("hello 你好"), Math.ceil(6 / 4 + 2 * 1.05));
36
+ assert.ok(estimateTokens("中文内容") > estimateTokens("ab"), "CJK is denser than ASCII at equal length");
37
+ assert.equal(estimateTokens("a".repeat(400) + "中".repeat(15)), Math.ceil(100 + 15 * 1.05), "ASCII and CJK add up independently");
38
+ });
39
+
40
+ test("tokens: MCP and non-loaded rows are never counted", () => {
41
+ const root = fixture("mcp", {
42
+ "mcp.json": JSON.stringify({ mcpServers: { x: { command: "npx" } } }),
43
+ "AGENTS.md": "# Agents\n",
44
+ });
45
+ assert.equal(entryTokens(entry("mcp", path.join(root, "mcp.json"))), undefined);
46
+ assert.equal(entryTokens(entry("instructions", path.join(root, "AGENTS.md"), { status: "inactive" })), undefined);
47
+ assert.equal(entryTokens(entry("skills", path.join(root, "AGENTS.md"), { status: "disabled" })), undefined);
48
+ });
49
+
50
+ test("tokens: instructions and rules are always-on content", () => {
51
+ const root = fixture("always", {
52
+ "project/CLAUDE.md": "# Project\n\nInstructions.\n",
53
+ "project/.claude/rules/always.md": "Always applied rule body\n",
54
+ });
55
+ for (const [category, file] of [["instructions", "project/CLAUDE.md"], ["rules", "project/.claude/rules/always.md"]] as const) {
56
+ const cost = entryTokens(entry(category, path.join(root, file)));
57
+ assert.ok(cost && cost.atRest > 0, file);
58
+ assert.equal(cost.onInvoke, 0, file);
59
+ }
60
+ });
61
+
62
+ test("tokens: on-demand entries split advertised metadata from the body", () => {
63
+ const root = fixture("split", { "skills/deploy/SKILL.md": SKILL });
64
+ const file = path.join(root, "skills/deploy/SKILL.md");
65
+ const cost = entryTokens(entry("skills", file, { name: "deploy", description: "Ship the service safely" }));
66
+ assert.ok(cost);
67
+ const full = estimateTokens(SKILL);
68
+ const advertised = estimateTokens("deploy\nShip the service safely");
69
+ assert.equal(cost.atRest, advertised);
70
+ assert.equal(cost.onInvoke, full - advertised);
71
+ assert.equal(cost.atRest + cost.onInvoke, full, "the two segments add up to the file");
72
+
73
+ const manual = entryTokens(entry("skills", file, { status: "manual", name: "deploy", description: "Ship the service safely" }));
74
+ assert.deepEqual(manual, { atRest: 0, onInvoke: full }, "manual-only skills are not advertised");
75
+ });
76
+
77
+ test("tokens: commands and subagents split like skills", () => {
78
+ const root = fixture("commands", {
79
+ "commands/report.md": "---\ndescription: Write a report\n---\nSummarize the diff in detail.\n",
80
+ "agents/review.md": "---\ndescription: Review a change\n---\nRead the diff and list risks.\n",
81
+ });
82
+ for (const [category, file, description] of [
83
+ ["commands", "commands/report.md", "Write a report"],
84
+ ["subagents", "agents/review.md", "Review a change"],
85
+ ] as const) {
86
+ const cost = entryTokens(entry(category, path.join(root, file), { name: path.basename(file, ".md"), description }));
87
+ assert.ok(cost && cost.atRest > 0 && cost.onInvoke > 0, file);
88
+ }
89
+ });
90
+
91
+ test("tokens: plugin rows split advertised components from their bodies", () => {
92
+ const root = fixture("plugin", {
93
+ "skills/a/SKILL.md": SKILL,
94
+ "skills/a/reference.md": "Deep reference material for the skill body.\n",
95
+ "commands/report.md": "---\ndescription: Write a report\n---\nSummarize the diff in detail.\n",
96
+ "rules/style.md": "Always write tests.\n",
97
+ "node_modules/dep/SKILL.md": "x".repeat(4000),
98
+ "src/index.js": "console.log('not context')",
99
+ "plugin.json": JSON.stringify({ name: "demo" }),
100
+ });
101
+ const cost = entryTokens(entry("plugins", path.join(root, "plugin.json")));
102
+ assert.ok(cost);
103
+ const advertisedSkill = estimateTokens("deploy\nShip the service safely");
104
+ const advertisedCommand = estimateTokens("report\nWrite a report");
105
+ const skillFull = estimateTokens(SKILL);
106
+ const commandFull = estimateTokens("---\ndescription: Write a report\n---\nSummarize the diff in detail.\n");
107
+ assert.equal(cost.atRest, advertisedSkill + advertisedCommand + estimateTokens("Always write tests.\n"));
108
+ assert.equal(cost.onInvoke, skillFull - advertisedSkill + estimateTokens("Deep reference material for the skill body.\n") + commandFull - advertisedCommand);
109
+ });
110
+
111
+ test("tokens: dot-plugin manifests and directory targets resolve to the package root", () => {
112
+ const dot = fixture("dot-plugin", { ".codex-plugin/plugin.json": "{}", "skills/a/SKILL.md": SKILL });
113
+ const fromDot = entryTokens(entry("plugins", path.join(dot, ".codex-plugin", "plugin.json")));
114
+ assert.deepEqual(fromDot, { atRest: estimateTokens("deploy\nShip the service safely"), onInvoke: estimateTokens(SKILL) - estimateTokens("deploy\nShip the service safely") });
115
+
116
+ const dir = fixture("dir-plugin", { "agents/review.md": SKILL });
117
+ const fromDir = entryTokens(entry("plugins", dir));
118
+ assert.deepEqual(fromDir, fromDot, "a directory target and a manifest resolve to the same package");
119
+ });
120
+
121
+ test("tokens: non-manifest plugin rows and empty plugins stay uncounted", () => {
122
+ const root = fixture("config-plugin", { "config.yaml": "extensions:\n demo:\n type: stdio\n", "empty/plugin.json": "{}" });
123
+ assert.equal(entryTokens(entry("plugins", path.join(root, "config.yaml"))), undefined);
124
+ assert.equal(entryTokens(entry("plugins", path.join(root, "empty", "plugin.json"))), undefined);
125
+ });
126
+
127
+ test("tokens: withTokens attaches only rows with a cost", () => {
128
+ const root = fixture("attach", { "AGENTS.md": "# Agents\n", "empty.md": "" });
129
+ const entries = withTokens([
130
+ entry("instructions", path.join(root, "AGENTS.md")),
131
+ entry("instructions", path.join(root, "empty.md")),
132
+ ]);
133
+ assert.deepEqual(entries[0]?.tokens, { atRest: estimateTokens("# Agents\n"), onInvoke: 0 });
134
+ assert.equal(entries[1]?.tokens, undefined);
135
+ });
136
+
137
+ test("tokens: every status that loads nothing is skipped", () => {
138
+ const root = fixture("statuses", { "SKILL.md": SKILL });
139
+ const file = path.join(root, "SKILL.md");
140
+ for (const status of ["disabled", "inactive"] as Status[]) {
141
+ assert.equal(entryTokens(entry("skills", file, { status })), undefined, status);
142
+ }
143
+ for (const status of ["auto", "conditional", "manual"] as Status[]) {
144
+ assert.ok(entryTokens(entry("skills", file, { status })), status);
145
+ }
146
+ });
@@ -0,0 +1,178 @@
1
+ import { readdirSync, statSync } from "node:fs";
2
+ import path from "node:path";
3
+ import type { Category, Entry, TokenCost } from "../shared/contracts.ts";
4
+ import { fmString } from "./frontmatter.ts";
5
+ import { isDir, readMarkdown, readText } from "./scan-kit.ts";
6
+
7
+ /**
8
+ * Script-aware token estimate for configuration content.
9
+ *
10
+ * `ceil(ascii / 4 + cjk * 1.05 + otherBytes / 3)` — calibrated against `o200k_base`
11
+ * (GPT-4o / GPT-5 family) on 2168 local markdown / code / config files, including
12
+ * Chinese `AGENTS.md` files: MAPE 10% overall and 9.7% on CJK content, with a slight
13
+ * conservative bias. ASCII prose and code run 4.0–4.6 chars per token; CJK, kana,
14
+ * Hangul, fullwidth forms and CJK punctuation cost about one token per character, so
15
+ * a plain `bytes / 4` undercounts them by 1.5–2x. Claude-family tokenizers run another
16
+ * 10–20% denser on CJK, which this estimate does not add.
17
+ */
18
+ export function estimateTokens(text: string): number {
19
+ let ascii = 0;
20
+ let dense = 0;
21
+ let otherBytes = 0;
22
+ for (const char of text) {
23
+ const cp = char.codePointAt(0)!;
24
+ if (cp <= 0x7f) ascii++;
25
+ else if (isDense(cp)) dense++;
26
+ else otherBytes += cp <= 0x7ff ? 2 : cp <= 0xffff ? 3 : 4;
27
+ }
28
+ return Math.ceil(ascii / 4 + dense * CJK_TOKENS_PER_CHAR + otherBytes / 3);
29
+ }
30
+
31
+ /** Fitted on `o200k_base`: one CJK character is about one token. */
32
+ const CJK_TOKENS_PER_CHAR = 1.05;
33
+
34
+ function isDense(cp: number): boolean {
35
+ return (cp >= 0x2e80 && cp <= 0x303f) // CJK radicals, Kangxi, CJK symbols and punctuation
36
+ || (cp >= 0x3040 && cp <= 0x30ff) // Hiragana, Katakana
37
+ || (cp >= 0x3130 && cp <= 0x318f) // Hangul compatibility jamo
38
+ || (cp >= 0x3400 && cp <= 0x4dbf) // CJK extension A
39
+ || (cp >= 0x4e00 && cp <= 0x9fff) // CJK unified ideographs
40
+ || (cp >= 0xa960 && cp <= 0xa97f) // Hangul jamo extended-A
41
+ || (cp >= 0xac00 && cp <= 0xd7af) // Hangul syllables
42
+ || (cp >= 0xf900 && cp <= 0xfaff) // CJK compatibility ideographs
43
+ || (cp >= 0xff00 && cp <= 0xffef) // Halfwidth and fullwidth forms
44
+ || (cp >= 0x20000 && cp <= 0x3ffff); // CJK extensions B+
45
+ }
46
+
47
+ /** Largest read for counting; longer files are counted from their first 4 MiB. */
48
+ const MAX_READ_BYTES = 4 * 1024 * 1024;
49
+ /** Prompt-bearing files inside a plugin package; code and packaging are not context. */
50
+ const PROMPT_EXTENSIONS = [".md", ".markdown", ".mdc", ".rules", ".txt"] as const;
51
+ /** Plugin component directories. A plugin root is never walked as a whole. */
52
+ const COMPONENT_DIRS = ["skills", "commands", "agents", "rules", "instructions"] as const;
53
+ const SKIP_DIRS = new Set(["node_modules", "dist", "build", "out", "coverage", "vendor", "target", "__pycache__"]);
54
+ const MAX_WALK_DEPTH = 6;
55
+ const MAX_WALK_FILES = 500;
56
+
57
+ const counts = new Map<string, number>();
58
+
59
+ /** Cached by path + mtime + size so repeated scans re-read nothing. */
60
+ export function fileTokens(file: string): number | undefined {
61
+ let key: string;
62
+ try {
63
+ const stat = statSync(file);
64
+ if (!stat.isFile()) return undefined;
65
+ key = `${file}\u0000${stat.mtimeMs}\u0000${stat.size}`;
66
+ } catch {
67
+ return undefined;
68
+ }
69
+ const hit = counts.get(key);
70
+ if (hit !== undefined) return hit;
71
+ const text = readText(file, MAX_READ_BYTES);
72
+ if (text == null) return undefined;
73
+ const tokens = estimateTokens(text);
74
+ if (counts.size >= 4096) counts.clear();
75
+ counts.set(key, tokens);
76
+ return tokens;
77
+ }
78
+
79
+ function collectComponentFiles(dir: string, component: string, depth: number, out: Array<{ file: string; component: string }>): void {
80
+ if (depth > MAX_WALK_DEPTH || out.length >= MAX_WALK_FILES) return;
81
+ let entries;
82
+ try {
83
+ entries = readdirSync(dir, { withFileTypes: true });
84
+ } catch {
85
+ return;
86
+ }
87
+ for (const entry of entries) {
88
+ if (out.length >= MAX_WALK_FILES) return;
89
+ const full = path.join(dir, entry.name);
90
+ if (entry.isDirectory() || (entry.isSymbolicLink() && isDir(full))) {
91
+ if (entry.name.startsWith(".") || SKIP_DIRS.has(entry.name)) continue;
92
+ collectComponentFiles(full, component, depth + 1, out);
93
+ } else if (PROMPT_EXTENSIONS.some((ext) => entry.name.toLowerCase().endsWith(ext))) {
94
+ out.push({ file: full, component });
95
+ }
96
+ }
97
+ }
98
+
99
+ /** `name` + `description` as a provider advertises them before the body loads. */
100
+ function advertisedTokens(file: string): number {
101
+ const doc = readMarkdown(file);
102
+ const name = (doc ? fmString(doc.data, "name") : undefined) ?? path.basename(file, path.extname(file));
103
+ return estimateTokens(`${name}\n${doc?.description ?? ""}`);
104
+ }
105
+
106
+ /** Component kinds that load on demand; everything else in a package is always-on content. */
107
+ const ON_DEMAND_COMPONENTS: ReadonlySet<string> = new Set(["skills", "commands", "agents"]);
108
+
109
+ /** Skills, commands, and agents are advertised by name + description; the body arrives on invoke. */
110
+ function isAdvertisedFile(component: string, file: string): boolean {
111
+ if (component === "skills") return path.basename(file) === "SKILL.md";
112
+ return component === "commands" || component === "agents";
113
+ }
114
+
115
+ /** Split of a plugin package's bundled component prompts (`skills`, `commands`, `agents`, `rules`, `instructions`). */
116
+ export function pluginTokens(root: string): TokenCost {
117
+ const files: Array<{ file: string; component: string }> = [];
118
+ for (const component of COMPONENT_DIRS) {
119
+ const dir = path.join(root, component);
120
+ if (isDir(dir)) collectComponentFiles(dir, component, 1, files);
121
+ }
122
+ let atRest = 0;
123
+ let onInvoke = 0;
124
+ for (const { file, component } of files) {
125
+ const full = fileTokens(file) ?? 0;
126
+ if (!full) continue;
127
+ if (!ON_DEMAND_COMPONENTS.has(component)) {
128
+ atRest += full;
129
+ continue;
130
+ }
131
+ if (!isAdvertisedFile(component, file)) {
132
+ onInvoke += full;
133
+ continue;
134
+ }
135
+ const advertised = Math.min(advertisedTokens(file), full);
136
+ atRest += advertised;
137
+ onInvoke += full - advertised;
138
+ }
139
+ return { atRest, onInvoke };
140
+ }
141
+
142
+ /** Package root for a plugin row: a directory target, or the parent of a `*.json` manifest. */
143
+ function pluginRoot(file: string): string | undefined {
144
+ if (isDir(file)) return file;
145
+ if (!file.toLowerCase().endsWith(".json")) return undefined;
146
+ const dir = path.dirname(file);
147
+ return /^\..+-plugin$/.test(path.basename(dir)) ? path.dirname(dir) : dir;
148
+ }
149
+
150
+ /** Categories whose body is loaded on demand: the provider advertises name + description first. */
151
+ const ON_DEMAND: ReadonlySet<Category> = new Set<Category>(["skills", "commands", "subagents"]);
152
+
153
+ /** Context cost of one entry; MCP, disabled, and non-package plugin rows have none. */
154
+ export function entryTokens(entry: Entry): TokenCost | undefined {
155
+ if (entry.category === "mcp") return undefined;
156
+ if (entry.status === "disabled" || entry.status === "inactive") return undefined;
157
+ if (entry.category === "plugins") {
158
+ const root = pluginRoot(entry.path);
159
+ if (!root) return undefined;
160
+ const cost = pluginTokens(root);
161
+ return cost.atRest || cost.onInvoke ? cost : undefined;
162
+ }
163
+ const full = fileTokens(entry.path);
164
+ if (!full) return undefined;
165
+ if (!ON_DEMAND.has(entry.category)) return { atRest: full, onInvoke: 0 };
166
+ // Manual-only entries are not advertised, so the whole file arrives on invoke.
167
+ if (entry.status === "manual") return { atRest: 0, onInvoke: full };
168
+ const advertised = Math.min(estimateTokens(`${entry.name}\n${entry.description ?? ""}`), full);
169
+ return { atRest: advertised, onInvoke: full - advertised };
170
+ }
171
+
172
+ /** Attaches `tokens` to every countable entry. Runs after alias merging so a skill is counted once. */
173
+ export function withTokens(entries: readonly Entry[]): Entry[] {
174
+ return entries.map((entry) => {
175
+ const tokens = entryTokens(entry);
176
+ return tokens ? { ...entry, tokens } : entry;
177
+ });
178
+ }
@@ -54,6 +54,14 @@ export const TAGS = [
54
54
  ] as const;
55
55
  export type Tag = (typeof TAGS)[number];
56
56
 
57
+ export const TokenCostSchema = z.object({
58
+ /** Loaded without any action: full text for instructions / rules, name + description for on-demand entries. */
59
+ atRest: z.number(),
60
+ /** Added when the entry is invoked (skill body, command body, agent body). Zero for always-on content. */
61
+ onInvoke: z.number(),
62
+ });
63
+ export type TokenCost = z.infer<typeof TokenCostSchema>;
64
+
57
65
  export const EntrySchema = z.object({
58
66
  id: z.string(),
59
67
  category: z.enum(CATEGORIES),
@@ -68,6 +76,8 @@ export const EntrySchema = z.object({
68
76
  tags: z.array(z.enum(TAGS)),
69
77
  agentPlugin: z.object({ version: z.string(), validation: z.enum(["valid", "unsupported"]) }).optional(),
70
78
  mcp: z.object({ name: z.string(), transport: z.string(), target: z.string() }).optional(),
79
+ /** Script-aware estimate of the entry's own content; not a live context measurement. */
80
+ tokens: TokenCostSchema.optional(),
71
81
  });
72
82
  export type Entry = z.infer<typeof EntrySchema>;
73
83
 
@@ -76,6 +86,9 @@ const ProviderIdSchema = z.enum(PROVIDER_IDS);
76
86
  export const CompatibilitySchema = z.object({ enabled: z.boolean().nullable(), source: z.string() });
77
87
  export type Compatibility = z.infer<typeof CompatibilitySchema>;
78
88
 
89
+ export const ProviderVersionSchema = z.object({ version: z.string().nullable(), source: z.enum(["host", "cli", "unknown"]) });
90
+ export type ProviderVersion = z.infer<typeof ProviderVersionSchema>;
91
+
79
92
  export const scanRpc = defineRpc({
80
93
  name: "customize.scan",
81
94
  input: z.object({ provider: ProviderIdSchema, projectRoot: z.string().nullable() }),
@@ -85,6 +98,7 @@ export const scanRpc = defineRpc({
85
98
  home: z.string(),
86
99
  entries: z.array(EntrySchema),
87
100
  compatibility: CompatibilitySchema.nullable(),
101
+ providerVersion: ProviderVersionSchema.optional(),
88
102
  scannedAt: z.string(),
89
103
  }),
90
104
  });