@koinzhang/paseo-plugin-customize 0.2.0 → 0.3.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,74 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { detectProviderVersion, parseProviderVersion } from "./provider-version.ts";
4
+ import { PROVIDER_IDS } from "../shared/providers.ts";
5
+
6
+ test("OpenCode version parsing accepts CLI formats and rejects diagnostic error numbers", () => {
7
+ for (const [output, expected] of [
8
+ ["1.18.32\n", "1.18.32"], ["v2.0.0", "2.0.0"], ["opencode v2.0.18\n", "2.0.18"],
9
+ ["opencode v2.0.0-beta.1+local", "2.0.0-beta.1+local"],
10
+ ["error: command 2.0.18 failed", null], ["/opt/opencode/2.0.18/bin", null], ["unknown", null], ["2.0", null],
11
+ ] as const) assert.equal(parseProviderVersion("opencode", output), expected);
12
+ });
13
+
14
+ test("provider versions support product labels, wrappers and date-based Cursor builds", () => {
15
+ for (const [provider, output, expected] of [
16
+ ["claude", "2.1.0 (Claude Code)", "2.1.0"], ["claude", "@tencent/tclaude 0.1.8", "0.1.8"],
17
+ ["codex", "codex-cli 0.157.1", "0.157.1"], ["cursor", "2026.09.26-dd393fe", "2026.09.26-dd393fe"],
18
+ ["copilot", "GitHub Copilot CLI 0.0.400", "0.0.400"], ["pi", "0.87.1", "0.87.1"], ["omp", "omp/18.3.5", "18.3.5"],
19
+ ["gemini", "0.52.0", "0.52.0"], ["kimi", "kimi, version 1.0.0", null],
20
+ ["codex", "error: command 0.157.1 failed", null], ["cursor", "/opt/cursor/2026.09.26-dd393fe", null],
21
+ ["omp", "error 18.3.5", null], ["pi", "unknown", null],
22
+ ] as const) assert.equal(parseProviderVersion(provider, output), expected, output);
23
+ });
24
+
25
+ test("host diagnostic wins over a different PATH CLI version", async () => {
26
+ const result = await detectProviderVersion("opencode", async (provider) => {
27
+ assert.equal(provider, "opencode");
28
+ return { provider, diagnostic: "OpenCode\n Configured command: /custom/opencode\n Version: opencode v2.0.18\n Auth: Not checked", requestId: "test" };
29
+ }, async () => { throw new Error("Fallback must not run"); });
30
+ assert.deepEqual(result, { version: "2.0.18", source: "host" });
31
+ });
32
+
33
+ test("missing, failed, unparseable and timed-out host diagnostics use a bounded CLI fallback", async () => {
34
+ const fallback = async (command: string, args: string[], options: { timeout: number; maxBuffer: number }) => {
35
+ assert.equal(command, "opencode");
36
+ assert.deepEqual(args, ["--version"]);
37
+ assert.equal(options.timeout, 3000);
38
+ assert.equal(options.maxBuffer, 32 * 1024);
39
+ return { stdout: "opencode v2.0.18" };
40
+ };
41
+ const missingVersion = async (provider: string) => ({ provider, diagnostic: "Version: error: 2.0.18 failed", requestId: "test" });
42
+ const unavailable = async () => { throw new Error("Host unavailable"); };
43
+ const hanging = () => new Promise<never>(() => {});
44
+ for (const diagnostic of [undefined, missingVersion, unavailable, hanging]) {
45
+ assert.deepEqual(await detectProviderVersion("opencode", diagnostic, fallback, 10), { version: "2.0.18", source: "cli" });
46
+ }
47
+ });
48
+
49
+ test("failed or unparseable CLI versions stay unknown without failing scans", async () => {
50
+ for (const run of [async () => { throw new Error("ENOENT"); }, async () => ({ stdout: "unknown" })]) {
51
+ assert.deepEqual(await detectProviderVersion("opencode", undefined, run), { version: null, source: "unknown" });
52
+ }
53
+ });
54
+
55
+ test("all Customize providers use their own host diagnostic, preserving configured overrides", async () => {
56
+ for (const provider of PROVIDER_IDS) {
57
+ const result = await detectProviderVersion(provider, async (requested) => {
58
+ assert.equal(requested, provider);
59
+ return { provider, diagnostic: "Provider\n Version: 1.2.3", requestId: "test" };
60
+ }, async () => { throw new Error("Fallback must not run"); });
61
+ assert.deepEqual(result, { version: "1.2.3", source: "host" });
62
+ }
63
+ });
64
+
65
+ test("CLI fallbacks use actual binary names and never install ACP packages", async () => {
66
+ for (const [provider, binary] of [["cursor", "cursor-agent"], ["codebuddy-code", "codebuddy"], ["kiro", "kiro-cli"], ["qwen-code", "qwen"]] as const) {
67
+ const result = await detectProviderVersion(provider, undefined, async (command, args) => {
68
+ assert.equal(command, binary);
69
+ assert.deepEqual(args, ["--version"]);
70
+ return { stdout: "1.2.3" };
71
+ });
72
+ assert.deepEqual(result, { version: "1.2.3", source: "cli" });
73
+ }
74
+ });
@@ -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
+ });