@aiti-ai/ext-shared 0.0.0-stage → 0.1.8
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.
- package/LICENSE +21 -0
- package/agent-accounts.test.mjs +227 -0
- package/agent-accounts.ts +324 -0
- package/agent-capability-contract.test.mjs +129 -0
- package/agent-interaction.test.mjs +194 -0
- package/agent-interaction.ts +340 -0
- package/agent-launch.test.mjs +262 -0
- package/agent-spawn-env.test.mjs +169 -0
- package/agent-spawn-env.ts +548 -0
- package/aiti-editor-inject.mjs +49 -0
- package/backend-queue.test.mjs +336 -0
- package/backend-queue.ts +469 -0
- package/blob-save-route.ts +128 -0
- package/cbc-model-catalog.ts +86 -0
- package/check-client.mjs +273 -0
- package/check-ext-globals.mjs +144 -0
- package/controlled-login-dialog.mjs +270 -0
- package/controlled-login.mjs +398 -0
- package/controlled-login.test.mjs +466 -0
- package/convert-saveas.test.mjs +39 -0
- package/convert-saveas.ts +170 -0
- package/copy-client-bundle.mjs +39 -0
- package/cursor-cli-store.ts +377 -0
- package/dedupe-fetch.test.mjs +71 -0
- package/dedupe-fetch.ts +58 -0
- package/deploy-commit.mjs +52 -0
- package/dev-pack.mjs +246 -0
- package/dock-icons.ts +127 -0
- package/esbuild-bin.test.mjs +53 -0
- package/esbuild-bin.ts +66 -0
- package/exec-async.test.mjs +86 -0
- package/exec-async.ts +179 -0
- package/ext-display-names.ts +91 -0
- package/ext-entry-contracts.test.mjs +131 -0
- package/ext-float-dock-core.test.mjs +348 -0
- package/ext-float-dock-core.ts +783 -0
- package/ext-float-dock-lite.ts +52 -0
- package/ext-float-dock.test.mjs +286 -0
- package/ext-float-dock.ts +740 -0
- package/ext-icons-deploy.mjs +24 -0
- package/ext-lazy.test.mjs +186 -0
- package/ext-lazy.tsx +183 -0
- package/ext-model-state.test.mjs +272 -0
- package/ext-model-state.ts +324 -0
- package/ext-protocol.mjs +113 -0
- package/ext-protocol.test.mjs +88 -0
- package/ext-session-usage.test.mjs +219 -0
- package/ext-session-usage.ts +507 -0
- package/external-cli-governance.ts +153 -0
- package/git-ops-client/api.mjs +56 -0
- package/git-ops-client/branch-panel.tsx +987 -0
- package/git-ops-client/i18n.mjs +328 -0
- package/host-tools-allow.test.mjs +46 -0
- package/host-tools-allow.ts +84 -0
- package/icons/alert.svg +1 -0
- package/icons/bookmark.svg +1 -0
- package/icons/bot.svg +1 -0
- package/icons/chart-column.svg +1 -0
- package/icons/check-circle.svg +1 -0
- package/icons/clipboard-list.svg +1 -0
- package/icons/clock.svg +1 -0
- package/icons/coffee.svg +1 -0
- package/icons/edit.svg +1 -0
- package/icons/eye.svg +1 -0
- package/icons/git-branch.svg +1 -0
- package/icons/git-commit-horizontal.svg +1 -0
- package/icons/globe.svg +1 -0
- package/icons/history.svg +1 -0
- package/icons/import.svg +1 -0
- package/icons/inbox.svg +1 -0
- package/icons/key-round.svg +1 -0
- package/icons/layout-grid.svg +1 -0
- package/icons/mail.svg +1 -0
- package/icons/message-circle.svg +1 -0
- package/icons/message-square.svg +1 -0
- package/icons/meter-vertical.svg +1 -0
- package/icons/mic.svg +1 -0
- package/icons/monitor.svg +1 -0
- package/icons/pen-line.svg +1 -0
- package/icons/plug.svg +1 -0
- package/icons/radio-dot.svg +1 -0
- package/icons/radio.svg +1 -0
- package/icons/refresh.svg +1 -0
- package/icons/rocket.svg +1 -0
- package/icons/search.svg +1 -0
- package/icons/shield.svg +1 -0
- package/icons/sparkles.svg +1 -0
- package/icons/square-kanban.svg +1 -0
- package/icons/terminal.svg +1 -0
- package/icons/users.svg +1 -0
- package/icons/volume-2.svg +1 -0
- package/icons/wand.svg +1 -0
- package/icons/wrench.svg +1 -0
- package/icons/x-circle.svg +1 -0
- package/icons/x.svg +1 -0
- package/ignore-semantics.ts +76 -0
- package/lazy-loading-metrics.mjs +61 -0
- package/new-session-cwd.test.mjs +389 -0
- package/new-session-cwd.ts +253 -0
- package/open-viewer-window.ts +65 -0
- package/overlay-back-client.test.mjs +123 -0
- package/overlay-back-client.ts +87 -0
- package/package.json +65 -4
- package/pi-fork-rpc/README.md +12 -0
- package/pi-fork-rpc/cli-resolve.test.mjs +42 -0
- package/pi-fork-rpc/cli-resolve.ts +79 -0
- package/pi-fork-rpc/remote-queue.test.mjs +100 -0
- package/pi-fork-rpc/remote-queue.ts +140 -0
- package/pi-fork-rpc/spec.ts +106 -0
- package/pi-fork-rpc/wire.test.mjs +260 -0
- package/pi-fork-rpc/wire.ts +367 -0
- package/popup-anchor.ts +45 -0
- package/provider-priority-contract.test.mjs +55 -0
- package/reconcile-deps.mjs +41 -0
- package/reload-instances.mjs +60 -0
- package/seed-tool.test.mjs +95 -0
- package/seed-tool.ts +88 -0
- package/session-recycle.ts +109 -0
- package/shared-copy-sync.test.mjs +115 -0
- package/soffice-locate.ts +171 -0
- package/soffice-panel.ts +239 -0
- package/sync-dir.mjs +91 -0
- package/sync-dir.test.mjs +101 -0
- package/sync-gate.test.mjs +93 -0
- package/sync-mirror.test.mjs +85 -0
- package/task-list.test.mjs +91 -0
- package/task-list.ts +118 -0
- package/test-rm-rf.mjs +33 -0
- package/ui-dialogs.test.mjs +198 -0
- package/ui-dialogs.ts +310 -0
- package/README.md +0 -3
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ext-model-state — 外部 agent 会话的「临时模型状态文件」共享模块(权威源)。
|
|
3
|
+
*
|
|
4
|
+
* 每个外部 agent 会话 handle 一份 JSON:
|
|
5
|
+
* ~/.pi/agent/ext-agents/<agentKey>/<sanitized-handle-id>.json
|
|
6
|
+
*
|
|
7
|
+
* 职责(需求:启动或切换时,把 pi 的 models 存到临时配置文件,引导外部 agent):
|
|
8
|
+
* 1. 记录当前选中模型(selected)→ 各扩展 spawn 参数(--model/-m)从它派生,
|
|
9
|
+
* 会话重开/进程重启后模型选择不丢;
|
|
10
|
+
* 2. 携带合并模型目录(外部自身 + pi 的 models.json 扁平化)→
|
|
11
|
+
* getAvailableModels 从这里拿 pi 部分,模型选择器外部/pi 同屏分组;
|
|
12
|
+
* 3. 原子写(tmp + rename),坏 JSON/缺目录一律 fail-soft(返回 null/[]);
|
|
13
|
+
* 4. 每次写入顺手维护该 agent 的「上次使用模型」KV(`<agentKey>/_last-model.json`)——
|
|
14
|
+
* 各 agent 新建会话的默认模型(per-agent last used,对齐 pi 的 defaultModel 语义)
|
|
15
|
+
* 读它即可,不需要每个扩展自己记录/扫描。
|
|
16
|
+
*
|
|
17
|
+
* 本文件按部署单元复制进各扩展目录(aiti-*-agent/ext-model-state.ts),
|
|
18
|
+
* 修改后同步副本(与 cursor-cli-store.ts 同一模式)。
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
22
|
+
import { homedir } from "node:os";
|
|
23
|
+
import { join } from "node:path";
|
|
24
|
+
|
|
25
|
+
/** pi 的模型注册表(~/.pi/agent/models.json,{providers:{<key>:{models:[…]}}})。 */
|
|
26
|
+
export function piModelsConfigPath(): string {
|
|
27
|
+
return process.env.PI_MODELS_CONFIG_PATH || join(homedir(), ".pi", "agent", "models.json");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 读 pi models.json 并扁平化为合并目录条目(读不到/坏 JSON → [],fail-soft)。 */
|
|
31
|
+
export async function readPiModels(): Promise<ExtModelEntry[]> {
|
|
32
|
+
try {
|
|
33
|
+
const raw = await readFile(piModelsConfigPath(), "utf8");
|
|
34
|
+
return piModelsFromModelsConfig(JSON.parse(raw));
|
|
35
|
+
} catch {
|
|
36
|
+
return [];
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 合并目录条目:source 区分外部自身目录与 pi 目录。 */
|
|
41
|
+
export type ExtModelEntry = {
|
|
42
|
+
id: string;
|
|
43
|
+
provider: string;
|
|
44
|
+
label?: string;
|
|
45
|
+
source?: "ext" | "pi";
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export type ExtModelState = {
|
|
49
|
+
agentKey: string;
|
|
50
|
+
sessionId: string;
|
|
51
|
+
selected?: { provider: string; id: string };
|
|
52
|
+
models: ExtModelEntry[];
|
|
53
|
+
updatedAt: string;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/** 状态文件根目录(可用 EXT_MODEL_STATE_DIR 覆盖,测试用)。 */
|
|
57
|
+
export function extModelStateDir(): string {
|
|
58
|
+
return process.env.EXT_MODEL_STATE_DIR || join(homedir(), ".pi", "agent", "ext-agents");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** handle id → 安全文件名(复合 id 形如 claude:<uuid>,冒号/斜杠等一律消毒;无字母数字时回退 session)。 */
|
|
62
|
+
export function sanitizeId(id: string): string {
|
|
63
|
+
const cleaned = id.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 120);
|
|
64
|
+
return /[A-Za-z0-9]/.test(cleaned) ? cleaned : "session";
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function extModelStatePath(agentKey: string, sessionId: string): string {
|
|
68
|
+
return join(extModelStateDir(), sanitizeId(agentKey), `${sanitizeId(sessionId)}.json`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** 该 agent「上次使用模型」KV 文件名(agent 目录内保留名,不参与状态 GC/扫描)。 */
|
|
72
|
+
export const AGENT_LAST_MODEL_FILE = "_last-model.json";
|
|
73
|
+
|
|
74
|
+
export function agentLastModelPath(agentKey: string): string {
|
|
75
|
+
return join(extModelStateDir(), sanitizeId(agentKey), AGENT_LAST_MODEL_FILE);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 进程内 last-used 快照(agentKey → 最近一次已知值 + 文件 mtime):
|
|
80
|
+
* - 读:内存快照优先(不重读内容;命中时只做一次 mtime 校验——文件被删/被其它进程
|
|
81
|
+
* (dev/prod 双实例共享状态目录)改写才回退读 KV 文件),miss 时读文件并回填;
|
|
82
|
+
* - 写:同值重复写直接跳过(不落盘);命中时同样用 mtime 校验文件未被别处改写。
|
|
83
|
+
* 状态写入在 setModel/建会话时都会触发,同一模型反复读/写不应放大文件 IO。
|
|
84
|
+
*/
|
|
85
|
+
const lastModelCache = new Map<string, { provider: string; id: string; mtimeMs: number }>();
|
|
86
|
+
|
|
87
|
+
/** 测试钩子:清空进程内 last-used 快照(读/跳写行为跨用例隔离)。 */
|
|
88
|
+
export function resetAgentLastModelCacheForTests(): void {
|
|
89
|
+
lastModelCache.clear();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** 原子写「该 agent 上次使用的模型」(目录不存在自动建;同值重复写跳过;失败仅告警)。 */
|
|
93
|
+
export async function writeAgentLastModel(agentKey: string, selected: { provider: string; id: string }): Promise<void> {
|
|
94
|
+
const file = agentLastModelPath(agentKey);
|
|
95
|
+
const cached = lastModelCache.get(agentKey);
|
|
96
|
+
if (cached && cached.provider === selected.provider && cached.id === selected.id) {
|
|
97
|
+
try {
|
|
98
|
+
const st = await stat(file);
|
|
99
|
+
if (st.mtimeMs === cached.mtimeMs) return; // 未变且文件没被别处改写 → 不写
|
|
100
|
+
} catch { /* 文件被删/不可读 → 重写 */ }
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
await mkdir(join(file, ".."), { recursive: true });
|
|
104
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.${++writeSeq}.tmp`;
|
|
105
|
+
await writeFile(tmp, JSON.stringify({ agentKey, selected, updatedAt: new Date().toISOString() }, null, 2));
|
|
106
|
+
await rename(tmp, file);
|
|
107
|
+
const st = await stat(file).catch(() => null);
|
|
108
|
+
lastModelCache.set(agentKey, { provider: selected.provider, id: selected.id, mtimeMs: st?.mtimeMs ?? 0 });
|
|
109
|
+
} catch (e) {
|
|
110
|
+
console.warn(`[ext-model-state] last-model write failed (${file}):`, e instanceof Error ? e.message : e);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 读「该 agent 上次使用的模型」:内存快照优先(不读文件内容;命中时只做一次 mtime
|
|
116
|
+
* 校验——文件被删/被其它实例(dev/prod 共享目录)改写才回退读盘);miss 时读专用 KV
|
|
117
|
+
* (`_last-model.json`)并回填内存;存量安装(KV 尚未生成)回退扫描目录内 mtime 最新的
|
|
118
|
+
* 状态文件。缺失/损坏 → null(fail-soft)。调用方负责合法性校验(通道/目录内存在)。
|
|
119
|
+
*/
|
|
120
|
+
export async function readAgentLastUsedModel(agentKey: string): Promise<{ provider: string; id: string } | null> {
|
|
121
|
+
const file = agentLastModelPath(agentKey);
|
|
122
|
+
const cached = lastModelCache.get(agentKey);
|
|
123
|
+
if (cached) {
|
|
124
|
+
try {
|
|
125
|
+
const st = await stat(file);
|
|
126
|
+
if (st.mtimeMs === cached.mtimeMs) return { provider: cached.provider, id: cached.id };
|
|
127
|
+
} catch { /* 文件被删 → 落到下面读盘/回退扫描 */ }
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
const parsed = JSON.parse(await readFile(file, "utf8")) as { selected?: { provider?: unknown; id?: unknown } };
|
|
131
|
+
const selected = parsed?.selected;
|
|
132
|
+
if (selected && typeof selected.id === "string" && selected.id) {
|
|
133
|
+
const value = {
|
|
134
|
+
provider: typeof selected.provider === "string" && selected.provider ? selected.provider : agentKey,
|
|
135
|
+
id: selected.id,
|
|
136
|
+
};
|
|
137
|
+
const st = await stat(file).catch(() => null);
|
|
138
|
+
lastModelCache.set(agentKey, { ...value, mtimeMs: st?.mtimeMs ?? 0 });
|
|
139
|
+
return value;
|
|
140
|
+
}
|
|
141
|
+
} catch { /* KV 不存在/损坏 → 回退扫描 */ }
|
|
142
|
+
return readLatestSelectedModel(agentKey);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** 原子写状态(目录不存在自动建;失败仅告警——状态文件永不阻断主流程)。 */
|
|
146
|
+
let writeSeq = 0;
|
|
147
|
+
export async function writeExtModelState(state: ExtModelState): Promise<void> {
|
|
148
|
+
const file = extModelStatePath(state.agentKey, state.sessionId);
|
|
149
|
+
const dir = join(file, "..");
|
|
150
|
+
try {
|
|
151
|
+
await mkdir(dir, { recursive: true });
|
|
152
|
+
// 并发写防撞:同 pid 同毫秒的两次写不能共用同一个 tmp 名
|
|
153
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.${++writeSeq}.tmp`;
|
|
154
|
+
await writeFile(tmp, JSON.stringify({ ...state, updatedAt: new Date().toISOString() }, null, 2));
|
|
155
|
+
await rename(tmp, file);
|
|
156
|
+
// 顺手更新该 agent 的「上次使用模型」KV(专用小文件;前端/新建页默认项与 pi 的
|
|
157
|
+
// defaultModel 同语义)。写失败不阻断主流程——KV 缺失时读取端会回退 mtime 扫描。
|
|
158
|
+
if (state.selected?.id) await writeAgentLastModel(state.agentKey, state.selected);
|
|
159
|
+
} catch (e) {
|
|
160
|
+
console.warn(`[ext-model-state] write failed (${file}):`, e instanceof Error ? e.message : e);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
// 机会式 GC:写成功后顺手清理过期状态(不阻塞、失败静默)
|
|
164
|
+
void pruneExpiredStates(dir, file);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** 状态保留期:30 天未更新的会话状态视为陈旧(会话早已不存在)。 */
|
|
168
|
+
export const EXT_MODEL_STATE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
|
|
169
|
+
|
|
170
|
+
/** 目录级节流:每目录每进程至多扫一次(避免每次写都 stat 风暴)。 */
|
|
171
|
+
const prunedDirs = new Set<string>();
|
|
172
|
+
|
|
173
|
+
/** 删除目录下超过保留期的旧状态文件(keepFile 除外)。清理永不抛错。 */
|
|
174
|
+
export async function pruneExpiredStates(dir: string, keepFile?: string): Promise<number> {
|
|
175
|
+
if (prunedDirs.has(dir)) return 0;
|
|
176
|
+
prunedDirs.add(dir);
|
|
177
|
+
let removed = 0;
|
|
178
|
+
try {
|
|
179
|
+
const now = Date.now();
|
|
180
|
+
for (const f of await readdir(dir)) {
|
|
181
|
+
if (!f.endsWith(".json")) continue;
|
|
182
|
+
if (f === AGENT_LAST_MODEL_FILE) continue; // last-used KV 长期保留(不代表会话存在)
|
|
183
|
+
const p = join(dir, f);
|
|
184
|
+
if (p === keepFile) continue;
|
|
185
|
+
try {
|
|
186
|
+
const st = await stat(p);
|
|
187
|
+
if (now - st.mtimeMs > EXT_MODEL_STATE_RETENTION_MS) {
|
|
188
|
+
await rm(p, { force: true });
|
|
189
|
+
removed++;
|
|
190
|
+
}
|
|
191
|
+
} catch { /* 单文件失败不影响其余 */ }
|
|
192
|
+
}
|
|
193
|
+
} catch { /* 目录不存在等 —— 静默 */ }
|
|
194
|
+
return removed;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** 读状态;缺失/损坏返回 null(fail-soft)。 */
|
|
198
|
+
export async function readExtModelState(agentKey: string, sessionId: string): Promise<ExtModelState | null> {
|
|
199
|
+
try {
|
|
200
|
+
const raw = await readFile(extModelStatePath(agentKey, sessionId), "utf8");
|
|
201
|
+
const parsed = JSON.parse(raw) as ExtModelState;
|
|
202
|
+
if (!parsed || typeof parsed !== "object") return null;
|
|
203
|
+
return parsed;
|
|
204
|
+
} catch {
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* 读「该 agent 上次使用的模型」(per-agent last used,pi 的 defaultModel 同语义):
|
|
211
|
+
* 取 agentKey 目录下 mtime 最新的状态文件的 selected——状态文件在 createSession 与每次
|
|
212
|
+
* setModel 时写入,所以最新的那份即该 agent 最近一次实际使用的模型。
|
|
213
|
+
* 目录缺失/无文件/坏 JSON → null(fail-soft)。调用方负责合法性校验(通道/目录内存在)。
|
|
214
|
+
*/
|
|
215
|
+
export async function readLatestSelectedModel(agentKey: string): Promise<{ provider: string; id: string } | null> {
|
|
216
|
+
const dir = join(extModelStateDir(), sanitizeId(agentKey));
|
|
217
|
+
try {
|
|
218
|
+
const files = (await readdir(dir)).filter((f) => f.endsWith(".json") && f !== AGENT_LAST_MODEL_FILE);
|
|
219
|
+
let newest: { file: string; mtimeMs: number } | null = null;
|
|
220
|
+
for (const f of files) {
|
|
221
|
+
try {
|
|
222
|
+
const st = await stat(join(dir, f));
|
|
223
|
+
if (!newest || st.mtimeMs > newest.mtimeMs) newest = { file: f, mtimeMs: st.mtimeMs };
|
|
224
|
+
} catch { /* 单文件失败跳过 */ }
|
|
225
|
+
}
|
|
226
|
+
if (!newest) return null;
|
|
227
|
+
const parsed = JSON.parse(await readFile(join(dir, newest.file), "utf8")) as ExtModelState;
|
|
228
|
+
const selected = parsed?.selected;
|
|
229
|
+
if (!selected || typeof selected.id !== "string" || !selected.id) return null;
|
|
230
|
+
return {
|
|
231
|
+
provider: typeof selected.provider === "string" && selected.provider ? selected.provider : agentKey,
|
|
232
|
+
id: selected.id,
|
|
233
|
+
};
|
|
234
|
+
} catch {
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** 换绑真实 id(session_backend_ready):旧文件搬到新 id 名下。 */
|
|
240
|
+
export async function renameExtModelState(agentKey: string, fromId: string, toId: string): Promise<void> {
|
|
241
|
+
if (fromId === toId) return;
|
|
242
|
+
const from = extModelStatePath(agentKey, fromId);
|
|
243
|
+
const to = extModelStatePath(agentKey, toId);
|
|
244
|
+
try {
|
|
245
|
+
await mkdir(join(to, ".."), { recursive: true });
|
|
246
|
+
await rename(from, to);
|
|
247
|
+
} catch {
|
|
248
|
+
// 旧文件不存在(fresh 会话首次写)或跨设备——忽略,下次 write 覆盖
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** 删除状态(dispose 时调用可选;缺省保留供重开恢复)。 */
|
|
253
|
+
export async function removeExtModelState(agentKey: string, sessionId: string): Promise<void> {
|
|
254
|
+
try {
|
|
255
|
+
await rm(extModelStatePath(agentKey, sessionId), { force: true });
|
|
256
|
+
} catch { /* ignore */ }
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* pi 的 models.json({providers:{<key>:{apiKey,api,baseUrl,models:[{id,name,api,contextWindow,…}]}}})
|
|
261
|
+
* 扁平化为合并目录条目:provider 统一 "pi"(选择器独立分组),label 尾注协议/窗口。
|
|
262
|
+
*/
|
|
263
|
+
export function piModelsFromModelsConfig(config: unknown): ExtModelEntry[] {
|
|
264
|
+
const providers = (config as { providers?: Record<string, unknown> } | null)?.providers;
|
|
265
|
+
if (!providers || typeof providers !== "object") return [];
|
|
266
|
+
const out: ExtModelEntry[] = [];
|
|
267
|
+
for (const [provKey, prov] of Object.entries(providers as Record<string, unknown>)) {
|
|
268
|
+
const models = (prov as { models?: unknown }).models;
|
|
269
|
+
if (!Array.isArray(models)) continue;
|
|
270
|
+
for (const m of models as Array<Record<string, unknown>>) {
|
|
271
|
+
if (typeof m?.id !== "string" || !m.id) continue;
|
|
272
|
+
const bits: string[] = [];
|
|
273
|
+
if (typeof m.api === "string" && m.api) bits.push(String(m.api));
|
|
274
|
+
if (typeof m.contextWindow === "number" && m.contextWindow > 0) bits.push(`${Math.round(m.contextWindow / 1024)}k`);
|
|
275
|
+
out.push({
|
|
276
|
+
id: m.id,
|
|
277
|
+
provider: "pi",
|
|
278
|
+
label: bits.length > 0 ? `${String(m.name ?? m.id)} · ${bits.join(" · ")}` : String(m.name ?? m.id),
|
|
279
|
+
source: "pi",
|
|
280
|
+
});
|
|
281
|
+
void provKey; // pi 目录按模型平铺;来源 provider key 不进 UI(避免与 provider 分组语义冲突)
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
return out;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* 合并目录:外部自身条目在前(source:"ext"),pi 条目在后(source:"pi");
|
|
289
|
+
* 以 provider+id 去重(先到先得——外部自身目录优先)。
|
|
290
|
+
*/
|
|
291
|
+
export function mergeModelCatalogs(external: ExtModelEntry[], piModels: ExtModelEntry[]): ExtModelEntry[] {
|
|
292
|
+
const seen = new Set<string>();
|
|
293
|
+
const out: ExtModelEntry[] = [];
|
|
294
|
+
for (const m of [...external, ...piModels]) {
|
|
295
|
+
const key = `${m.provider}/${m.id}`;
|
|
296
|
+
if (seen.has(key)) continue;
|
|
297
|
+
seen.add(key);
|
|
298
|
+
out.push(m);
|
|
299
|
+
}
|
|
300
|
+
return out;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** 当前模型排最前的目录整理(选择器默认高亮当前项)。
|
|
304
|
+
* 目录内命中当前模型时整体前移(保留 label 等元数据——合成条目会丢 label 产生裸 ref 行);
|
|
305
|
+
* 不在目录中(如通道折叠前的旧 ref)才合成最小条目前置。 */
|
|
306
|
+
export function withCurrentFirst(models: ExtModelEntry[], current?: { id: string; provider: string; label?: string }): ExtModelEntry[] {
|
|
307
|
+
if (!current?.id) return models;
|
|
308
|
+
const idx = models.findIndex((m) => m.id === current.id && m.provider === current.provider);
|
|
309
|
+
if (idx < 0) return [{ ...current, source: "ext" as const }, ...models];
|
|
310
|
+
return [models[idx], ...models.slice(0, idx), ...models.slice(idx + 1)];
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* 静态目录把「上次使用的模型」置顶——只在目录内按 id 命中时前移(保留原条目的
|
|
315
|
+
* provider/label),不合成条目。静态目录供新建页默认项(前端取 list[0]),
|
|
316
|
+
* 若用 withCurrentFirst 会为 provider 不匹配的 pi 模型合成裸条目 → 列表重复。
|
|
317
|
+
* 无命中/已在首位 → 原数组。
|
|
318
|
+
*/
|
|
319
|
+
export function withLastUsedFirst(models: ExtModelEntry[], lastUsedId?: string | null): ExtModelEntry[] {
|
|
320
|
+
if (!lastUsedId) return models;
|
|
321
|
+
const idx = models.findIndex((m) => m.id === lastUsedId);
|
|
322
|
+
if (idx <= 0) return models;
|
|
323
|
+
return [models[idx], ...models.slice(0, idx), ...models.slice(idx + 1)];
|
|
324
|
+
}
|
package/ext-protocol.mjs
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-web 扩展协议版本 —— canonical 定义(pi-work 侧)。
|
|
3
|
+
*
|
|
4
|
+
* 用途:
|
|
5
|
+
* - 扩展在 package.json 声明 `"aitiExtProtocol": "1.0"`(字符串 MAJOR.MINOR);
|
|
6
|
+
* - 检查脚本 / extman / 未来安装筛查器共用本模块的解析与状态计算;
|
|
7
|
+
* - 宿主 pi-web 镜像实现 `lib/ext/protocol.ts`(同语义,规范见 docs/pi-web-ext-protocol.md)。
|
|
8
|
+
*
|
|
9
|
+
* 本文件被 extman deploy 拷贝进扩展目录(ext-protocol.mjs)供运行时使用——保持零依赖纯 ESM。
|
|
10
|
+
* bump 规则(docs/pi-web-ext-protocol.md §2.1):仅**明显改动已有接口且影响现有功能**时 MAJOR+1;
|
|
11
|
+
* 纯增项不 bump。bump 流程见规范 §7(改本文件常量 + 变更记录 + 迁移手册;宿主镜像同步改)。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** 当前协议版本(字符串 MAJOR.MINOR)。 */
|
|
15
|
+
export const EXT_PROTOCOL_VERSION = "1.0";
|
|
16
|
+
|
|
17
|
+
/** 宿主最低支持的协议 MAJOR(声明 major < 此值 = incompatible;首次 bump 时按兼容策略提高)。 */
|
|
18
|
+
export const EXT_PROTOCOL_MIN_MAJOR = 1;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 解析协议版本声明。仅接受字符串 "MAJOR.MINOR"(数字类型/其他格式 → null)。
|
|
22
|
+
* @param {unknown} v
|
|
23
|
+
* @returns {{ major: number, minor: number, raw: string } | null}
|
|
24
|
+
*/
|
|
25
|
+
export function parseExtProtocol(v) {
|
|
26
|
+
if (typeof v !== "string") return null;
|
|
27
|
+
const s = v.trim();
|
|
28
|
+
const m = /^(\d+)\.(\d+)$/.exec(s);
|
|
29
|
+
if (!m) return null;
|
|
30
|
+
return { major: Number(m[1]), minor: Number(m[2]), raw: s };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 声明 → 当前协议之间的迁移手册引用(逐跳;声明缺失视为 legacy)。
|
|
35
|
+
* 例:声明 "1.0" + 当前 "2.1" → ["v1-to-v2"];缺失 + 当前 "1.0" → ["legacy-to-v1"]。
|
|
36
|
+
* 手册位于 pi-web-ext/aiti-extman/skills/ext-protocol-upgrade/references/。
|
|
37
|
+
* @param {unknown} declared
|
|
38
|
+
* @param {{ current?: string }} [opts]
|
|
39
|
+
* @returns {string[]}
|
|
40
|
+
*/
|
|
41
|
+
export function extProtocolUpgradeRefs(declared, opts = {}) {
|
|
42
|
+
const cur = parseExtProtocol(opts.current ?? EXT_PROTOCOL_VERSION) ?? parseExtProtocol(EXT_PROTOCOL_VERSION);
|
|
43
|
+
if (!cur) return [];
|
|
44
|
+
const d = parseExtProtocol(declared);
|
|
45
|
+
const refs = [];
|
|
46
|
+
// 声明缺失/非法/0.x(版本化前谱系)→ 先补 legacy 手册;迁移手册按 major 逐跳。
|
|
47
|
+
const legacy = !d || d.major < 1;
|
|
48
|
+
let fromMajor = legacy ? 1 : d.major;
|
|
49
|
+
if (legacy) refs.push("legacy-to-v1");
|
|
50
|
+
for (let m = fromMajor; m < cur.major; m++) refs.push(`v${m}-to-v${m + 1}`);
|
|
51
|
+
return refs;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 兼容状态计算(唯一裁决口径)。
|
|
56
|
+
*
|
|
57
|
+
* state:
|
|
58
|
+
* ok 同 major(扩展 minor 高于宿主 minor 时 minorAhead=true,仅黄提示)
|
|
59
|
+
* stale 声明 major < 当前 major 且 >= minMajor(宿主保留兼容层,仍可运行)
|
|
60
|
+
* incompatible 声明 major < minMajor(宿主已不再兼容)
|
|
61
|
+
* too_new 声明 major > 当前 major(宿主过旧,需升级 pi-web)
|
|
62
|
+
* missing 无声明(版本化前遗留,视为 legacy v0)
|
|
63
|
+
* invalid 声明非法(非 "M.m" 字符串)
|
|
64
|
+
*
|
|
65
|
+
* @param {unknown} declared
|
|
66
|
+
* @param {{ current?: string, minMajor?: number }} [opts]
|
|
67
|
+
* @returns {{
|
|
68
|
+
* state: "ok"|"stale"|"incompatible"|"too_new"|"missing"|"invalid",
|
|
69
|
+
* declared: string|null,
|
|
70
|
+
* current: string,
|
|
71
|
+
* minSupported: string,
|
|
72
|
+
* minorAhead: boolean,
|
|
73
|
+
* needsUpgrade: boolean,
|
|
74
|
+
* upgradeRefs: string[],
|
|
75
|
+
* detail?: string,
|
|
76
|
+
* }}
|
|
77
|
+
*/
|
|
78
|
+
export function extProtocolInfo(declared, opts = {}) {
|
|
79
|
+
const current = parseExtProtocol(opts.current ?? EXT_PROTOCOL_VERSION) ?? { major: 1, minor: 0, raw: EXT_PROTOCOL_VERSION };
|
|
80
|
+
const minMajor = Number.isInteger(opts.minMajor) ? opts.minMajor : EXT_PROTOCOL_MIN_MAJOR;
|
|
81
|
+
const minSupported = `${minMajor}.0`;
|
|
82
|
+
const base = {
|
|
83
|
+
declared: typeof declared === "string" ? declared : null,
|
|
84
|
+
current: current.raw,
|
|
85
|
+
minSupported,
|
|
86
|
+
minorAhead: false,
|
|
87
|
+
needsUpgrade: false,
|
|
88
|
+
upgradeRefs: [],
|
|
89
|
+
};
|
|
90
|
+
if (declared === undefined || declared === null || declared === "") {
|
|
91
|
+
return { ...base, state: "missing", needsUpgrade: true, upgradeRefs: extProtocolUpgradeRefs(declared, opts), detail: "未声明协议版本(legacy)" };
|
|
92
|
+
}
|
|
93
|
+
const d = parseExtProtocol(declared);
|
|
94
|
+
if (!d) {
|
|
95
|
+
return { ...base, state: "invalid", needsUpgrade: true, upgradeRefs: extProtocolUpgradeRefs(declared, opts), detail: '声明必须是 "MAJOR.MINOR" 字符串' };
|
|
96
|
+
}
|
|
97
|
+
if (d.major > current.major) {
|
|
98
|
+
return { ...base, state: "too_new", detail: `扩展声明协议 ${d.raw} 高于宿主 ${current.raw}——请升级 pi-web 宿主` };
|
|
99
|
+
}
|
|
100
|
+
if (d.major < minMajor) {
|
|
101
|
+
return { ...base, state: "incompatible", needsUpgrade: true, upgradeRefs: extProtocolUpgradeRefs(declared, opts), detail: `声明 ${d.raw} 低于宿主最低支持 ${minSupported}` };
|
|
102
|
+
}
|
|
103
|
+
if (d.major < current.major) {
|
|
104
|
+
return { ...base, state: "stale", needsUpgrade: true, upgradeRefs: extProtocolUpgradeRefs(declared, opts), detail: `声明 ${d.raw} 落后当前 ${current.raw}` };
|
|
105
|
+
}
|
|
106
|
+
const minorAhead = d.minor > current.minor;
|
|
107
|
+
return {
|
|
108
|
+
...base,
|
|
109
|
+
state: "ok",
|
|
110
|
+
minorAhead,
|
|
111
|
+
detail: minorAhead ? `扩展用到 ${d.raw} 的新增能力(宿主 ${current.raw})——宿主可升级以启用` : undefined,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ext-protocol 单测(纯函数)。
|
|
3
|
+
* 运行:node scripts/test-web-ext.mjs --only _shared
|
|
4
|
+
*/
|
|
5
|
+
import { test } from "node:test";
|
|
6
|
+
import assert from "node:assert/strict";
|
|
7
|
+
import {
|
|
8
|
+
EXT_PROTOCOL_VERSION,
|
|
9
|
+
EXT_PROTOCOL_MIN_MAJOR,
|
|
10
|
+
parseExtProtocol,
|
|
11
|
+
extProtocolInfo,
|
|
12
|
+
extProtocolUpgradeRefs,
|
|
13
|
+
} from "./ext-protocol.mjs";
|
|
14
|
+
|
|
15
|
+
test("常量:当前版本与最低支持 major", () => {
|
|
16
|
+
assert.equal(EXT_PROTOCOL_VERSION, "1.0");
|
|
17
|
+
assert.equal(EXT_PROTOCOL_MIN_MAJOR, 1);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test("parseExtProtocol:合法字符串", () => {
|
|
21
|
+
assert.deepEqual(parseExtProtocol("1.0"), { major: 1, minor: 0, raw: "1.0" });
|
|
22
|
+
assert.deepEqual(parseExtProtocol(" 2.13 "), { major: 2, minor: 13, raw: "2.13" });
|
|
23
|
+
assert.deepEqual(parseExtProtocol("10.7"), { major: 10, minor: 7, raw: "10.7" });
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test("parseExtProtocol:非法输入(含数字类型)", () => {
|
|
27
|
+
assert.equal(parseExtProtocol(1.0), null); // 数字必须拒绝(1.10 被吃成 1.1 的经典坑)
|
|
28
|
+
assert.equal(parseExtProtocol(1), null);
|
|
29
|
+
assert.equal(parseExtProtocol("1"), null); // 必须 MAJOR.MINOR
|
|
30
|
+
assert.equal(parseExtProtocol("1.0.0"), null);
|
|
31
|
+
assert.equal(parseExtProtocol("v1.0"), null);
|
|
32
|
+
assert.equal(parseExtProtocol(""), null);
|
|
33
|
+
assert.equal(parseExtProtocol(null), null);
|
|
34
|
+
assert.equal(parseExtProtocol(undefined), null);
|
|
35
|
+
assert.equal(parseExtProtocol({}), null);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test("extProtocolInfo:ok / minorAhead", () => {
|
|
39
|
+
const ok = extProtocolInfo("1.0");
|
|
40
|
+
assert.equal(ok.state, "ok");
|
|
41
|
+
assert.equal(ok.needsUpgrade, false);
|
|
42
|
+
assert.deepEqual(ok.upgradeRefs, []);
|
|
43
|
+
|
|
44
|
+
const ahead = extProtocolInfo("1.2", { current: "1.0" });
|
|
45
|
+
assert.equal(ahead.state, "ok");
|
|
46
|
+
assert.equal(ahead.minorAhead, true);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test("extProtocolInfo:stale / incompatible", () => {
|
|
50
|
+
const stale = extProtocolInfo("1.0", { current: "2.1", minMajor: 1 });
|
|
51
|
+
assert.equal(stale.state, "stale");
|
|
52
|
+
assert.equal(stale.needsUpgrade, true);
|
|
53
|
+
assert.deepEqual(stale.upgradeRefs, ["v1-to-v2"]);
|
|
54
|
+
|
|
55
|
+
const incompat = extProtocolInfo("1.0", { current: "3.0", minMajor: 2 });
|
|
56
|
+
assert.equal(incompat.state, "incompatible");
|
|
57
|
+
assert.equal(incompat.needsUpgrade, true);
|
|
58
|
+
assert.deepEqual(incompat.upgradeRefs, ["v1-to-v2", "v2-to-v3"]);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test("extProtocolInfo:too_new", () => {
|
|
62
|
+
const info = extProtocolInfo("2.0", { current: "1.0" });
|
|
63
|
+
assert.equal(info.state, "too_new");
|
|
64
|
+
assert.equal(info.needsUpgrade, false);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test("extProtocolInfo:missing / invalid", () => {
|
|
68
|
+
const missing = extProtocolInfo(undefined);
|
|
69
|
+
assert.equal(missing.state, "missing");
|
|
70
|
+
assert.equal(missing.needsUpgrade, true);
|
|
71
|
+
assert.deepEqual(missing.upgradeRefs, ["legacy-to-v1"]);
|
|
72
|
+
|
|
73
|
+
const invalid = extProtocolInfo(1.0);
|
|
74
|
+
assert.equal(invalid.state, "invalid");
|
|
75
|
+
assert.equal(invalid.needsUpgrade, true);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test("extProtocolUpgradeRefs:逐跳路由", () => {
|
|
79
|
+
assert.deepEqual(extProtocolUpgradeRefs("1.0", { current: "1.0" }), []);
|
|
80
|
+
assert.deepEqual(extProtocolUpgradeRefs("1.0", { current: "2.0" }), ["v1-to-v2"]);
|
|
81
|
+
assert.deepEqual(extProtocolUpgradeRefs("1.0", { current: "3.2" }), ["v1-to-v2", "v2-to-v3"]);
|
|
82
|
+
assert.deepEqual(extProtocolUpgradeRefs(undefined, { current: "1.0" }), ["legacy-to-v1"]);
|
|
83
|
+
assert.deepEqual(extProtocolUpgradeRefs(undefined, { current: "2.0" }), ["legacy-to-v1", "v1-to-v2"]);
|
|
84
|
+
// 0.x(版本化前谱系)与缺失同路由:先 legacy 手册
|
|
85
|
+
assert.deepEqual(extProtocolUpgradeRefs("0.9", { current: "1.0" }), ["legacy-to-v1"]);
|
|
86
|
+
assert.deepEqual(extProtocolUpgradeRefs("0.9", { current: "2.0" }), ["legacy-to-v1", "v1-to-v2"]);
|
|
87
|
+
assert.equal(extProtocolInfo("0.9").state, "incompatible");
|
|
88
|
+
});
|