@shelken/pi-auto-model-prompts 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +59 -0
  3. package/index.ts +138 -0
  4. package/package.json +40 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 shelken
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # pi-auto-model-prompts
2
+
3
+ 按当前模型 ID 注入额外 system prompt。在 `before_agent_start` 以 `# AUTO MODEL PROMPT(模型特别规则)` 标题追加到末尾。
4
+
5
+ ## 安装
6
+
7
+ ```bash
8
+ pi install npm:@shelken/pi-auto-model-prompts
9
+ ```
10
+
11
+ ## 配置
12
+
13
+ 可选:
14
+
15
+ - 项目:`.pi/extensions/pi-auto-model-prompts/config.json`
16
+ - 全局:`{pi-agent-dir}/extensions/pi-auto-model-prompts/config.json`
17
+
18
+ ```json
19
+ {
20
+ "enabled": true,
21
+ "liveReload": false
22
+ }
23
+ ```
24
+
25
+ | 字段 | 默认 | 说明 |
26
+ |---|---|---|
27
+ | `enabled` | `true` | 是否注入 |
28
+ | `liveReload` | `false` | `true`:每轮重读文件;`false`:按模型缓存,改文件需 `/reload` |
29
+
30
+ 项目级同名字段覆盖全局。
31
+
32
+ ## Prompt 文件
33
+
34
+ ```text
35
+ .pi/auto-model-prompts/ # 项目,优先
36
+ {pi-agent-dir}/auto-model-prompts/ # 全局
37
+ ```
38
+
39
+ 文件名(去掉 `.md`)即匹配规则:
40
+
41
+ | 规则 | 例 | 说明 |
42
+ |---|---|---|
43
+ | 精确 | `gpt-5.5.md` | 模型 ID 完全一致 |
44
+ | 前缀 | `gpt-5.4*.md` / `kimi*.md` | 去掉末尾 `*` 后做前缀;更长前缀优先 |
45
+ | 兜底 | `*.md` | 匹配所有模型,优先级最低 |
46
+
47
+ 同一目录只注入**一个**非空匹配。项目目录无匹配才用全局。
48
+
49
+ ## 行为摘要
50
+
51
+ - `liveReload=false`(默认):同模型复用缓存,利于 prompt cache;改 `.md` 后 `/reload`
52
+ - `liveReload=true`:每轮扫盘,改文件下一轮生效
53
+ - 空文件忽略;内容会 `trim`
54
+
55
+ ## 验证
56
+
57
+ ```bash
58
+ bun --filter '@shelken/pi-auto-model-prompts' test
59
+ ```
package/index.ts ADDED
@@ -0,0 +1,138 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ // --- 类型 ---
7
+
8
+ interface Config {
9
+ enabled: boolean;
10
+ /**
11
+ * 是否在每次发消息时实时读取 prompt 文件(当前轮立即反映文件改动)。
12
+ * false 时只在 session_start(含 /reload)时读取一次并缓存,改文件后需 /reload 才生效。
13
+ */
14
+ liveReload: boolean;
15
+ }
16
+
17
+ const DEFAULT_CONFIG: Config = { enabled: true, liveReload: false };
18
+
19
+ const EXTENSION_NAME = "pi-auto-model-prompts";
20
+
21
+ type Prompt =
22
+ | { path: string; priority: number; kind: "exact"; modelId: string }
23
+ | { path: string; priority: number; kind: "prefix"; prefix: string }
24
+ | { path: string; priority: number; kind: "wildcard" };
25
+
26
+ // --- 配置加载 ---
27
+
28
+ export function getConfigPaths(cwd: string, homeDir = homedir()): string[] {
29
+ return [
30
+ join(homeDir, ".pi", "agent", "extensions", EXTENSION_NAME, "config.json"),
31
+ join(cwd, ".pi", "extensions", EXTENSION_NAME, "config.json"),
32
+ ];
33
+ }
34
+
35
+ export function loadConfig(cwd: string, homeDir = homedir()): Config {
36
+ const cfg: Config = { ...DEFAULT_CONFIG };
37
+
38
+ for (const p of getConfigPaths(cwd, homeDir)) {
39
+ if (!existsSync(p)) continue;
40
+ const parsed = JSON.parse(readFileSync(p, "utf-8"));
41
+ if (typeof parsed.enabled === "boolean") cfg.enabled = parsed.enabled;
42
+ if (typeof parsed.liveReload === "boolean") cfg.liveReload = parsed.liveReload;
43
+ }
44
+
45
+ return cfg;
46
+ }
47
+
48
+ export function getPromptDirs(cwd: string, homeDir = homedir()): string[] {
49
+ return [
50
+ join(cwd, ".pi", "auto-model-prompts"),
51
+ join(homeDir, ".pi", "agent", "auto-model-prompts"),
52
+ ];
53
+ }
54
+
55
+ // --- Prompt 扫描与匹配 ---
56
+
57
+ /**
58
+ * 扫描目录下 .md 文件,按优先级降序排列。
59
+ *
60
+ * 优先级:
61
+ * - 精确匹配(无 *):最高
62
+ * - 前缀匹配(以 * 结尾):前缀越长越具体
63
+ * - 通配 *.md:最低
64
+ */
65
+ function scanPrompts(dir: string): Prompt[] {
66
+ if (!existsSync(dir)) return [];
67
+
68
+ return readdirSync(dir)
69
+ .filter((f) => f.endsWith(".md"))
70
+ .map((f) => {
71
+ const name = f.slice(0, -3);
72
+ if (name === "*") return { path: join(dir, f), priority: 0, kind: "wildcard" as const };
73
+ if (name.endsWith("*")) {
74
+ const prefix = name.slice(0, -1);
75
+ return { path: join(dir, f), priority: 10_000 + prefix.length, kind: "prefix" as const, prefix };
76
+ }
77
+ return { path: join(dir, f), priority: 20_000 + name.length, kind: "exact" as const, modelId: name };
78
+ })
79
+ .sort((a, b) => b.priority - a.priority);
80
+ }
81
+
82
+ function isMatch(modelId: string, prompt: Prompt): boolean {
83
+ const mid = modelId.toLowerCase();
84
+ if (prompt.kind === "exact") return mid === prompt.modelId.toLowerCase();
85
+ if (prompt.kind === "prefix") return mid.startsWith(prompt.prefix.toLowerCase());
86
+ return true;
87
+ }
88
+
89
+ function matchPrompt(modelId: string, prompts: Prompt[]): string | undefined {
90
+ for (const prompt of prompts) {
91
+ if (!isMatch(modelId, prompt)) continue;
92
+
93
+ const content = readFileSync(prompt.path, "utf-8").trim();
94
+ if (content) return content;
95
+ }
96
+ return undefined;
97
+ }
98
+
99
+ export function findPrompt(modelId: string, dirs: string[]): string | undefined {
100
+ for (const dir of dirs) {
101
+ const content = matchPrompt(modelId, scanPrompts(dir));
102
+ if (content) return content;
103
+ }
104
+ return undefined;
105
+ }
106
+
107
+ // --- 插件入口 ---
108
+
109
+ export default function (pi: ExtensionAPI) {
110
+ let config: Config = { ...DEFAULT_CONFIG };
111
+ // 懒加载缓存:仅在 before_agent_start 时填充 / 刷新,不在 session_start 预热。
112
+ // 缓存同时记录「为哪个模型缓存」,模型变化时自动失效。
113
+ let cachedPrompt: string | undefined;
114
+ let cachedForModelId: string | undefined;
115
+
116
+ pi.on("session_start", (_event, ctx) => {
117
+ config = loadConfig(ctx.cwd);
118
+ });
119
+
120
+ pi.on("before_agent_start", (event, ctx) => {
121
+ if (config.enabled === false) return;
122
+
123
+ const modelId = ctx.model?.id;
124
+ if (!modelId) return;
125
+
126
+ // liveReload=true 每次实时读;liveReload=false 仅在模型变化时重读。
127
+ // 不响应 model_select:所有判断和读取都集中在这里,避免缓存提前变动。
128
+ if (config.liveReload || modelId !== cachedForModelId) {
129
+ cachedPrompt = findPrompt(modelId, getPromptDirs(ctx.cwd));
130
+ cachedForModelId = modelId;
131
+ }
132
+ if (!cachedPrompt) return;
133
+
134
+ return {
135
+ systemPrompt: `${event.systemPrompt}\n\n# AUTO MODEL PROMPT(模型特别规则)\n\n${cachedPrompt}`,
136
+ };
137
+ });
138
+ }
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@shelken/pi-auto-model-prompts",
3
+ "version": "0.2.1",
4
+ "description": "Inject model-specific system prompts into pi turns from local Markdown files.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "files": [
8
+ "index.ts"
9
+ ],
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/shelken/pi-extensions.git",
13
+ "directory": "extensions/pi-auto-model-prompts"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "scripts": {
19
+ "test": "vitest run *.test.ts"
20
+ },
21
+ "keywords": [
22
+ "pi-package",
23
+ "pi-extension",
24
+ "system-prompt",
25
+ "prompt-cache"
26
+ ],
27
+ "pi": {
28
+ "extensions": [
29
+ "./index.ts"
30
+ ]
31
+ },
32
+ "peerDependencies": {
33
+ "@earendil-works/pi-coding-agent": "*"
34
+ },
35
+ "peerDependenciesMeta": {
36
+ "@earendil-works/pi-coding-agent": {
37
+ "optional": true
38
+ }
39
+ }
40
+ }