pi-private-models 0.1.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.
- package/LICENSE +199 -0
- package/README.md +42 -0
- package/README.zh-CN.md +42 -0
- package/extensions/private-models/apply.ts +87 -0
- package/extensions/private-models/defaults.ts +46 -0
- package/extensions/private-models/index.ts +88 -0
- package/extensions/private-models/private-file.ts +221 -0
- package/extensions/private-models/resolve-inherit.ts +146 -0
- package/extensions/private-models/utils/fields.ts +31 -0
- package/extensions/private-models/utils/read-agent-json.ts +34 -0
- package/extensions/private-models/utils/suggest.ts +32 -0
- package/package.json +27 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to the Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding any notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. Please also get an approval
|
|
185
|
+
from your organization if needed.
|
|
186
|
+
|
|
187
|
+
Copyright 2025 the contributors
|
|
188
|
+
|
|
189
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
190
|
+
you may not use this file except in compliance with the License.
|
|
191
|
+
You may obtain a copy of the License at
|
|
192
|
+
|
|
193
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
194
|
+
|
|
195
|
+
Unless required by applicable law or agreed to in writing, software
|
|
196
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
197
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
198
|
+
See the License for the specific language governing permissions and
|
|
199
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# pi-private-models
|
|
2
|
+
|
|
3
|
+
**English** | [简体中文](./README.zh-CN.md)
|
|
4
|
+
|
|
5
|
+
pi extension that keeps private model providers out of the published `models.json`
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
<agent-dir>/models.json public, committed
|
|
9
|
+
<agent-dir>/models.private.json private, kept out of the repository
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
```jsonc
|
|
13
|
+
{
|
|
14
|
+
"providers": {
|
|
15
|
+
"my-gateway": {
|
|
16
|
+
"baseUrl": "http://10.0.0.5:8123/v1",
|
|
17
|
+
"api": "openai-completions",
|
|
18
|
+
"apiKey": "$GATEWAY_API_KEY",
|
|
19
|
+
"models": [
|
|
20
|
+
{ "id": "glm-5.3", "reasoning": true, "contextWindow": 200000, "maxTokens": 32000 },
|
|
21
|
+
// ...
|
|
22
|
+
]
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
|
|
30
|
+
From npmjs:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pi install npm:pi-private-models
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
From GitHub:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pi install git:github.com/jalaxy33/pi-private-models
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Add `models.private.json` to your `.gitignore`. A missing file does nothing.
|
package/README.zh-CN.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# pi-private-models
|
|
2
|
+
|
|
3
|
+
[English](./README.md) | **简体中文**
|
|
4
|
+
|
|
5
|
+
pi 扩展,让私有模型 provider 不进公开的 `models.json`
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
<agent-dir>/models.json 公开,提交进仓库
|
|
9
|
+
<agent-dir>/models.private.json 私有,不进仓库
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
```jsonc
|
|
13
|
+
{
|
|
14
|
+
"providers": {
|
|
15
|
+
"my-gateway": {
|
|
16
|
+
"baseUrl": "http://10.0.0.5:8123/v1",
|
|
17
|
+
"api": "openai-completions",
|
|
18
|
+
"apiKey": "$GATEWAY_API_KEY",
|
|
19
|
+
"models": [
|
|
20
|
+
{ "id": "glm-5.3", "reasoning": true, "contextWindow": 200000, "maxTokens": 32000 },
|
|
21
|
+
// ……
|
|
22
|
+
]
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## 安装
|
|
29
|
+
|
|
30
|
+
从 npmjs 安装:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pi install npm:pi-private-models
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
从 GitHub 安装:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pi install git:github.com/jalaxy33/pi-private-models
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
记得把 `models.private.json` 加进 `.gitignore`。文件不存在就什么都不做。
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turn models.private.json into provider registrations.
|
|
3
|
+
*
|
|
4
|
+
* Runs twice: while extensions load, when there is no runtime yet and inherit
|
|
5
|
+
* targets come from the files, and at session start, when pi's own model store
|
|
6
|
+
* can answer for the catalog and for models.json.
|
|
7
|
+
*/
|
|
8
|
+
import { readAgentJson, type Dict } from "./utils/read-agent-json.ts";
|
|
9
|
+
import { withDefaults } from "./defaults.ts";
|
|
10
|
+
import { parsePrivateFile, readPrivateFile } from "./private-file.ts";
|
|
11
|
+
import { fileLookup, planInherit, providerIdsOf, storeLookup, withModelDefaults } from "./resolve-inherit.ts";
|
|
12
|
+
|
|
13
|
+
/** The two provider calls this extension makes. */
|
|
14
|
+
export interface Registrations {
|
|
15
|
+
register(providerId: string, config: Dict): void;
|
|
16
|
+
unregister(providerId: string): void;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Applies the private file and returns what is wrong with it. `registered` holds
|
|
21
|
+
* the ids this extension owns, and is kept up to date.
|
|
22
|
+
*/
|
|
23
|
+
export function applyPrivateProviders(registrations: Registrations, registered: Set<string>, runtime: any | undefined): string[] {
|
|
24
|
+
const publicFile = readAgentJson("models.json");
|
|
25
|
+
const parsed = parsePrivateFile(readPrivateFile());
|
|
26
|
+
const issues = [...parsed.issues];
|
|
27
|
+
|
|
28
|
+
const lookup = runtime ? storeLookup(parsed.providers, runtime) : fileLookup(parsed.providers, publicFile);
|
|
29
|
+
const knownProviders = new Set([...parsed.providers.keys(), ...providerIdsOf(publicFile), ...runtimeProviderIds(runtime)]);
|
|
30
|
+
const plan = planInherit(parsed.providers, lookup, knownProviders);
|
|
31
|
+
issues.push(...plan.issues);
|
|
32
|
+
// Without a runtime a catalog model is simply not there yet, so wait for the next run.
|
|
33
|
+
if (runtime) issues.push(...plan.unresolved);
|
|
34
|
+
|
|
35
|
+
const taken = takenIds(runtime, registered);
|
|
36
|
+
const next = new Set<string>();
|
|
37
|
+
for (const [providerId, provider] of parsed.providers) {
|
|
38
|
+
const conflict = taken.get(providerId);
|
|
39
|
+
if (conflict) {
|
|
40
|
+
issues.push(`providers["${providerId}"] is ignored: "${providerId}" is ${conflict}.`);
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
const { config, models } = withDefaults(provider.config, plan.models.get(providerId) ?? provider.models, parsed.defaults, providerId);
|
|
44
|
+
const missing = ["baseUrl", "api"].filter((key) => typeof config[key] !== "string" || config[key] === "");
|
|
45
|
+
if (missing.length > 0) {
|
|
46
|
+
issues.push(`providers["${providerId}"] needs ${missing.map((key) => `"${key}"`).join(" and ")}: this extension registers it, so it has to carry them.`);
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
registrations.register(providerId, { ...config, models: models.map(withModelDefaults) });
|
|
51
|
+
next.add(providerId);
|
|
52
|
+
} catch (error) {
|
|
53
|
+
issues.push(`providers["${providerId}"]: ${error instanceof Error ? error.message : String(error)}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
for (const providerId of [...registered]) if (!next.has(providerId)) registrations.unregister(providerId);
|
|
57
|
+
registered.clear();
|
|
58
|
+
for (const providerId of next) registered.add(providerId);
|
|
59
|
+
return issues;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Why a private id must stay away: that id belongs to pi, or to another extension. */
|
|
63
|
+
function takenIds(runtime: any | undefined, ours: ReadonlySet<string>): Map<string, string> {
|
|
64
|
+
const taken = new Map<string, string>();
|
|
65
|
+
const add = (providerId: string, reason: string): void => {
|
|
66
|
+
if (!taken.has(providerId)) taken.set(providerId, reason);
|
|
67
|
+
};
|
|
68
|
+
for (const providerId of providerIdsOf(readAgentJson("models.json"))) add(providerId, "defined in models.json");
|
|
69
|
+
for (const providerId of runtime?.builtins?.keys?.() ?? []) add(String(providerId), "a built-in provider");
|
|
70
|
+
for (const map of [runtime?.nativeExtensionProviders, runtime?.extensionProviders]) {
|
|
71
|
+
for (const providerId of map?.keys?.() ?? []) {
|
|
72
|
+
if (ours.has(String(providerId))) continue; // our own registration
|
|
73
|
+
add(String(providerId), "registered by another extension");
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return taken;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Provider ids pi knows once it is running: built-ins, models.json, extensions. */
|
|
80
|
+
function runtimeProviderIds(runtime: any | undefined): string[] {
|
|
81
|
+
const ids = new Set<string>();
|
|
82
|
+
for (const map of [runtime?.builtins, runtime?.nativeExtensionProviders, runtime?.extensionProviders]) {
|
|
83
|
+
for (const providerId of map?.keys?.() ?? []) ids.add(String(providerId));
|
|
84
|
+
}
|
|
85
|
+
for (const providerId of runtime?.config?.getProviderIds?.() ?? []) ids.add(String(providerId));
|
|
86
|
+
return [...ids];
|
|
87
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `default` block of models.private.json: values the providers of that file
|
|
3
|
+
* inherit. Applied here, while building the registration, so they never reach a
|
|
4
|
+
* provider that is defined somewhere else.
|
|
5
|
+
*/
|
|
6
|
+
import { isObj, type Dict } from "./utils/read-agent-json.ts";
|
|
7
|
+
import { merge, pick } from "./utils/fields.ts";
|
|
8
|
+
|
|
9
|
+
/** Keys pi reads while composing a provider, so they belong on the provider config. */
|
|
10
|
+
const CONFIG_KEYS = ["name", "baseUrl", "apiKey", "api", "authHeader"];
|
|
11
|
+
|
|
12
|
+
export interface PrivateDefaults {
|
|
13
|
+
star?: Dict;
|
|
14
|
+
exact: Map<string, Dict>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export const noDefaults = (): PrivateDefaults => ({ exact: new Map() });
|
|
18
|
+
|
|
19
|
+
/** `"*"` first, then the exact provider id. */
|
|
20
|
+
export function defaultsFor(defaults: PrivateDefaults, providerId: string): Dict | undefined {
|
|
21
|
+
const star = defaults.star;
|
|
22
|
+
const exact = defaults.exact.get(providerId);
|
|
23
|
+
if (!star) return exact;
|
|
24
|
+
if (!exact) return star;
|
|
25
|
+
return merge(star, exact);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Provider config with the default block under the provider's own values.
|
|
30
|
+
*
|
|
31
|
+
* `compat` is handed down to every model entry: pi drops provider-level compat
|
|
32
|
+
* for providers that an extension registers, so the entry is the only place it counts.
|
|
33
|
+
*/
|
|
34
|
+
export function withDefaults(config: Dict, models: Dict[], defaults: PrivateDefaults, providerId: string): { config: Dict; models: Dict[] } {
|
|
35
|
+
const layer = defaultsFor(defaults, providerId);
|
|
36
|
+
const compat = merge(isObj(layer?.compat) ? layer.compat : {}, isObj(config.compat) ? config.compat : {});
|
|
37
|
+
const merged = merge(pick(layer, CONFIG_KEYS) ?? {}, config);
|
|
38
|
+
delete merged.compat;
|
|
39
|
+
if (isObj(layer?.headers)) merged.headers = merge(layer.headers, isObj(config.headers) ? config.headers : {});
|
|
40
|
+
return {
|
|
41
|
+
config: merged,
|
|
42
|
+
models: Object.keys(compat).length > 0
|
|
43
|
+
? models.map((entry) => ({ ...entry, compat: merge(compat, isObj(entry.compat) ? entry.compat : {}) }))
|
|
44
|
+
: models,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-private-models: the providers of `models.private.json`, a file next to the
|
|
3
|
+
* models.json that gets published.
|
|
4
|
+
*
|
|
5
|
+
* models.json public, committed
|
|
6
|
+
* models.private.json private, kept out of the repository
|
|
7
|
+
*
|
|
8
|
+
* The private file only adds providers. An id that already belongs to pi or to
|
|
9
|
+
* another extension is ignored, and nothing is written back.
|
|
10
|
+
*/
|
|
11
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
12
|
+
import { readAgentJson } from "./utils/read-agent-json.ts";
|
|
13
|
+
import { applyPrivateProviders, type Registrations } from "./apply.ts";
|
|
14
|
+
import { LOCAL_KEYS } from "./resolve-inherit.ts";
|
|
15
|
+
|
|
16
|
+
const LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
|
|
17
|
+
type Level = (typeof LEVELS)[number];
|
|
18
|
+
const isLevel = (value: unknown): value is Level => typeof value === "string" && (LEVELS as readonly string[]).includes(value);
|
|
19
|
+
|
|
20
|
+
export default function piPrivateModels(pi: ExtensionAPI): void {
|
|
21
|
+
const registered = new Set<string>();
|
|
22
|
+
const warned = new Set<string>();
|
|
23
|
+
const registrations: Registrations = {
|
|
24
|
+
register: (providerId, config) => pi.registerProvider(providerId, config as any),
|
|
25
|
+
unregister: (providerId) => pi.unregisterProvider(providerId),
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
// Register the file before pi picks the startup model, so model selection and
|
|
29
|
+
// --list-models already see the private providers. Without a runtime only the
|
|
30
|
+
// files can answer `inherit`, so the values may still change at session start.
|
|
31
|
+
applyPrivateProviders(registrations, registered, undefined);
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* pi resolves the session's thinking level from settings while it builds the
|
|
35
|
+
* startup model, before the private provider exists, so a model that only
|
|
36
|
+
* becomes reasoning-capable through `inherit` starts at a level clamped to
|
|
37
|
+
* "off". An endpoint that rejects `thinking: {"type":"disabled"}` then fails
|
|
38
|
+
* every request, so put back the level pi would have chosen.
|
|
39
|
+
*/
|
|
40
|
+
const restoreThinkingLevel = (model: any): void => {
|
|
41
|
+
if (model?.reasoning !== true || pi.getThinkingLevel?.() !== "off") return;
|
|
42
|
+
const settings = readAgentJson("settings.json");
|
|
43
|
+
const level = settings?.modelThinkingLevels?.[`${model.provider}/${model.id}`] ?? settings?.defaultThinkingLevel ?? "medium";
|
|
44
|
+
if (!isLevel(level) || level === "off") return;
|
|
45
|
+
try {
|
|
46
|
+
pi.setThinkingLevel(level);
|
|
47
|
+
} catch {
|
|
48
|
+
/* no session runtime: nothing to restore */
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* A model resolved before this extension re-registered its provider keeps the
|
|
54
|
+
* object it was built with, so copy the fields of the freshly composed one.
|
|
55
|
+
*/
|
|
56
|
+
const adopt = (ctx: any): void => {
|
|
57
|
+
const model = ctx?.model;
|
|
58
|
+
if (!model || !registered.has(model.provider)) return;
|
|
59
|
+
const fresh = ctx?.modelRegistry?.runtime?.models?.getModel?.(model.provider, model.id);
|
|
60
|
+
if (fresh && fresh !== model) {
|
|
61
|
+
for (const [key, value] of Object.entries(fresh)) {
|
|
62
|
+
if (LOCAL_KEYS.includes(key)) continue;
|
|
63
|
+
try {
|
|
64
|
+
model[key] = value;
|
|
65
|
+
} catch {
|
|
66
|
+
/* frozen: the store copy is still correct */
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
restoreThinkingLevel(model);
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const warn = (ctx: any, issues: string[]): void => {
|
|
74
|
+
if (issues.length === 0) return;
|
|
75
|
+
const message = `pi-private-models: ${issues.join(" ")}`;
|
|
76
|
+
if (warned.has(message)) return;
|
|
77
|
+
warned.add(message);
|
|
78
|
+
if (ctx?.hasUI && typeof ctx.ui?.notify === "function") ctx.ui.notify(message, "warning");
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const sync = (ctx: any): void => {
|
|
82
|
+
warn(ctx, applyPrivateProviders(registrations, registered, ctx?.modelRegistry?.runtime));
|
|
83
|
+
adopt(ctx);
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
pi.on("session_start", (_event, ctx) => sync(ctx));
|
|
87
|
+
pi.on("model_select", (_event, ctx) => sync(ctx));
|
|
88
|
+
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* models.private.json: the same shape as models.json, read by this extension
|
|
3
|
+
* instead of by pi. It only adds providers; a key that would change a provider
|
|
4
|
+
* defined elsewhere is refused.
|
|
5
|
+
*/
|
|
6
|
+
import { isObj, readAgentJson, type Dict } from "./utils/read-agent-json.ts";
|
|
7
|
+
import { suggest } from "./utils/suggest.ts";
|
|
8
|
+
import { noDefaults, type PrivateDefaults } from "./defaults.ts";
|
|
9
|
+
|
|
10
|
+
export const PRIVATE_FILE = "models.private.json";
|
|
11
|
+
|
|
12
|
+
/** Parsed `<agentDir>/models.private.json`, or undefined when there is no such file. */
|
|
13
|
+
export const readPrivateFile = (): Dict | undefined => readAgentJson(PRIVATE_FILE);
|
|
14
|
+
|
|
15
|
+
export interface PrivateProvider {
|
|
16
|
+
/** Provider config as written, without `models`. */
|
|
17
|
+
config: Dict;
|
|
18
|
+
/** Model entries as written, `inherit` not resolved yet. */
|
|
19
|
+
models: Dict[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface ParsedFile {
|
|
23
|
+
providers: Map<string, PrivateProvider>;
|
|
24
|
+
defaults: PrivateDefaults;
|
|
25
|
+
issues: string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const FILE_KEYS = ["providers", "default"];
|
|
29
|
+
|
|
30
|
+
const PROVIDER_KEYS = ["name", "baseUrl", "api", "apiKey", "authHeader", "headers", "compat", "models"];
|
|
31
|
+
const PROVIDER_REJECTED: Dict = {
|
|
32
|
+
oauth: "oauth needs provider code, so it cannot come from a JSON file",
|
|
33
|
+
modelOverrides: "modelOverrides would change a model defined elsewhere",
|
|
34
|
+
inherit: "inherit belongs inside a models entry",
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const DEFAULT_KEYS = ["name", "baseUrl", "apiKey", "api", "authHeader", "headers", "compat"];
|
|
38
|
+
const DEFAULT_REJECTED: Dict = {
|
|
39
|
+
models: "default supplies values, not model definitions",
|
|
40
|
+
modelOverrides: "default supplies values, not model overrides",
|
|
41
|
+
oauth: "oauth needs provider code, so it cannot come from a JSON file",
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const MODEL_KEYS = [
|
|
45
|
+
"id", "name", "api", "baseUrl", "reasoning", "thinkingLevelMap", "input", "inputLimits", "cost",
|
|
46
|
+
"promptCache", "contextWindow", "maxTokens", "samplingParams", "headers", "compat", "inherit",
|
|
47
|
+
];
|
|
48
|
+
|
|
49
|
+
// pi's compat vocabulary. A key pi adds later is unknown here, so only a near
|
|
50
|
+
// miss is reported; anything else is left to pi.
|
|
51
|
+
const COMPAT_KEYS = [
|
|
52
|
+
"supportsStore", "supportsDeveloperRole", "supportsReasoningEffort", "supportsUsageInStreaming", "supportsFinishReason",
|
|
53
|
+
"maxTokensField", "requiresToolResultName", "requiresAssistantAfterToolResult", "requiresThinkingAsText",
|
|
54
|
+
"requiresReasoningContentOnAssistantMessages", "thinkingFormat", "chatTemplateKwargs", "chatTemplateArgs",
|
|
55
|
+
"cacheControlFormat", "openRouterRouting", "vercelGatewayRouting", "supportsOpenAIGrammarTools", "supportsStrictMode",
|
|
56
|
+
"sendSessionAffinityHeaders", "sessionAffinityFormat", "supportsLongCacheRetention", "vllmPriority", "zaiToolStream",
|
|
57
|
+
"supportsMaxOutputTokens", "supportsEagerToolInputStreaming", "supportsCacheControlOnTools", "supportsTemperature",
|
|
58
|
+
"forceAdaptiveThinking", "allowEmptySignature", "supportsStrictTools", "supportsMidConvoEffort", "allowedFallbackModels",
|
|
59
|
+
"supportsMidConvoSystemMessages", "supportsMidConvoToolAdditions", "supportsMidConvoToolChanges",
|
|
60
|
+
];
|
|
61
|
+
|
|
62
|
+
export function parsePrivateFile(file: Dict | undefined): ParsedFile {
|
|
63
|
+
const issues: string[] = [];
|
|
64
|
+
const providers = new Map<string, PrivateProvider>();
|
|
65
|
+
const defaults = noDefaults();
|
|
66
|
+
if (!file) return { providers, defaults, issues };
|
|
67
|
+
|
|
68
|
+
for (const key of Object.keys(file)) {
|
|
69
|
+
if (FILE_KEYS.includes(key)) continue;
|
|
70
|
+
const hint = suggest(key, FILE_KEYS);
|
|
71
|
+
issues.push(`"${key}" is not supported${hint ? `; did you mean "${hint}"` : ""} (valid: ${FILE_KEYS.join(", ")})`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
readDefaults(file.default, defaults, issues);
|
|
75
|
+
|
|
76
|
+
if (file.providers !== undefined && !isObj(file.providers)) {
|
|
77
|
+
issues.push('"providers" must be an object.');
|
|
78
|
+
return { providers, defaults, issues };
|
|
79
|
+
}
|
|
80
|
+
for (const [providerId, entry] of Object.entries((file.providers as Dict | undefined) ?? {})) {
|
|
81
|
+
const parsed = parseProvider(providerId, entry, issues);
|
|
82
|
+
if (parsed) providers.set(providerId, parsed);
|
|
83
|
+
}
|
|
84
|
+
return { providers, defaults, issues };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function parseProvider(providerId: string, entry: unknown, issues: string[]): PrivateProvider | undefined {
|
|
88
|
+
const where = `providers["${providerId}"]`;
|
|
89
|
+
if (providerId === "") {
|
|
90
|
+
issues.push("a provider id must not be empty.");
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
if (!isObj(entry)) {
|
|
94
|
+
issues.push(`${where} must be an object.`);
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
const config: Dict = {};
|
|
98
|
+
const models: Dict[] = [];
|
|
99
|
+
for (const [key, value] of Object.entries(entry)) {
|
|
100
|
+
if (key === "models") {
|
|
101
|
+
if (!Array.isArray(value)) issues.push(`${where}.models must be an array.`);
|
|
102
|
+
else value.forEach((model, index) => {
|
|
103
|
+
const parsed = parseModel(`${where}.models[${index}]`, model, issues);
|
|
104
|
+
if (parsed) models.push(parsed);
|
|
105
|
+
});
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (key in PROVIDER_REJECTED) {
|
|
109
|
+
issues.push(`${where}.${key} is ignored: ${PROVIDER_REJECTED[key]}.`);
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (!PROVIDER_KEYS.includes(key)) {
|
|
113
|
+
const hint = suggest(key, PROVIDER_KEYS);
|
|
114
|
+
issues.push(`${where}.${key} is ignored${hint ? `; did you mean "${hint}"` : ""} (valid: ${PROVIDER_KEYS.join(", ")})`);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
config[key] = value;
|
|
118
|
+
}
|
|
119
|
+
for (const key of ["name", "baseUrl", "api", "apiKey"]) {
|
|
120
|
+
if (config[key] !== undefined && (typeof config[key] !== "string" || config[key] === "")) issues.push(`${where}.${key} must be a non-empty string.`);
|
|
121
|
+
}
|
|
122
|
+
if (config.authHeader !== undefined && typeof config.authHeader !== "boolean") issues.push(`${where}.authHeader must be a boolean.`);
|
|
123
|
+
if (config.headers !== undefined) checkHeaders(`${where}.headers`, config.headers, issues);
|
|
124
|
+
if (config.compat !== undefined) checkCompat(`${where}.compat`, config.compat, issues);
|
|
125
|
+
if (models.length === 0) issues.push(`${where} is ignored: a private provider must define its "models".`);
|
|
126
|
+
return models.length > 0 ? { config, models } : undefined;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function parseModel(where: string, entry: unknown, issues: string[]): Dict | undefined {
|
|
130
|
+
if (!isObj(entry)) {
|
|
131
|
+
issues.push(`${where} must be an object.`);
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
for (const key of Object.keys(entry)) {
|
|
135
|
+
if (MODEL_KEYS.includes(key)) continue;
|
|
136
|
+
const hint = suggest(key, MODEL_KEYS);
|
|
137
|
+
issues.push(`${where}.${key} is ignored${hint ? `; did you mean "${hint}"` : ""} (valid: ${MODEL_KEYS.join(", ")})`);
|
|
138
|
+
}
|
|
139
|
+
if (typeof entry.id !== "string" || entry.id === "") {
|
|
140
|
+
issues.push(`${where}.id must be a non-empty string.`);
|
|
141
|
+
return undefined;
|
|
142
|
+
}
|
|
143
|
+
if (entry.inherit !== undefined && (typeof entry.inherit !== "string" || entry.inherit === "")) {
|
|
144
|
+
issues.push(`${where}.inherit must be a string like "provider/modelId".`);
|
|
145
|
+
}
|
|
146
|
+
for (const key of ["name", "api", "baseUrl"]) {
|
|
147
|
+
if (entry[key] !== undefined && typeof entry[key] !== "string") issues.push(`${where}.${key} must be a string.`);
|
|
148
|
+
}
|
|
149
|
+
if (entry.reasoning !== undefined && typeof entry.reasoning !== "boolean") issues.push(`${where}.reasoning must be a boolean.`);
|
|
150
|
+
if (entry.input !== undefined && (!Array.isArray(entry.input) || entry.input.some((kind) => kind !== "text" && kind !== "image"))) {
|
|
151
|
+
issues.push(`${where}.input must be an array of "text" and "image".`);
|
|
152
|
+
}
|
|
153
|
+
for (const key of ["contextWindow", "maxTokens"]) {
|
|
154
|
+
if (entry[key] !== undefined && (typeof entry[key] !== "number" || entry[key] <= 0)) issues.push(`${where}.${key} must be a positive number.`);
|
|
155
|
+
}
|
|
156
|
+
if (entry.cost !== undefined && !isObj(entry.cost)) issues.push(`${where}.cost must be an object.`);
|
|
157
|
+
if (entry.headers !== undefined) checkHeaders(`${where}.headers`, entry.headers, issues);
|
|
158
|
+
if (entry.compat !== undefined) checkCompat(`${where}.compat`, entry.compat, issues);
|
|
159
|
+
return entry;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function readDefaults(block: unknown, out: PrivateDefaults, issues: string[]): void {
|
|
163
|
+
if (block === undefined) return;
|
|
164
|
+
if (!isObj(block)) {
|
|
165
|
+
issues.push('"default" must be an object.');
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
for (const key of Object.keys(block)) if (key !== "providers") issues.push(`"default.${key}" is not supported; only "providers" is.`);
|
|
169
|
+
if (block.providers !== undefined && !isObj(block.providers)) {
|
|
170
|
+
issues.push('"default.providers" must be an object.');
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
for (const [id, entry] of Object.entries((block.providers as Dict | undefined) ?? {})) {
|
|
174
|
+
const where = `default.providers["${id}"]`;
|
|
175
|
+
if (!isObj(entry)) {
|
|
176
|
+
issues.push(`${where} must be an object.`);
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (Object.keys(entry).length === 0) {
|
|
180
|
+
issues.push(`${where} is empty.`);
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
const layer: Dict = {};
|
|
184
|
+
for (const [key, value] of Object.entries(entry)) {
|
|
185
|
+
if (key in DEFAULT_REJECTED) {
|
|
186
|
+
issues.push(`${where}.${key} is ignored: ${DEFAULT_REJECTED[key]}.`);
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
if (!DEFAULT_KEYS.includes(key)) {
|
|
190
|
+
const hint = suggest(key, DEFAULT_KEYS);
|
|
191
|
+
issues.push(`${where}.${key} is ignored${hint ? `; did you mean "${hint}"` : ""} (valid: ${DEFAULT_KEYS.join(", ")})`);
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
layer[key] = value;
|
|
195
|
+
}
|
|
196
|
+
for (const key of ["name", "baseUrl", "apiKey", "api"]) {
|
|
197
|
+
if (layer[key] !== undefined && (typeof layer[key] !== "string" || layer[key] === "")) issues.push(`${where}.${key} must be a non-empty string.`);
|
|
198
|
+
}
|
|
199
|
+
if (layer.authHeader !== undefined && typeof layer.authHeader !== "boolean") issues.push(`${where}.authHeader must be a boolean.`);
|
|
200
|
+
if (layer.headers !== undefined) checkHeaders(`${where}.headers`, layer.headers, issues);
|
|
201
|
+
if (layer.compat !== undefined) checkCompat(`${where}.compat`, layer.compat, issues);
|
|
202
|
+
if (id === "*") out.star = layer;
|
|
203
|
+
else out.exact.set(id, layer);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function checkHeaders(where: string, value: unknown, issues: string[]): void {
|
|
208
|
+
if (!isObj(value) || Object.values(value).some((header) => typeof header !== "string")) issues.push(`${where} must map strings to strings.`);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function checkCompat(where: string, value: unknown, issues: string[]): void {
|
|
212
|
+
if (!isObj(value)) {
|
|
213
|
+
issues.push(`${where} must be an object.`);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
for (const key of Object.keys(value)) {
|
|
217
|
+
if (COMPAT_KEYS.includes(key)) continue;
|
|
218
|
+
const hint = suggest(key, COMPAT_KEYS);
|
|
219
|
+
if (hint) issues.push(`${where}.${key} is ignored; did you mean "${hint}"?`);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `inherit` inside models.private.json, plus the model fields pi fills in for
|
|
3
|
+
* models.json entries but not for providers that an extension registers.
|
|
4
|
+
*
|
|
5
|
+
* `inherit` copies another model's configuration into an entry: everything
|
|
6
|
+
* except `id`, `provider` and `baseUrl`, and a value written on the entry itself
|
|
7
|
+
* always wins.
|
|
8
|
+
*/
|
|
9
|
+
import { isObj, type Dict } from "./utils/read-agent-json.ts";
|
|
10
|
+
import { merge, omit } from "./utils/fields.ts";
|
|
11
|
+
import { suggest } from "./utils/suggest.ts";
|
|
12
|
+
import type { PrivateProvider } from "./private-file.ts";
|
|
13
|
+
|
|
14
|
+
/** Fields an entry keeps for itself. */
|
|
15
|
+
export const LOCAL_KEYS = ["id", "provider", "baseUrl", "inherit"];
|
|
16
|
+
|
|
17
|
+
/** Where an inherited model's fields come from. */
|
|
18
|
+
export interface Lookup {
|
|
19
|
+
/** Entry as written: the private file first, then models.json. */
|
|
20
|
+
entry(providerId: string, modelId: string): Dict | undefined;
|
|
21
|
+
/** Model pi composed, for targets that are not written in a file. */
|
|
22
|
+
model(providerId: string, modelId: string): Dict | undefined;
|
|
23
|
+
/** Model ids of a provider, for the did-you-mean hint. */
|
|
24
|
+
ids(providerId: string): string[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface Plan {
|
|
28
|
+
/** providerId -> its models entries with `inherit` resolved. */
|
|
29
|
+
models: Map<string, Dict[]>;
|
|
30
|
+
issues: string[];
|
|
31
|
+
/** References with no target. Only a problem once pi is running: catalogs live there. */
|
|
32
|
+
unresolved: string[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Providers in a models.json, used both as resolve targets and for provider ids. */
|
|
36
|
+
export const fileProviders = (file: Dict | undefined): Dict => (isObj(file?.providers) ? file.providers : {});
|
|
37
|
+
|
|
38
|
+
const entriesOf = (providers: Dict, providerId: string): Dict[] => {
|
|
39
|
+
const entry = providers[providerId];
|
|
40
|
+
return isObj(entry) && Array.isArray(entry.models) ? entry.models.filter(isObj) : [];
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
export function planInherit(providers: Map<string, PrivateProvider>, lookup: Lookup, knownProviders: ReadonlySet<string>): Plan {
|
|
44
|
+
const models = new Map<string, Dict[]>();
|
|
45
|
+
const issues: string[] = [];
|
|
46
|
+
const unresolved: string[] = [];
|
|
47
|
+
|
|
48
|
+
/** `"provider/modelId"`, or a model of this provider when the prefix is no provider. */
|
|
49
|
+
const splitRef = (ref: string, providerId: string): [string, string] => {
|
|
50
|
+
const slash = ref.indexOf("/");
|
|
51
|
+
return slash > 0 && knownProviders.has(ref.slice(0, slash)) ? [ref.slice(0, slash), ref.slice(slash + 1)] : [providerId, ref];
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/** Closest existing reference, for the did-you-mean hint. */
|
|
55
|
+
const nearest = (providerId: string, modelId: string): string | undefined => {
|
|
56
|
+
const nearModel = suggest(modelId, lookup.ids(providerId));
|
|
57
|
+
if (nearModel) return `${providerId}/${nearModel}`;
|
|
58
|
+
const nearProvider = suggest(providerId, [...knownProviders]);
|
|
59
|
+
return nearProvider && nearProvider !== providerId ? `${nearProvider}/${modelId}` : undefined;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/** Fields a target contributes; "cycle" when following `inherit` loops back. */
|
|
63
|
+
const fieldsOf = (providerId: string, modelId: string, chain: string[]): Dict | "cycle" | undefined => {
|
|
64
|
+
const key = `${providerId}/${modelId}`;
|
|
65
|
+
if (chain.includes(key)) return "cycle";
|
|
66
|
+
const entry = lookup.entry(providerId, modelId);
|
|
67
|
+
const written = entry ?? lookup.model(providerId, modelId);
|
|
68
|
+
if (!written) return undefined;
|
|
69
|
+
const own = omit(written, LOCAL_KEYS);
|
|
70
|
+
const ref = entry?.inherit;
|
|
71
|
+
if (typeof ref !== "string" || ref === "") return own;
|
|
72
|
+
const [provider, model] = splitRef(ref, providerId);
|
|
73
|
+
const parent = fieldsOf(provider, model, [...chain, key]);
|
|
74
|
+
if (parent === "cycle" || parent === undefined) return parent;
|
|
75
|
+
return merge(parent, own);
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
for (const [providerId, provider] of providers) {
|
|
79
|
+
models.set(providerId, provider.models.map((entry) => {
|
|
80
|
+
const ref = entry.inherit;
|
|
81
|
+
if (typeof ref !== "string" || ref === "") return omit(entry, ["inherit"]);
|
|
82
|
+
const where = `providers["${providerId}"].models "${entry.id}"`;
|
|
83
|
+
const [provider, model] = splitRef(ref, providerId);
|
|
84
|
+
const inherited = fieldsOf(provider, model, []);
|
|
85
|
+
if (inherited === "cycle") {
|
|
86
|
+
issues.push(`${where}: inherit "${ref}" forms a cycle; ignored.`);
|
|
87
|
+
return omit(entry, ["inherit"]);
|
|
88
|
+
}
|
|
89
|
+
if (inherited === undefined) {
|
|
90
|
+
const near = nearest(provider, model);
|
|
91
|
+
unresolved.push(`${where}: inherit target "${ref}" was not found${near ? `; did you mean "${near}"?` : ""}`);
|
|
92
|
+
return omit(entry, ["inherit"]);
|
|
93
|
+
}
|
|
94
|
+
return merge(inherited, omit(entry, ["inherit"]));
|
|
95
|
+
}));
|
|
96
|
+
}
|
|
97
|
+
return { models, issues, unresolved };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Stage one: everything written in a file, no runtime yet. */
|
|
101
|
+
export function fileLookup(providers: Map<string, PrivateProvider>, publicFile: Dict | undefined): Lookup {
|
|
102
|
+
const publicProviders = fileProviders(publicFile);
|
|
103
|
+
const entries = (providerId: string): Dict[] => [...(providers.get(providerId)?.models ?? []), ...entriesOf(publicProviders, providerId)];
|
|
104
|
+
return {
|
|
105
|
+
entry: (providerId, modelId) => entries(providerId).find((entry) => entry.id === modelId),
|
|
106
|
+
model: () => undefined,
|
|
107
|
+
ids: (providerId) => entries(providerId).map((entry) => entry.id),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Stage two: the private file first, then what pi composed. */
|
|
112
|
+
export function storeLookup(providers: Map<string, PrivateProvider>, runtime: any): Lookup {
|
|
113
|
+
const composed = (providerId: string): Dict[] => {
|
|
114
|
+
try {
|
|
115
|
+
const models = runtime?.models?.getModels?.(providerId);
|
|
116
|
+
return Array.isArray(models) ? models : [];
|
|
117
|
+
} catch {
|
|
118
|
+
return [];
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
const ids = (providerId: string): string[] => [...(providers.get(providerId)?.models ?? []), ...composed(providerId)]
|
|
122
|
+
.map((entry) => entry?.id)
|
|
123
|
+
.filter((id): id is string => typeof id === "string");
|
|
124
|
+
return {
|
|
125
|
+
entry: (providerId, modelId) => providers.get(providerId)?.models.find((entry) => entry.id === modelId),
|
|
126
|
+
model: (providerId, modelId) => composed(providerId).find((model) => model?.id === modelId),
|
|
127
|
+
ids,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Fields pi fills in for models.json entries: a registered provider has to carry them itself. */
|
|
132
|
+
export function withModelDefaults(entry: Dict): Dict {
|
|
133
|
+
const cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, ...(isObj(entry.cost) ? entry.cost : {}) };
|
|
134
|
+
return {
|
|
135
|
+
...entry,
|
|
136
|
+
name: typeof entry.name === "string" ? entry.name : entry.id,
|
|
137
|
+
reasoning: typeof entry.reasoning === "boolean" ? entry.reasoning : false,
|
|
138
|
+
input: Array.isArray(entry.input) ? entry.input : ["text"],
|
|
139
|
+
cost,
|
|
140
|
+
contextWindow: typeof entry.contextWindow === "number" ? entry.contextWindow : 128000,
|
|
141
|
+
maxTokens: typeof entry.maxTokens === "number" ? entry.maxTokens : 16384,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Provider ids known before pi starts: the private file, models.json, and what is handed in. */
|
|
146
|
+
export const providerIdsOf = (file: Dict | undefined): string[] => Object.keys(fileProviders(file));
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Field-level operations, following pi's own merge rules: object-valued fields
|
|
3
|
+
* merge key by key, everything else is replaced.
|
|
4
|
+
*/
|
|
5
|
+
import { isObj, type Dict } from "./read-agent-json.ts";
|
|
6
|
+
|
|
7
|
+
const NESTED_KEYS = ["compat", "headers", "openRouterRouting", "vercelGatewayRouting", "chatTemplateKwargs", "chatTemplateArgs"];
|
|
8
|
+
|
|
9
|
+
/** `override` wins per key; nested object fields merge one level deeper. */
|
|
10
|
+
export function merge(base: Dict, override: Dict): Dict {
|
|
11
|
+
const merged: Dict = { ...base, ...override };
|
|
12
|
+
for (const key of NESTED_KEYS) {
|
|
13
|
+
if (isObj(base[key]) && isObj(override[key])) merged[key] = { ...base[key], ...override[key] };
|
|
14
|
+
}
|
|
15
|
+
return merged;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Subset of `source` holding only defined values for `keys`. */
|
|
19
|
+
export function pick(source: Dict | undefined, keys: readonly string[]): Dict | undefined {
|
|
20
|
+
if (!source) return undefined;
|
|
21
|
+
const out: Dict = {};
|
|
22
|
+
for (const key of keys) if (source[key] !== undefined) out[key] = source[key];
|
|
23
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Copy of `source` without `keys`. Undefined values are dropped, so they never mask an inherited field. */
|
|
27
|
+
export function omit(source: Dict, keys: readonly string[]): Dict {
|
|
28
|
+
const out: Dict = {};
|
|
29
|
+
for (const [key, value] of Object.entries(source)) if (value !== undefined && !keys.includes(key)) out[key] = value;
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read the JSON files in pi's agent directory, and narrow unknown JSON values.
|
|
3
|
+
* Tolerates comments and trailing commas exactly like pi's own reader.
|
|
4
|
+
*/
|
|
5
|
+
import { readFileSync } from "node:fs";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
|
|
9
|
+
export type Dict = Record<string, any>;
|
|
10
|
+
|
|
11
|
+
export const isObj = (value: unknown): value is Dict =>
|
|
12
|
+
typeof value === "object" && value !== null && !Array.isArray(value) && !Buffer.isBuffer(value);
|
|
13
|
+
|
|
14
|
+
/** pi's agent directory (this package imports pi types only, so resolve it here). */
|
|
15
|
+
export function agentDir(): string {
|
|
16
|
+
const dir = process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
|
|
17
|
+
return dir.startsWith("~") ? join(homedir(), dir.slice(1)) : dir;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Parsed `<agentDir>/<name>`, or undefined when it is missing, unreadable or not an object. */
|
|
21
|
+
export function readAgentJson(name: string): Dict | undefined {
|
|
22
|
+
try {
|
|
23
|
+
const text = readFileSync(join(agentDir(), name), "utf8").replace(/^\uFEFF/, "");
|
|
24
|
+
const parsed: unknown = JSON.parse(stripJsonComments(text));
|
|
25
|
+
return isObj(parsed) ? parsed : undefined;
|
|
26
|
+
} catch {
|
|
27
|
+
return undefined; // pi reports its own errors
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const stripJsonComments = (input: string): string =>
|
|
32
|
+
input
|
|
33
|
+
.replace(/"(?:\\.|[^"\\])*"|\/\/[^\n]*/g, (m) => (m[0] === '"' ? m : ""))
|
|
34
|
+
.replace(/"(?:\\.|[^"\\])*"|,(\s*[}\]])/g, (m: string, tail: string) => tail ?? (m[0] === '"' ? m : ""));
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Near-miss matching for "did you mean" hints. Only clearly similar names count,
|
|
3
|
+
* so a key pi adds later never triggers a bogus suggestion.
|
|
4
|
+
*/
|
|
5
|
+
export function suggest(key: string, known: readonly string[]): string | undefined {
|
|
6
|
+
let best: string | undefined;
|
|
7
|
+
let score = Infinity;
|
|
8
|
+
for (const candidate of known) {
|
|
9
|
+
const d = distance(key.toLowerCase(), candidate.toLowerCase());
|
|
10
|
+
if (d < score) {
|
|
11
|
+
score = d;
|
|
12
|
+
best = candidate;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
if (best === undefined) return undefined;
|
|
16
|
+
if (score <= 2) return best;
|
|
17
|
+
const a = key.toLowerCase();
|
|
18
|
+
const b = best.toLowerCase();
|
|
19
|
+
return a.length >= 6 && (b.startsWith(a) || a.startsWith(b)) ? best : undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function distance(a: string, b: string): number {
|
|
23
|
+
let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
24
|
+
for (let i = 1; i <= a.length; i++) {
|
|
25
|
+
const next = [i];
|
|
26
|
+
for (let j = 1; j <= b.length; j++) {
|
|
27
|
+
next[j] = Math.min(prev[j] + 1, next[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
28
|
+
}
|
|
29
|
+
prev = next;
|
|
30
|
+
}
|
|
31
|
+
return prev[b.length];
|
|
32
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "pi-private-models",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "pi extension that keeps private model providers out of the published models.json",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"pi-package"
|
|
9
|
+
],
|
|
10
|
+
"pi": {
|
|
11
|
+
"extensions": [
|
|
12
|
+
"./extensions/private-models/index.ts"
|
|
13
|
+
]
|
|
14
|
+
},
|
|
15
|
+
"scripts": {
|
|
16
|
+
"test": "node --experimental-strip-types --no-warnings --test tests/*.test.ts"
|
|
17
|
+
},
|
|
18
|
+
"peerDependencies": {
|
|
19
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"extensions",
|
|
23
|
+
"README.md",
|
|
24
|
+
"README.zh-CN.md",
|
|
25
|
+
"LICENSE"
|
|
26
|
+
]
|
|
27
|
+
}
|