pi-model-manager 0.4.8 → 0.4.10

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/index.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  // factory 阶段(pi 会等待)读取配置并注册完整 provider,本地代理按请求启动。
4
4
  // session_start 核对配置与注册状态,session_shutdown 幂等关闭代理服务。
5
5
  //
6
- // models.json 是模型定义唯一来源;state.json 只保存请求头 profile、抓包缓存、service_tier 等插件私有元数据。
6
+ // models.json 是模型定义唯一来源;state.json 只保存请求头选择、自定义方案、service_tier 等插件私有元数据。
7
7
  // 启动期通知用 session_start 事件 + ctx.ui.notify(factory 期没有 ctx)。
8
8
  //
9
9
  // 命令:/model-manager → TUI 面板
@@ -12,13 +12,14 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
12
12
  import { formatUnknownError } from "./common.ts";
13
13
  import { DEFAULT_UI_LANGUAGE, joinLocalizedList, setUiLanguage, t } from "./i18n.ts";
14
14
  import { readUiLanguage } from "./ui-language-settings.ts";
15
- import { persistManagedConfiguration, recoverPendingConfigurationTransaction, migrateManagedEndpointConfiguration } from "./configuration-persistence.ts";
15
+ import { persistManagedConfiguration, recoverPendingConfigurationTransaction, migrateManagedConfiguration } from "./configuration-persistence.ts";
16
16
  import { resetClaudeCodeMetadataSession } from "./claude-code-compat.ts";
17
17
  import { findProvidersNeedingBaseUrlNormalization, normalizeProviderBaseUrlsInDocument } from "./state-document.ts";
18
18
  import { closeLocalProxyServer } from "./local-proxy-service.ts";
19
19
  import { registerAllFromState, registerCatalogFromState } from "./provider-registrar.ts";
20
20
  import { createRequestPipeline } from "./request-pipeline.ts";
21
21
  import { createEmptyState, readState } from "./state-store.ts";
22
+ import { runWorkbench } from "./tui/workbench.ts";
22
23
 
23
24
  interface StartupSummary {
24
25
  startupErrors: string[];
@@ -34,10 +35,10 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
34
35
  }
35
36
 
36
37
  let configurationBlocked = false;
37
- let migratedEndpointConfiguration = false;
38
+ let migratedConfiguration = false;
38
39
  try {
39
40
  await recoverPendingConfigurationTransaction();
40
- migratedEndpointConfiguration = await migrateManagedEndpointConfiguration();
41
+ migratedConfiguration = await migrateManagedConfiguration();
41
42
  } catch (error) {
42
43
  configurationBlocked = true;
43
44
  summary.startupErrors.push(t("恢复未完成配置事务失败:{error}(为避免读取半完成配置,本次暂不注册模型)", { error: formatUnknownError(error) }));
@@ -67,7 +68,7 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
67
68
  try {
68
69
  if (configurationBlocked) {
69
70
  await recoverPendingConfigurationTransaction();
70
- migratedEndpointConfiguration = await migrateManagedEndpointConfiguration() || migratedEndpointConfiguration;
71
+ migratedConfiguration = await migrateManagedConfiguration() || migratedConfiguration;
71
72
  configurationBlocked = false;
72
73
  }
73
74
  const currentState = await readState();
@@ -78,11 +79,12 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
78
79
  // 归一化幂等,写完后后续启动检测不到差异,不会重复写盘。
79
80
  const staleBaseUrlProviderIds = findProvidersNeedingBaseUrlNormalization(currentState);
80
81
  if (staleBaseUrlProviderIds.length > 0) {
81
- await persistManagedConfiguration(ctx, (latest) => ({
82
+ const result = await persistManagedConfiguration(ctx, (latest) => ({
82
83
  document: normalizeProviderBaseUrlsInDocument(latest, staleBaseUrlProviderIds),
83
84
  changedProviderIds: [...staleBaseUrlProviderIds],
84
85
  removedProviderIds: [],
85
86
  }));
87
+ transportErrors.push(...result.warnings);
86
88
  migratedBaseUrlProviderIds = staleBaseUrlProviderIds;
87
89
  }
88
90
  } catch (error) {
@@ -99,9 +101,9 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
99
101
  for (const error of transportErrors) {
100
102
  ctx.ui.notify(`[pi-model-manager] ${error}`, "error");
101
103
  }
102
- if (migratedEndpointConfiguration) {
103
- ctx.ui.notify(t("[pi-model-manager] 已升级端点配置;迁移前快照保存在插件配置目录的 base-url-v5-*.json"), "info");
104
- migratedEndpointConfiguration = false;
104
+ if (migratedConfiguration) {
105
+ ctx.ui.notify(t("[pi-model-manager] 已升级配置;迁移前快照保存在插件配置目录的 configuration-v6-*.json"), "info");
106
+ migratedConfiguration = false;
105
107
  }
106
108
  if (migratedBaseUrlProviderIds.length > 0) {
107
109
  ctx.ui.notify(
@@ -114,6 +116,7 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
114
116
  }
115
117
  });
116
118
 
119
+ pi.on("before_provider_headers", async (event, ctx) => requestPipeline.transformHeaders(event.headers, ctx));
117
120
  pi.on("before_provider_request", async (event, ctx) => requestPipeline.transform(event.payload, ctx));
118
121
  pi.on("before_agent_start", () => requestPipeline.beginActivity());
119
122
  pi.on("agent_before_settle", (event, ctx) => requestPipeline.recover(event, ctx));
@@ -131,8 +134,7 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
131
134
  ctx.ui.notify(t("/model-manager 需要 TUI 交互模式"), "error");
132
135
  return;
133
136
  }
134
- const { runDashboard } = await import("./tui/dashboard.ts");
135
- await runDashboard(pi, ctx);
137
+ await runWorkbench(pi, ctx);
136
138
  },
137
139
  });
138
140
  }
