@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,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
  });
package/shared/i18n.ts CHANGED
@@ -26,6 +26,7 @@ export interface Messages {
26
26
  title: string;
27
27
  openBoard: string;
28
28
  provider: string;
29
+ providerVersion: (version: string) => string;
29
30
  compatibility: (state: "on" | "off" | "unknown" | "supported") => string;
30
31
  builtinProvider: string;
31
32
  noEnabledProvider: string;
@@ -37,6 +38,8 @@ export interface Messages {
37
38
  refresh: string;
38
39
  lastScanned: (date: string) => string;
39
40
  search: string;
41
+ showCards: string;
42
+ showList: string;
40
43
  skillInvocation: string;
41
44
  skillFilters: Record<"all" | "auto" | "manual", string>;
42
45
  categories: Record<Category, string>;
@@ -44,6 +47,10 @@ export interface Messages {
44
47
  statuses: Record<Status, string>;
45
48
  tags: Record<Tag, string>;
46
49
  agentPluginLabel: (version: string, validation: "valid" | "unsupported") => string;
50
+ tokens: (value: string) => string;
51
+ tokensOnInvoke: (value: string) => string;
52
+ tokensHint: (value: string) => string;
53
+ tokensOnInvokeHint: (value: string) => string;
47
54
  reason: (code: ReasonCode, value: string | undefined) => string;
48
55
  howItWorks: string;
49
56
  showDetails: string;
@@ -74,6 +81,7 @@ const en: Messages = {
74
81
  title: "Customize",
75
82
  openBoard: "Open Customize",
76
83
  provider: "Provider",
84
+ providerVersion: (version) => `Provider version: ${version}`,
77
85
  compatibility: (state) => state === "on" ? "Third-party skill directories enabled" : state === "off" ? "Third-party skill directories disabled" : state === "supported" ? "Supports shared skill directories" : "Third-party skill directory state unavailable",
78
86
  builtinProvider: "Built-in",
79
87
  noEnabledProvider: "No supported providers are enabled in Paseo.",
@@ -85,6 +93,8 @@ const en: Messages = {
85
93
  refresh: "Rescan",
86
94
  lastScanned: (date) => `Last scanned: ${date}`,
87
95
  search: "Filter by name or path",
96
+ showCards: "Switch to card view",
97
+ showList: "Switch to list view",
88
98
  skillInvocation: "Skill invocation",
89
99
  skillFilters: { all: "All", auto: "Auto", manual: "Manual" },
90
100
  categories: { instructions: "Instructions", rules: "Rules", skills: "Skills", mcp: "MCP", commands: "Commands", subagents: "Subagents", plugins: "Plugins" },
@@ -120,6 +130,10 @@ const en: Messages = {
120
130
  synced: "claude.ai sync",
121
131
  },
122
132
  agentPluginLabel: (version, validation) => `Agent Plugins ${version}${validation === "unsupported" ? " (unverified)" : ""}`,
133
+ tokens: (value) => `≈${value} tok`,
134
+ tokensOnInvoke: (value) => `+${value} on invoke`,
135
+ tokensHint: (value) => `Estimated tokens loaded without an action: ${value}. Skills, commands, and agents load their body only when used; MCP is not counted.`,
136
+ tokensOnInvokeHint: (value) => `Estimated tokens added when this entry is invoked: ${value}.`,
123
137
  reason: (code, value) => {
124
138
  switch (code) {
125
139
  case "frontmatter":
@@ -183,6 +197,7 @@ const zh: Messages = {
183
197
  title: "Customize",
184
198
  openBoard: "打开 Customize",
185
199
  provider: "Provider",
200
+ providerVersion: (version) => `Provider 版本:${version}`,
186
201
  compatibility: (state) => state === "on" ? "已开启第三方技能目录兼容" : state === "off" ? "已关闭第三方技能目录兼容" : state === "supported" ? "支持共享技能目录" : "第三方技能目录兼容状态未知",
187
202
  builtinProvider: "内置",
188
203
  noEnabledProvider: "Paseo 中没有已启用且受 Customize 支持的 Provider。",
@@ -194,6 +209,8 @@ const zh: Messages = {
194
209
  refresh: "重新扫描",
195
210
  lastScanned: (date) => `上次扫描:${date}`,
196
211
  search: "按名称或路径筛选",
212
+ showCards: "切换为卡片视图",
213
+ showList: "切换为列表视图",
197
214
  skillInvocation: "技能调用方式",
198
215
  skillFilters: { all: "全部", auto: "自动", manual: "仅手动" },
199
216
  categories: { instructions: "指令", rules: "规则", skills: "Skills", mcp: "MCP", commands: "命令", subagents: "子代理", plugins: "插件" },
@@ -229,6 +246,10 @@ const zh: Messages = {
229
246
  synced: "claude.ai 同步",
230
247
  },
231
248
  agentPluginLabel: (version, validation) => `Agent Plugins ${version}${validation === "unsupported" ? "(未校验)" : ""}`,
249
+ tokens: (value) => `≈${value} tok`,
250
+ tokensOnInvoke: (value) => `+${value} 调用时`,
251
+ tokensHint: (value) => `无需操作即加载的 token 估算:${value}。Skills、命令与子代理只在被调用时加载正文;MCP 不计入。`,
252
+ tokensOnInvokeHint: (value) => `被调用时额外加载的 token 估算:${value}。`,
232
253
  reason: (code, value) => {
233
254
  switch (code) {
234
255
  case "frontmatter":
@@ -297,3 +318,11 @@ export function formatBytes(bytes: number): string {
297
318
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`;
298
319
  return `${(bytes / 1024 / 1024).toFixed(1)} MiB`;
299
320
  }
321
+
322
+ /** Compact token count: exact below 1k, one decimal below 10k, integer k, one decimal M. */
323
+ export function formatTokenCount(tokens: number): string {
324
+ if (tokens < 1_000) return String(tokens);
325
+ if (tokens < 10_000) return `${(tokens / 1_000).toFixed(1)}k`;
326
+ if (tokens < 1_000_000) return `${Math.round(tokens / 1_000)}k`;
327
+ return `${(tokens / 1_000_000).toFixed(1)}M`;
328
+ }
@@ -1,5 +1,5 @@
1
1
  import { ACP_CONFIGS, type AcpConfig, type AcpProviderId } from "./acp-configs.ts";
2
- import { CATEGORIES, type Category, type Compatibility, type Scope } from "./contracts.ts";
2
+ import { CATEGORIES, type Category, type Compatibility, type ProviderVersion, type Scope } from "./contracts.ts";
3
3
  import { PROVIDER_IDS, type ProviderId } from "./providers.ts";
4
4
 
5
5
  /** Bilingual static copy; the client picks by app language. */
@@ -257,8 +257,8 @@ const BASE_MECHANISMS: Partial<Record<ProviderId, Partial<Record<Category, Mecha
257
257
  { scope: "user", path: "~/.claude/skills · ~/.agents/skills" },
258
258
  ],
259
259
  notes: [
260
- L("Every discovered, permitted skill is advertised automatically; there is no per-skill manual-only switch in OpenCode 1.18. The body loads on demand through the skill tool.", "OpenCode 1.18 会自动向模型列出所有已发现且获准使用的技能;不支持单个技能设为仅手动发现。正文仍由 skill 工具按需加载。"),
261
- L("`permission.skill` patterns: deny hides a skill, ask prompts first.", "`permission.skill` 通配:deny 隐藏,ask 先确认。"),
260
+ L("OpenCode v2: `metadata.opencode/autoinvoke: false` hides a skill from the model's available list; it can still be loaded explicitly by ID. Other agents' `disable-model-invocation` is ignored.", "OpenCode v2:`metadata.opencode/autoinvoke: false` 隐藏模型可用列表中的技能,仍可按 ID 显式加载;忽略其他 agent 的 `disable-model-invocation`。"),
261
+ L("Skill permissions: v1 uses `permission.skill`, v2 uses `permissions[]`. deny hides and blocks loading; ask prompts first. The body loads on demand through the skill tool.", "Skill 权限:v1 使用 `permission.skill`,v2 使用 `permissions[]`。deny 隐藏并禁止加载,ask 先确认;正文仍由 skill 工具按需加载。"),
262
262
  ],
263
263
  },
264
264
  mcp: {
@@ -359,8 +359,18 @@ export const MECHANISMS = Object.fromEntries(PROVIDER_IDS.map((id) => [
359
359
  ])) as Record<ProviderId, Record<Category, Mechanism>>;
360
360
 
361
361
  /** Reflect local compatibility switches in the discovery explanation. */
362
- export function mechanismFor(provider: ProviderId, category: Category, compatibility: Compatibility | null | undefined): Mechanism {
363
- const base = MECHANISMS[provider][category];
362
+ export function mechanismFor(provider: ProviderId, category: Category, compatibility: Compatibility | null | undefined, providerVersion?: ProviderVersion): Mechanism {
363
+ let base = MECHANISMS[provider][category];
364
+ if (provider === "opencode" && category === "skills") {
365
+ const version = providerVersion?.version;
366
+ const invocation = version && Number(version.split(".")[0]) < 2
367
+ ? L("OpenCode v1 advertises every discovered, permitted skill automatically; v2's `metadata.opencode/autoinvoke` and other agents' `disable-model-invocation` are ignored.",
368
+ "OpenCode v1 会自动列出所有已发现且获准使用的技能;忽略 v2 的 `metadata.opencode/autoinvoke` 和其他 agent 的 `disable-model-invocation`。")
369
+ : base.notes[0]!;
370
+ const unknown = L("Skills with `metadata.opencode/autoinvoke: false` await version confirmation; this switch requires v2.",
371
+ "带 `metadata.opencode/autoinvoke: false` 的技能待版本确认,此开关需要 v2。");
372
+ base = { ...base, notes: [...(!version ? [unknown] : []), invocation, ...base.notes.slice(1)] };
373
+ }
364
374
  if (!compatibility || !(provider === "cursor" && (category === "skills" || category === "subagents")
365
375
  || provider === "opencode" && category === "skills")) return base;
366
376
  const isCursor = provider === "cursor";
@@ -10,5 +10,6 @@ export const selectionSettings = defineSettings({
10
10
  schema: z.object({
11
11
  provider: z.enum(PROVIDER_IDS).default("claude"),
12
12
  projectRoot: z.string().nullable().default(null),
13
+ layout: z.enum(["list", "card"]).default("list"),
13
14
  }),
14
15
  });