@@ -22,13 +22,9 @@ import {
22
22
  verifyNativeModelAvailable,
23
23
  } from "./models-json-sync.ts";
24
24
  import { reconcileProvider, unregisterManagedProvider } from "./provider-registrar.ts";
25
- import { withModelRescue } from "./rescue.ts";
25
+ import { withModelRescue, type RescueNotice } from "./rescue.ts";
26
26
  import { deleteModelFromDocument, deleteProviderFromDocument, getModelFullId, upsertModelInDocument, upsertProviderInDocument, validateModelDraft, validateProviderDraft } from "./state-document.ts";
27
- import type { StateDocument, StoredProvider } from "./types.ts";
28
- import type { createModelDraftForStoredProvider, createProviderDraft } from "./state-document.ts";
29
-
30
- type ProviderDraft = ReturnType<typeof createProviderDraft>;
31
- type ModelDraft = ReturnType<typeof createModelDraftForStoredProvider>;
27
+ import type { ConfigurationChangeResult, ModelDraft, ProviderDraft, StateDocument } from "./types.ts";
32
28
 
33
29
  async function assertProviderIsEditable(providerId: string): Promise<void> {
34
30
  if (await isBuiltinProviderId(providerId)) {
@@ -42,12 +38,12 @@ function formatEnableNote(mode: "all-enabled" | "updated" | "unchanged", scope?:
42
38
  return t("已在 enabledModels 中");
43
39
  }
44
40
 
45
- async function notifyModelAvailability(
41
+ async function synchronizeModelAvailability(
46
42
  ctx: ExtensionCommandContext,
43
+ result: ConfigurationChangeResult,
47
44
  providerId: string,
48
45
  modelId: string,
49
46
  replacedFullId?: string,
50
- messagePrefix = t("已保存并启用模型"),
51
47
  ): Promise<void> {
52
48
  const fullId = getModelFullId(providerId, modelId);
53
49
  try {
@@ -55,35 +51,35 @@ async function notifyModelAvailability(
55
51
  const verification = await verifyNativeModelAvailable(ctx, providerId, modelId);
56
52
  const enableNote = formatEnableNote(enableOutcome.mode, enableOutcome.scope);
57
53
  if (verification.ok) {
58
- ctx.ui.notify(t("{messagePrefix} {fullId}({availability})", { messagePrefix, fullId, availability: enableNote }), "info");
54
+ result.messages[0] = t("{messagePrefix} {fullId}({availability})", { messagePrefix: t("已保存并启用模型"), fullId, availability: enableNote });
59
55
  } else {
60
- ctx.ui.notify(t("已保存模型 {fullId},但启用校验有警告:\n- {warnings}", { fullId, warnings: verification.warnings.join("\n- ") }), "warning");
56
+ result.warnings.push(t("已保存模型 {fullId},但启用校验有警告:\n- {warnings}", { fullId, warnings: verification.warnings.join("\n- ") }));
61
57
  }
62
58
  } catch (error) {
63
- ctx.ui.notify(t("已保存模型 {fullId},但启用同步/校验失败:{error}", { fullId, error: formatUnknownError(error) }), "warning");
59
+ result.warnings.push(t("已保存模型 {fullId},但启用同步/校验失败:{error}", { fullId, error: formatUnknownError(error) }));
64
60
  }
65
61
  }
66
62
 
67
- async function reconcilePersistedProviderRuntime(
68
- pi: ExtensionAPI,
69
- providerId: string,
70
- provider: StoredProvider,
71
- document: StateDocument,
72
- ): Promise<void> {
63
+ async function finishConfigurationChange(
64
+ result: ConfigurationChangeResult,
65
+ activate: () => Promise<RescueNotice | void>,
66
+ ): Promise<ConfigurationChangeResult> {
67
+ // [喵喵喵]: 落盘后只报告同步警告,不能再让调用方把已提交对象当作未保存的新草稿。
73
68
  try {
74
- await reconcileProvider(pi, providerId, provider, document.requestHeaderProfiles, document.clientHeaderCaptures);
69
+ const rescue = await activate();
70
+ if (rescue) (rescue.level === "warning" ? result.warnings : result.messages).push(rescue.message);
75
71
  } catch (error) {
76
- throw new Error(t("models.json/state.json 已保存,但当前会话接入刷新失败:{error}。可执行 /reload 重试。", { error: formatUnknownError(error) }));
72
+ result.warnings.push(t("配置已保存,但后续同步失败:{error}。可执行 /reload 重试。", { error: formatUnknownError(error) }));
77
73
  }
74
+ return result;
78
75
  }
79
76
 
80
77
  export async function saveProviderConfiguration(
81
78
  pi: ExtensionAPI,
82
79
  ctx: ExtensionCommandContext,
83
- _state: StateDocument,
84
80
  draft: ProviderDraft,
85
81
  oldProviderId: string | undefined,
86
- ): Promise<void> {
82
+ ): Promise<ConfigurationChangeResult> {
87
83
  await assertProviderIsEditable(draft.providerId);
88
84
  if (oldProviderId) await assertProviderIsEditable(oldProviderId);
89
85
  const prepare = (latest: StateDocument) => {
@@ -96,52 +92,40 @@ export async function saveProviderConfiguration(
96
92
  const document = upsertProviderInDocument(latest, oldProviderId, draft);
97
93
  return { document, changedProviderIds: [draft.providerId], removedProviderIds: [] };
98
94
  };
99
- const nextState = oldProviderId && oldProviderId !== draft.providerId
95
+ const commit = oldProviderId && oldProviderId !== draft.providerId
100
96
  ? await persistProviderRenameConfiguration(ctx, prepare, oldProviderId, draft.providerId)
101
97
  : await persistManagedConfiguration(ctx, prepare);
102
- const stored = nextState.providers[draft.providerId]!;
103
- const renamedCurrentModelId = oldProviderId
104
- && oldProviderId !== draft.providerId
105
- && ctx.model?.provider === oldProviderId
106
- && stored.models.some((model) => model.id === ctx.model?.id)
107
- ? ctx.model.id
108
- : undefined;
109
- await reconcilePersistedProviderRuntime(pi, draft.providerId, stored, nextState);
110
- if (oldProviderId && oldProviderId !== draft.providerId) unregisterManagedProvider(pi, oldProviderId);
111
-
112
- ctx.ui.notify(t("已保存接入 {providerId}", { providerId: draft.providerId }), "info");
113
-
114
- if (oldProviderId && oldProviderId !== draft.providerId) {
115
- try {
116
- const outcome = await replaceProviderInEnabledModelsForNextPiStart(
117
- ctx.cwd,
118
- oldProviderId,
119
- draft.providerId,
120
- );
121
- if (outcome.mode === "updated") {
122
- ctx.ui.notify(outcome.scope === "project"
123
- ? t("已同步项目 enabledModels 中的接入重命名")
124
- : t("已同步全局 enabledModels 中的接入重命名"), "info");
98
+ const result: ConfigurationChangeResult = { ...commit, messages: [t("已保存接入 {providerId}", { providerId: draft.providerId })] };
99
+ return finishConfigurationChange(result, async () => {
100
+ const nextState = result.document;
101
+ const stored = nextState.providers[draft.providerId]!;
102
+ const renamedCurrentModelId = oldProviderId && oldProviderId !== draft.providerId
103
+ && ctx.model?.provider === oldProviderId && stored.models.some((model) => model.id === ctx.model?.id)
104
+ ? ctx.model.id : undefined;
105
+ await reconcileProvider(pi, draft.providerId, stored, nextState.requestHeaderProfiles);
106
+ if (oldProviderId && oldProviderId !== draft.providerId) unregisterManagedProvider(pi, oldProviderId);
107
+ if (oldProviderId && oldProviderId !== draft.providerId) {
108
+ try {
109
+ const outcome = await replaceProviderInEnabledModelsForNextPiStart(ctx.cwd, oldProviderId, draft.providerId);
110
+ if (outcome.mode === "updated") result.messages.push(outcome.scope === "project"
111
+ ? t("已同步项目 enabledModels 中的接入重命名") : t("已同步全局 enabledModels 中的接入重命名"));
112
+ } catch (error) {
113
+ result.warnings.push(t("接入已保存,但 enabledModels 同步失败:{error}", { error: formatUnknownError(error) }));
125
114
  }
126
- } catch (error) {
127
- ctx.ui.notify(t("接入已保存,但 enabledModels 同步失败:{error}", { error: formatUnknownError(error) }), "warning");
115
+ return withModelRescue(ctx, pi, { providerId: oldProviderId }, {
116
+ reason: t("接入 {oldProviderId} 已重命名为 {providerId}", { oldProviderId, providerId: draft.providerId }),
117
+ preferred: renamedCurrentModelId ? { providerId: draft.providerId, modelId: renamedCurrentModelId } : undefined,
118
+ });
128
119
  }
129
- await withModelRescue(ctx, pi, { providerId: oldProviderId }, {
130
- reason: t("接入 {oldProviderId} 已重命名为 {providerId}", { oldProviderId, providerId: draft.providerId }),
131
- preferred: renamedCurrentModelId
132
- ? { providerId: draft.providerId, modelId: renamedCurrentModelId }
133
- : undefined,
134
- });
135
- }
120
+ });
136
121
  }
137
122
 
138
123
  export async function saveModelConfiguration(
139
124
  pi: ExtensionAPI,
140
125
  ctx: ExtensionCommandContext,
141
- _state: StateDocument,
142
126
  draft: ModelDraft,
143
127
  replacedModelId: string | undefined,
144
- ): Promise<void> {
128
+ ): Promise<ConfigurationChangeResult> {
145
129
  await assertProviderIsEditable(draft.providerId);
146
130
  const newModelId = draft.modelId.trim();
147
131
  const prepare = (latest: StateDocument) => {
@@ -156,70 +140,40 @@ export async function saveModelConfiguration(
156
140
  const oldFullId = replacedModelId && replacedModelId !== newModelId
157
141
  ? getModelFullId(draft.providerId, replacedModelId)
158
142
  : undefined;
159
- const nextState = oldFullId && replacedModelId
143
+ const commit = oldFullId && replacedModelId
160
144
  ? await persistModelRenameConfiguration(ctx, prepare, draft.providerId, replacedModelId, newModelId)
161
145
  : await persistModelConfiguration(ctx, prepare, draft.providerId, newModelId);
162
- const stored = nextState.providers[draft.providerId]!;
163
- await reconcilePersistedProviderRuntime(pi, draft.providerId, stored, nextState);
164
- const newFullId = getModelFullId(draft.providerId, newModelId);
165
- await notifyModelAvailability(ctx, draft.providerId, newModelId, oldFullId);
166
-
167
- if (oldFullId && replacedModelId) {
168
- await withModelRescue(
169
- ctx,
170
- pi,
171
- { providerId: draft.providerId, modelId: replacedModelId },
172
- {
173
- reason: t("模型 {oldFullId} 已重命名为 {newFullId}", { oldFullId, newFullId }),
174
- preferred: { providerId: draft.providerId, modelId: draft.modelId.trim() },
175
- },
176
- );
177
- }
178
- }
179
-
180
- export async function saveNewProviderWithModelConfiguration(
181
- pi: ExtensionAPI,
182
- ctx: ExtensionCommandContext,
183
- _providerState: StateDocument,
184
- providerDraft: ProviderDraft,
185
- modelDraft: ModelDraft,
186
- ): Promise<void> {
187
- await assertProviderIsEditable(providerDraft.providerId);
188
- const prepare = (latest: StateDocument) => {
189
- const providerErrors = validateProviderDraft(providerDraft, latest, new Set());
190
- if (providerErrors.length > 0) throw new Error(providerErrors.join("\n"));
191
- const withProvider = upsertProviderInDocument(latest, undefined, providerDraft);
192
- const modelErrors = validateModelDraft(modelDraft, withProvider);
193
- if (modelErrors.length > 0) throw new Error(modelErrors.join("\n"));
194
- const document = upsertModelInDocument(withProvider, modelDraft);
195
- return { document, changedProviderIds: [providerDraft.providerId], removedProviderIds: [] };
196
- };
197
- const nextState = await persistManagedConfiguration(ctx, prepare);
198
- const stored = nextState.providers[providerDraft.providerId]!;
199
- await reconcilePersistedProviderRuntime(pi, providerDraft.providerId, stored, nextState);
200
- await notifyModelAvailability(ctx, providerDraft.providerId, modelDraft.modelId.trim(), undefined, t("已创建并启用模型"));
146
+ const result: ConfigurationChangeResult = { ...commit, messages: [t("已保存模型 {fullId}", { fullId: getModelFullId(draft.providerId, newModelId) })] };
147
+ return finishConfigurationChange(result, async () => {
148
+ const nextState = result.document;
149
+ await reconcileProvider(pi, draft.providerId, nextState.providers[draft.providerId]!, nextState.requestHeaderProfiles);
150
+ const newFullId = getModelFullId(draft.providerId, newModelId);
151
+ await synchronizeModelAvailability(ctx, result, draft.providerId, newModelId, oldFullId);
152
+ if (oldFullId && replacedModelId) return withModelRescue(ctx, pi, { providerId: draft.providerId, modelId: replacedModelId }, {
153
+ reason: t("模型 {oldFullId} 已重命名为 {newFullId}", { oldFullId, newFullId }),
154
+ preferred: { providerId: draft.providerId, modelId: newModelId },
155
+ });
156
+ });
201
157
  }
202
158
 
203
159
  export async function deleteProviderConfiguration(
204
160
  pi: ExtensionAPI,
205
161
  ctx: ExtensionCommandContext,
206
162
  providerId: string,
207
- _provider: StoredProvider,
208
- ): Promise<void> {
163
+ ): Promise<ConfigurationChangeResult> {
209
164
  await assertProviderIsEditable(providerId);
210
- await persistManagedConfiguration(ctx, (latest) => ({
165
+ const commit = await persistManagedConfiguration(ctx, (latest) => ({
211
166
  document: deleteProviderFromDocument(latest, providerId),
212
167
  changedProviderIds: [],
213
168
  removedProviderIds: [providerId],
214
169
  }));
215
- try {
216
- await removeProviderFromNextPiStart(ctx.cwd, providerId);
217
- } catch (error) {
218
- ctx.ui.notify(t("接入已删除,但 enabledModels 清理失败:{error}", { error: formatUnknownError(error) }), "warning");
219
- }
220
- unregisterManagedProvider(pi, providerId);
221
- ctx.ui.notify(t("已删除接入 {providerId}", { providerId }), "info");
222
- await withModelRescue(ctx, pi, { providerId }, { reason: t("接入 {providerId} 已删除", { providerId }) });
170
+ const result: ConfigurationChangeResult = { ...commit, messages: [t("已删除接入 {providerId}", { providerId })] };
171
+ return finishConfigurationChange(result, async () => {
172
+ try { await removeProviderFromNextPiStart(ctx.cwd, providerId); }
173
+ catch (error) { result.warnings.push(t("接入已删除,但 enabledModels 清理失败:{error}", { error: formatUnknownError(error) })); }
174
+ unregisterManagedProvider(pi, providerId);
175
+ return withModelRescue(ctx, pi, { providerId }, { reason: t("接入 {providerId} 已删除", { providerId }) });
176
+ });
223
177
  }
224
178
 
225
179
  export async function deleteModelConfiguration(
@@ -227,28 +181,24 @@ export async function deleteModelConfiguration(
227
181
  ctx: ExtensionCommandContext,
228
182
  providerId: string,
229
183
  modelId: string,
230
- ): Promise<void> {
184
+ ): Promise<ConfigurationChangeResult> {
231
185
  await assertProviderIsEditable(providerId);
232
186
  const fullId = getModelFullId(providerId, modelId);
233
- const nextState = await persistModelDeletionConfiguration(ctx, (latest) => {
234
- let document = deleteModelFromDocument(latest, providerId, modelId);
235
- if ((document.providers[providerId]?.models.length ?? 0) === 0) {
236
- document = deleteProviderFromDocument(document, providerId);
237
- }
187
+ const commit = await persistModelDeletionConfiguration(ctx, (latest) => {
188
+ const document = deleteModelFromDocument(latest, providerId, modelId);
238
189
  return {
239
190
  document,
240
- changedProviderIds: document.providers[providerId] ? [providerId] : [],
241
- removedProviderIds: document.providers[providerId] ? [] : [providerId],
191
+ changedProviderIds: [providerId],
192
+ removedProviderIds: [],
242
193
  };
243
194
  }, providerId, modelId);
244
- const stored = nextState.providers[providerId];
245
- try {
246
- await removeModelFromNextPiStart(ctx.cwd, fullId);
247
- } catch (error) {
248
- ctx.ui.notify(t("模型已删除,但 enabledModels 清理失败:{error}", { error: formatUnknownError(error) }), "warning");
249
- }
250
- if (stored) await reconcilePersistedProviderRuntime(pi, providerId, stored, nextState);
251
- else unregisterManagedProvider(pi, providerId);
252
- ctx.ui.notify(t("已删除模型 {fullId}", { fullId }), "info");
253
- await withModelRescue(ctx, pi, { providerId, modelId }, { reason: t("模型 {fullId} 已删除", { fullId }) });
195
+ const result: ConfigurationChangeResult = { ...commit, messages: [t("已删除模型 {fullId}", { fullId })] };
196
+ return finishConfigurationChange(result, async () => {
197
+ const nextState = result.document;
198
+ const stored = nextState.providers[providerId];
199
+ try { await removeModelFromNextPiStart(ctx.cwd, fullId); }
200
+ catch (error) { result.warnings.push(t("模型已删除,但 enabledModels 清理失败:{error}", { error: formatUnknownError(error) })); }
201
+ if (stored) await reconcileProvider(pi, providerId, stored, nextState.requestHeaderProfiles);
202
+ return withModelRescue(ctx, pi, { providerId, modelId }, { reason: t("模型 {fullId} 已删除", { fullId }) });
203
+ });
254
204
  }
@@ -0,0 +1,54 @@
1
+ import { getClientHeadersForProfile, mergeModelRequestHeaders, resolveClientHeaderProfile, resolveProviderCustomHeaders } from "./presets/client-headers.ts";
2
+ import { buildCodexClientHeaders } from "./presets/codex-client-headers.ts";
3
+ import type { ApiKind, StoredModel, StoredProvider, StoredRequestHeaderProfile } from "./types.ts";
4
+
5
+ type HeaderProvider = Pick<StoredProvider, "api" | "managed" | "headers" | "clientHeaderProfile" | "requestHeaderProfileId" | "customClientHeaders">;
6
+ type HeaderModel = Pick<StoredModel, "api" | "headers">;
7
+ type HeaderProfiles = Record<string, StoredRequestHeaderProfile>;
8
+
9
+ export function resolveManagedModelApi(value: string | undefined, fallback: ApiKind): ApiKind {
10
+ if (value === "openai-completions" || value === "openai-responses"
11
+ || value === "anthropic-messages" || value === "google-generative-ai") return value;
12
+ return fallback;
13
+ }
14
+
15
+ export function buildModelRequestHeaders(
16
+ provider: HeaderProvider,
17
+ model: HeaderModel,
18
+ profiles: HeaderProfiles,
19
+ ): Record<string, string> | undefined {
20
+ if (!provider.managed) return model.headers ? { ...model.headers } : undefined;
21
+ const api = resolveManagedModelApi(model.api, provider.api);
22
+ const profile = resolveClientHeaderProfile(provider.clientHeaderProfile, api);
23
+ const custom = profile === "custom" ? resolveProviderCustomHeaders(provider, profiles) : {};
24
+ const headers = getClientHeadersForProfile(provider.clientHeaderProfile, api, custom) ?? {};
25
+ const explicit = mergeModelRequestHeaders(provider.headers, model.headers) ?? {};
26
+ if (profile === "codex-cli") return buildCodexClientHeaders(headers, explicit);
27
+ return profile === "custom" ? mergeModelRequestHeaders(explicit, headers) : mergeModelRequestHeaders(headers, explicit);
28
+ }
29
+
30
+ /** 在宿主头钩子阶段补充内置身份,保留已解析的用户值和其它扩展的删除标记。 */
31
+ export function applyBuiltinRequestHeaders(headers: Record<string, string | null>, provider: HeaderProvider, api: ApiKind): void {
32
+ const profile = resolveClientHeaderProfile(provider.clientHeaderProfile, api);
33
+ if (!provider.managed || profile === "disabled" || profile === "custom") return;
34
+ const current = Object.fromEntries(Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]));
35
+ let builtin = getClientHeadersForProfile(profile, api, {})!;
36
+ if (profile === "codex-cli" && typeof current["user-agent"] === "string") {
37
+ builtin = buildCodexClientHeaders(builtin, { "user-agent": current["user-agent"] });
38
+ }
39
+ for (const [name, value] of Object.entries(builtin)) {
40
+ if (!Object.hasOwn(current, name.toLowerCase())) headers[name] = value;
41
+ }
42
+ }
43
+ /** 内置身份只在运行时计算;磁盘只保留模型显式头与用户选择的自定义方案。 */
44
+ export function buildPersistedModelHeaders(provider: HeaderProvider, model: HeaderModel, profiles: HeaderProfiles): Record<string, string> | undefined {
45
+ if (!provider.managed) return model.headers ? { ...model.headers } : undefined;
46
+ return mergeModelRequestHeaders(model.headers, getGeneratedCustomHeaders(provider, profiles));
47
+ }
48
+
49
+ /** 自定义方案的派生副本仍记录来源,确保更新或删除方案时不遗留旧值。 */
50
+ export function getGeneratedCustomHeaders(provider: HeaderProvider, profiles: HeaderProfiles): Record<string, string> | undefined {
51
+ return provider.managed && provider.clientHeaderProfile === "custom"
52
+ ? mergeModelRequestHeaders(undefined, resolveProviderCustomHeaders(provider, profiles)) ?? {}
53
+ : undefined;
54
+ }
@@ -29,12 +29,10 @@ import {
29
29
  type ModelsJsonModelEntry,
30
30
  type ModelsJsonProviderEntry,
31
31
  } from "./models-json-manager.ts";
32
- import { buildModelRequestHeaders } from "./provider-registrar.ts";
32
+ import { buildPersistedModelHeaders } from "./model-request-headers.ts";
33
33
  import { toNativeBaseUrl } from "./runtime-base-url.ts";
34
34
  import type {
35
- BuiltInClientHeaderProfileId,
36
35
  StateDocument,
37
- StoredClientHeaderCapture,
38
36
  StoredModel,
39
37
  StoredProvider,
40
38
  StoredRequestHeaderProfile,
@@ -77,7 +75,6 @@ function buildModelsJsonModelEntry(
77
75
  provider: StoredProvider,
78
76
  model: StoredModel,
79
77
  requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
80
- clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>>,
81
78
  existing?: ModelsJsonModelEntry,
82
79
  ): ModelsJsonModelEntry {
83
80
  const next: ModelsJsonModelEntry = existing ? { ...existing } : { id: model.id };
@@ -98,7 +95,7 @@ function buildModelsJsonModelEntry(
98
95
  next.contextWindow = model.contextWindow;
99
96
  next.maxTokens = model.maxTokens;
100
97
  next.cost = copyCost(model.cost);
101
- const headers = buildModelRequestHeaders(provider, model, requestHeaderProfiles, clientHeaderCaptures);
98
+ const headers = buildPersistedModelHeaders(provider, model, requestHeaderProfiles);
102
99
  if (headers) next.headers = headers;
103
100
  else delete next.headers;
104
101
  if (model.compat) next.compat = copyRecord(model.compat);
@@ -109,7 +106,6 @@ function buildModelsJsonModelEntry(
109
106
  function buildModelsJsonProviderEntry(
110
107
  provider: StoredProvider,
111
108
  requestHeaderProfiles: Record<string, StoredRequestHeaderProfile> = {},
112
- clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>> = {},
113
109
  existing?: ModelsJsonProviderEntry,
114
110
  ): ModelsJsonProviderEntry {
115
111
  const next: ModelsJsonProviderEntry = existing ? { ...existing } : {};
@@ -133,7 +129,6 @@ function buildModelsJsonProviderEntry(
133
129
  provider,
134
130
  model,
135
131
  requestHeaderProfiles,
136
- clientHeaderCaptures,
137
132
  existingModels.get(model.id),
138
133
  ));
139
134
  return markProviderEntryAsPluginManaged(next);
@@ -151,14 +146,13 @@ export function buildSynchronizedModelsDocument(
151
146
  }
152
147
  for (const providerId of [...new Set(changedProviderIds)]) {
153
148
  const provider = document.providers[providerId];
154
- if (!provider || provider.models.length === 0) {
149
+ if (!provider) {
155
150
  nextDocument = deleteProviderInDoc(nextDocument, providerId);
156
151
  continue;
157
152
  }
158
153
  const entry = buildModelsJsonProviderEntry(
159
154
  provider,
160
155
  document.requestHeaderProfiles,
161
- document.clientHeaderCaptures,
162
156
  nextDocument.providers[providerId],
163
157
  );
164
158
  nextDocument = setProviderInDoc(nextDocument, providerId, entry);
@@ -207,7 +201,6 @@ export function buildModelsDocumentWithSynchronizedModel(
207
201
  provider,
208
202
  model,
209
203
  document.requestHeaderProfiles,
210
- document.clientHeaderCaptures,
211
204
  sourceModel,
212
205
  );
213
206
  return setModelInDoc(sourceDocument, providerId, entry, replacedModelId);
@@ -219,9 +212,16 @@ export function buildModelsDocumentWithoutModel(
219
212
  providerId: string,
220
213
  modelId: string,
221
214
  ): ModelsJsonDocument {
222
- return document.providers[providerId]
223
- ? deleteModelInDoc(sourceDocument, providerId, modelId)
224
- : deleteProviderInDoc(sourceDocument, providerId);
215
+ const provider = document.providers[providerId];
216
+ if (!provider) throw new Error(t("接入不存在:{providerId}", { providerId }));
217
+ const next = deleteModelInDoc(sourceDocument, providerId, modelId);
218
+ const entry = next.providers[providerId];
219
+ if (entry?.models?.length === 0) {
220
+ // [喵喵喵]: 原生接入可仅在模型上声明连接信息;删除末模型后须保留空接入的读取依据,不接管其他字段。
221
+ entry.api ??= provider.api;
222
+ entry.baseUrl ??= provider.managed ? toNativeBaseUrl(provider.api, provider.baseUrl).baseUrl : provider.baseUrl;
223
+ }
224
+ return next;
225
225
  }
226
226
  function splitThinkingSuffix(pattern: string): { base: string; suffix: string } {
227
227
  const index = pattern.lastIndexOf(":");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-model-manager",
3
- "version": "0.4.8",
3
+ "version": "0.4.10",
4
4
  "description": "A TUI model and provider manager for Pi with native models.json persistence, request-header profiles, proxy routing, and protocol compatibility.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -30,6 +30,7 @@
30
30
  "models-json-manager.ts",
31
31
  "models-json-sync.ts",
32
32
  "provider-registrar.ts",
33
+ "model-request-headers.ts",
33
34
  "provider-transport.ts",
34
35
  "local-proxy-service.ts",
35
36
  "request-pipeline.ts",
@@ -1,9 +1,9 @@
1
- // Claude Code 身份字段来自真实客户端捕获,协议 beta 由 Pi 按请求生成;Codex 采用 codex-proxy-rs 的通用 Rust CLI 画像。
1
+ // Claude Code 身份字段来自真实客户端捕获,协议 beta 由 Pi 按请求生成;Codex 与 Antigravity CLI 采用 codex-proxy-rs 的客户端画像。
2
2
 
3
3
  export const CLAUDE_CODE_CLIENT_HEADERS: Record<string, string> = {
4
4
  "anthropic-dangerous-direct-browser-access": "true",
5
5
  "anthropic-version": "2023-06-01",
6
- "user-agent": "claude-cli/2.1.330 (external, sdk-cli)",
6
+ "user-agent": "claude-cli/2.1.335 (external, sdk-cli)",
7
7
  "x-app": "cli",
8
8
  "x-stainless-arch": "x64",
9
9
  "x-stainless-lang": "js",
@@ -17,6 +17,11 @@ export const CLAUDE_CODE_CLIENT_HEADERS: Record<string, string> = {
17
17
 
18
18
  export const CODEX_CLI_CLIENT_HEADERS: Record<string, string> = {
19
19
  "originator": "codex_cli_rs",
20
- "user-agent": "codex_cli_rs/0.171.0 (Windows 10.0.26100; x86_64) unknown",
21
- "version": "0.171.0",
20
+ "user-agent": "codex_cli_rs/0.173.0 (Windows 10.0.26100; x86_64) unknown",
21
+ "version": "0.173.0",
22
+ };
23
+
24
+ // [喵喵喵]: 官方发布清单提供版本;未知构建号不沿用其它版本的 cl,认证与请求体仍由宿主负责。
25
+ export const ANTIGRAVITY_CLI_CLIENT_HEADERS: Record<string, string> = {
26
+ "user-agent": "antigravity/cli/1.5.22 (aidev_client; os_type=linux; arch=amd64; auth_method=consumer)",
22
27
  };
@@ -1,4 +1,4 @@
1
- // 客户端请求头:5 个模式(recommended / disabled / claude-code / codex-cli / custom)。
1
+ // 客户端请求头:自动推荐、禁用、内置画像与自定义。
2
2
  // ClaudeCode profile 的 body metadata 信号由 ../claude-code-compat.ts 在请求发送前补齐。
3
3
  //
4
4
  // [喵喵喵]: 内置值由私有抓包工具生成,公开插件不携带捕获能力 (2026-07-26)
@@ -6,13 +6,14 @@
6
6
  import { cloneStringRecord, hasStringRecordEntries } from "../common.ts";
7
7
  import { buildCodexClientHeaders } from "./codex-client-headers.ts";
8
8
  import { t } from "../i18n.ts";
9
- import type { ApiKind, BuiltInClientHeaderProfileId, ClientHeaderProfileId, StoredClientHeaderCapture, StoredRequestHeaderProfile } from "../types.ts";
10
- import { CLAUDE_CODE_CLIENT_HEADERS, CODEX_CLI_CLIENT_HEADERS } from "./builtin-client-headers.ts";
9
+ import type { ApiKind, ClientHeaderProfileId, StoredRequestHeaderProfile } from "../types.ts";
10
+ import { ANTIGRAVITY_CLI_CLIENT_HEADERS, CLAUDE_CODE_CLIENT_HEADERS, CODEX_CLI_CLIENT_HEADERS } from "./builtin-client-headers.ts";
11
11
 
12
12
  export function getClientHeaderProfileLabel(profile: ClientHeaderProfileId): string {
13
13
  if (profile === "recommended") return t("自动推荐");
14
14
  if (profile === "disabled") return t("不添加");
15
15
  if (profile === "custom") return t("自定义请求头");
16
+ if (profile === "antigravity-cli") return "Antigravity CLI";
16
17
  return profile === "claude-code" ? "ClaudeCode" : "Codex";
17
18
  }
18
19
 
@@ -28,7 +29,7 @@ export function mergeModelRequestHeaders(
28
29
  return hasStringRecordEntries(merged) ? merged : undefined;
29
30
  }
30
31
 
31
- /** 读取 models.json 时剥离当前 profile 管理的字段,避免把生成值误当作用户原生 headers。 */
32
+ /** 按来源记录剥离仍与生成值一致的字段,保留用户改写的值。 */
32
33
  export function stripManagedClientHeaders(
33
34
  storedHeaders: Record<string, string> | undefined,
34
35
  profileHeaders: Record<string, string> | undefined,
@@ -53,6 +54,7 @@ export function resolveProviderCustomHeaders(
53
54
  function getRecommendedClientHeaderProfile(api: ApiKind): ClientHeaderProfileId {
54
55
  if (api === "anthropic-messages") return "claude-code";
55
56
  if (api === "openai-completions" || api === "openai-responses") return "codex-cli";
57
+ if (api === "google-generative-ai") return "antigravity-cli";
56
58
  return "disabled";
57
59
  }
58
60
 
@@ -64,23 +66,12 @@ export function getClientHeadersForProfile(
64
66
  profile: ClientHeaderProfileId,
65
67
  api: ApiKind,
66
68
  customHeaders: Record<string, string>,
67
- clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>> = {},
68
69
  ): Record<string, string> | undefined {
69
70
  const resolved = resolveClientHeaderProfile(profile, api);
70
71
  if (resolved === "disabled") return undefined;
71
- if (resolved === "claude-code") {
72
- const headers = hasStringRecordEntries(clientHeaderCaptures[resolved]?.headers)
73
- ? clientHeaderCaptures[resolved]!.headers
74
- : CLAUDE_CODE_CLIENT_HEADERS;
75
- // [喵喵喵]: 显式 beta 会禁用 Pi 的协议能力推导;抓包缓存只提供身份字段,不重放其条件性 beta。
76
- return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== "anthropic-beta"));
77
- }
78
- if (resolved === "codex-cli") {
79
- const headers = hasStringRecordEntries(clientHeaderCaptures[resolved]?.headers)
80
- ? clientHeaderCaptures[resolved]!.headers
81
- : CODEX_CLI_CLIENT_HEADERS;
82
- return buildCodexClientHeaders(headers);
83
- }
72
+ if (resolved === "claude-code") return cloneStringRecord(CLAUDE_CODE_CLIENT_HEADERS);
73
+ if (resolved === "codex-cli") return buildCodexClientHeaders(CODEX_CLI_CLIENT_HEADERS);
74
+ if (resolved === "antigravity-cli") return cloneStringRecord(ANTIGRAVITY_CLI_CLIENT_HEADERS);
84
75
  return hasStringRecordEntries(customHeaders) ? cloneStringRecord(customHeaders) : undefined;
85
76
  }
86
77
  export function getClientHeaderProfileDisplay(profile: ClientHeaderProfileId, api: ApiKind): string {