@mcowger/pi-plexus 0.2.4 → 0.4.2
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 +82 -68
- package/package.json +15 -13
- package/src/map-models.ts +112 -0
- package/src/pi-compat.ts +7 -0
- package/README.md +0 -81
- package/src/plexus-cache.ts +0 -52
- package/src/plexus-config.ts +0 -58
- package/src/plexus-log.ts +0 -17
- package/src/plexus-models.ts +0 -318
package/index.ts
CHANGED
|
@@ -1,10 +1,21 @@
|
|
|
1
1
|
import type { ExtensionAPI, ProviderConfig } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import type { Api } from "@earendil-works/pi-ai";
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
3
|
+
import {
|
|
4
|
+
readCachedModelsSync,
|
|
5
|
+
writeCachedModels,
|
|
6
|
+
writeRawResponse,
|
|
7
|
+
getBaseUrl,
|
|
8
|
+
getModelsUrl,
|
|
9
|
+
saveBaseUrl,
|
|
10
|
+
getDefaultModel,
|
|
11
|
+
fetchPlexusModels,
|
|
12
|
+
convertDescriptors,
|
|
13
|
+
log,
|
|
14
|
+
} from "@mcowger/plexus-models";
|
|
15
|
+
import type { PlexusModelDescriptor } from "@mcowger/plexus-models";
|
|
16
|
+
import { getAgentDir } from "./src/pi-compat.js";
|
|
17
|
+
import { mapDescriptorsToPiModels } from "./src/map-models.js";
|
|
18
|
+
import type { PiModel } from "./src/map-models.js";
|
|
8
19
|
|
|
9
20
|
const PLEXUS_PROVIDER = "plexus";
|
|
10
21
|
|
|
@@ -16,96 +27,101 @@ const createProviderConfig = (models: PiModel[], baseUrl: string): ProviderConfi
|
|
|
16
27
|
models,
|
|
17
28
|
});
|
|
18
29
|
|
|
19
|
-
// Store current
|
|
20
|
-
let
|
|
30
|
+
// Store current descriptors globally for use by setDefaultModel
|
|
31
|
+
let currentDescriptors: PlexusModelDescriptor[] = [];
|
|
21
32
|
|
|
22
|
-
const attemptLiveRefresh = async (
|
|
23
|
-
|
|
24
|
-
|
|
33
|
+
const attemptLiveRefresh = async (
|
|
34
|
+
pi: ExtensionAPI,
|
|
35
|
+
apiKey: string,
|
|
36
|
+
agentDir: string,
|
|
37
|
+
setDefault = true,
|
|
38
|
+
): Promise<void> => {
|
|
39
|
+
const baseUrl = getBaseUrl(agentDir);
|
|
40
|
+
const modelsUrl = getModelsUrl(agentDir);
|
|
25
41
|
|
|
26
|
-
log("attemptLiveRefresh", { hasApiKey: !!apiKey, baseUrl, modelsUrl });
|
|
42
|
+
log(agentDir, "attemptLiveRefresh", { hasApiKey: !!apiKey, baseUrl, modelsUrl });
|
|
27
43
|
|
|
28
44
|
if (!baseUrl || !modelsUrl) {
|
|
29
|
-
log("attemptLiveRefresh: missing baseUrl, skipping");
|
|
45
|
+
log(agentDir, "attemptLiveRefresh: missing baseUrl, skipping");
|
|
30
46
|
return;
|
|
31
47
|
}
|
|
32
48
|
|
|
33
49
|
try {
|
|
34
50
|
const { models: apiModels, raw } = await fetchPlexusModels(apiKey, modelsUrl);
|
|
35
|
-
const
|
|
51
|
+
const descriptors = convertDescriptors(apiModels, baseUrl);
|
|
52
|
+
const piModels = mapDescriptorsToPiModels(descriptors, baseUrl);
|
|
36
53
|
|
|
37
|
-
log("attemptLiveRefresh: fetched models", { count:
|
|
54
|
+
log(agentDir, "attemptLiveRefresh: fetched models", { count: piModels.length });
|
|
38
55
|
|
|
39
|
-
await Promise.all([writeCachedModels(
|
|
40
|
-
|
|
41
|
-
pi.registerProvider(PLEXUS_PROVIDER, createProviderConfig(
|
|
42
|
-
log("attemptLiveRefresh: provider registered");
|
|
56
|
+
await Promise.all([writeCachedModels(agentDir, descriptors), writeRawResponse(agentDir, raw)]);
|
|
57
|
+
currentDescriptors = descriptors;
|
|
58
|
+
pi.registerProvider(PLEXUS_PROVIDER, createProviderConfig(piModels, baseUrl));
|
|
59
|
+
log(agentDir, "attemptLiveRefresh: provider registered");
|
|
43
60
|
|
|
44
|
-
// Set default model after registering new provider
|
|
45
61
|
if (setDefault) {
|
|
46
|
-
await setDefaultModel(pi,
|
|
62
|
+
await setDefaultModel(pi, agentDir, descriptors);
|
|
47
63
|
}
|
|
48
64
|
} catch (error) {
|
|
49
|
-
log("attemptLiveRefresh: fetch failed", { error: String(error) });
|
|
65
|
+
log(agentDir, "attemptLiveRefresh: fetch failed", { error: String(error) });
|
|
50
66
|
}
|
|
51
67
|
};
|
|
52
68
|
|
|
53
|
-
const setDefaultModel = async (
|
|
54
|
-
|
|
69
|
+
const setDefaultModel = async (
|
|
70
|
+
pi: ExtensionAPI,
|
|
71
|
+
agentDir: string,
|
|
72
|
+
descriptors?: PlexusModelDescriptor[],
|
|
73
|
+
): Promise<void> => {
|
|
74
|
+
const defaultModelId = getDefaultModel(agentDir);
|
|
55
75
|
if (!defaultModelId) return;
|
|
56
76
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
log("setDefaultModel: no models available", { defaultModelId });
|
|
77
|
+
const list = descriptors ?? currentDescriptors;
|
|
78
|
+
if (!list || list.length === 0) {
|
|
79
|
+
log(agentDir, "setDefaultModel: no models available", { defaultModelId });
|
|
61
80
|
return;
|
|
62
81
|
}
|
|
63
82
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
// Find model by ID in our list
|
|
70
|
-
const model = modelList.find(m => m.id === defaultModelId);
|
|
71
|
-
|
|
72
|
-
if (!model) {
|
|
73
|
-
log("setDefaultModel: model not found in list", { defaultModelId });
|
|
83
|
+
const descriptor = list.find((d) => d.id === defaultModelId);
|
|
84
|
+
if (!descriptor) {
|
|
85
|
+
log(agentDir, "setDefaultModel: model not found", { defaultModelId });
|
|
74
86
|
return;
|
|
75
87
|
}
|
|
76
88
|
|
|
77
|
-
const
|
|
78
|
-
|
|
89
|
+
const baseUrl = getBaseUrl(agentDir) ?? descriptor.baseUrl;
|
|
90
|
+
const piModel = mapDescriptorsToPiModels([descriptor], baseUrl)[0];
|
|
91
|
+
if (!piModel) return;
|
|
92
|
+
|
|
93
|
+
const success = await pi.setModel(piModel);
|
|
94
|
+
log(agentDir, "setDefaultModel", { defaultModelId, success });
|
|
79
95
|
};
|
|
80
96
|
|
|
81
97
|
export default function plexusExtension(pi: ExtensionAPI) {
|
|
82
|
-
const
|
|
83
|
-
const
|
|
84
|
-
const
|
|
98
|
+
const agentDir = getAgentDir();
|
|
99
|
+
const cached = readCachedModelsSync(agentDir);
|
|
100
|
+
const startupBaseUrl = getBaseUrl(agentDir) ?? "http://localhost/v1";
|
|
101
|
+
const startupDescriptors = cached?.models ?? [];
|
|
102
|
+
const startupModels = mapDescriptorsToPiModels(startupDescriptors, startupBaseUrl);
|
|
85
103
|
|
|
86
|
-
log("startup", {
|
|
104
|
+
log(agentDir, "startup", {
|
|
87
105
|
cachedModelCount: startupModels.length,
|
|
88
106
|
startupBaseUrl,
|
|
89
|
-
sampleCachedModelBaseUrl: startupModels[0]?.baseUrl,
|
|
90
107
|
});
|
|
91
108
|
|
|
92
109
|
pi.registerProvider(PLEXUS_PROVIDER, createProviderConfig(startupModels, startupBaseUrl));
|
|
93
|
-
|
|
110
|
+
currentDescriptors = startupDescriptors;
|
|
94
111
|
|
|
95
112
|
pi.on("session_start", async (_event, ctx) => {
|
|
96
113
|
const apiKey = await ctx.modelRegistry.authStorage.getApiKey(PLEXUS_PROVIDER);
|
|
97
|
-
const baseUrl = getBaseUrl();
|
|
114
|
+
const baseUrl = getBaseUrl(agentDir);
|
|
98
115
|
|
|
99
|
-
log("session_start", { hasApiKey: !!apiKey, baseUrl });
|
|
116
|
+
log(agentDir, "session_start", { hasApiKey: !!apiKey, baseUrl });
|
|
100
117
|
|
|
101
118
|
if (!apiKey || !baseUrl) {
|
|
102
|
-
log("session_start: no auth configured, skipping refresh");
|
|
103
|
-
|
|
104
|
-
await setDefaultModel(pi, startupModels);
|
|
119
|
+
log(agentDir, "session_start: no auth configured, skipping refresh");
|
|
120
|
+
await setDefaultModel(pi, agentDir, startupDescriptors);
|
|
105
121
|
return;
|
|
106
122
|
}
|
|
107
123
|
|
|
108
|
-
await attemptLiveRefresh(pi, apiKey, true);
|
|
124
|
+
await attemptLiveRefresh(pi, apiKey, agentDir, true);
|
|
109
125
|
});
|
|
110
126
|
|
|
111
127
|
pi.registerCommand("plexus", {
|
|
@@ -124,28 +140,25 @@ export default function plexusExtension(pi: ExtensionAPI) {
|
|
|
124
140
|
const apiKey = await ctx.ui.input("Plexus API key");
|
|
125
141
|
if (!apiKey) return;
|
|
126
142
|
|
|
127
|
-
// Prompt for default model (optional)
|
|
128
143
|
const defaultModel = await ctx.ui.input("Default model (optional)", "");
|
|
129
144
|
const defaultModelTrimmed = defaultModel?.trim() || undefined;
|
|
130
145
|
|
|
131
|
-
await saveBaseUrl(baseUrl.trim(), defaultModelTrimmed);
|
|
146
|
+
await saveBaseUrl(agentDir, baseUrl.trim(), defaultModelTrimmed);
|
|
132
147
|
ctx.modelRegistry.authStorage.set(PLEXUS_PROVIDER, { type: "api_key", key: apiKey.trim() });
|
|
133
148
|
|
|
134
|
-
log("login: saved", { baseUrl: baseUrl.trim(), defaultModel: defaultModelTrimmed });
|
|
149
|
+
log(agentDir, "login: saved", { baseUrl: baseUrl.trim(), defaultModel: defaultModelTrimmed });
|
|
135
150
|
ctx.ui.notify("Plexus credentials saved", "info");
|
|
136
151
|
|
|
137
|
-
await attemptLiveRefresh(pi, apiKey.trim(), false);
|
|
138
|
-
|
|
139
|
-
// Set default model after refresh (attemptLiveRefresh handles it when setDefault=true)
|
|
152
|
+
await attemptLiveRefresh(pi, apiKey.trim(), agentDir, false);
|
|
140
153
|
return;
|
|
141
154
|
}
|
|
142
155
|
|
|
143
156
|
if (sub === "refresh") {
|
|
144
157
|
const apiKey = await ctx.modelRegistry.authStorage.getApiKey(PLEXUS_PROVIDER);
|
|
145
|
-
const baseUrl = getBaseUrl();
|
|
146
|
-
const modelsUrl = getModelsUrl();
|
|
158
|
+
const baseUrl = getBaseUrl(agentDir);
|
|
159
|
+
const modelsUrl = getModelsUrl(agentDir);
|
|
147
160
|
|
|
148
|
-
log("refresh command", { hasApiKey: !!apiKey, baseUrl });
|
|
161
|
+
log(agentDir, "refresh command", { hasApiKey: !!apiKey, baseUrl });
|
|
149
162
|
|
|
150
163
|
if (!apiKey) {
|
|
151
164
|
ctx.ui.notify("No Plexus API key configured. Run /plexus login first.", "error");
|
|
@@ -159,18 +172,19 @@ export default function plexusExtension(pi: ExtensionAPI) {
|
|
|
159
172
|
try {
|
|
160
173
|
ctx.ui.notify("Fetching Plexus models...", "info");
|
|
161
174
|
const { models: apiModels, raw } = await fetchPlexusModels(apiKey, modelsUrl);
|
|
162
|
-
const
|
|
175
|
+
const descriptors = convertDescriptors(apiModels, baseUrl);
|
|
176
|
+
const piModels = mapDescriptorsToPiModels(descriptors, baseUrl);
|
|
163
177
|
|
|
164
|
-
await Promise.all([writeCachedModels(
|
|
165
|
-
|
|
178
|
+
await Promise.all([writeCachedModels(agentDir, descriptors), writeRawResponse(agentDir, raw)]);
|
|
179
|
+
currentDescriptors = descriptors;
|
|
180
|
+
pi.registerProvider(PLEXUS_PROVIDER, createProviderConfig(piModels, baseUrl));
|
|
166
181
|
|
|
167
|
-
log("refresh command: done", { count:
|
|
168
|
-
ctx.ui.notify(`Refreshed ${
|
|
182
|
+
log(agentDir, "refresh command: done", { count: piModels.length });
|
|
183
|
+
ctx.ui.notify(`Refreshed ${piModels.length} Plexus models`, "info");
|
|
169
184
|
|
|
170
|
-
|
|
171
|
-
await setDefaultModel(pi, currentModels);
|
|
185
|
+
await setDefaultModel(pi, agentDir);
|
|
172
186
|
} catch (error) {
|
|
173
|
-
log("refresh command: failed", { error: String(error) });
|
|
187
|
+
log(agentDir, "refresh command: failed", { error: String(error) });
|
|
174
188
|
ctx.ui.notify(`Refresh failed: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
175
189
|
}
|
|
176
190
|
return;
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mcowger/pi-plexus",
|
|
3
3
|
"author": "Matt Cowger",
|
|
4
|
-
"version": "0.2
|
|
5
|
-
"description": "Plexus AI provider extension
|
|
4
|
+
"version": "0.4.2",
|
|
5
|
+
"description": "Plexus AI provider extension for pi (earendil-works fork)",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"keywords": [
|
|
@@ -22,25 +22,27 @@
|
|
|
22
22
|
"LICENSE"
|
|
23
23
|
],
|
|
24
24
|
"scripts": {
|
|
25
|
-
"postinstall": "command -v lefthook >/dev/null 2>&1 && lefthook install || true",
|
|
26
25
|
"check": "bunx tsc --noEmit",
|
|
27
|
-
"test": "bun test"
|
|
28
|
-
"format": "biome format --write .",
|
|
29
|
-
"format:check": "biome format .",
|
|
30
|
-
"lint": "biome lint .",
|
|
31
|
-
"pack:dry-run": "bun pack --dry-run"
|
|
26
|
+
"test": "bun test"
|
|
32
27
|
},
|
|
33
|
-
"
|
|
34
|
-
"@
|
|
35
|
-
"lefthook": "2.1.8"
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@mcowger/plexus-models": "0.4.0"
|
|
36
30
|
},
|
|
37
31
|
"peerDependencies": {
|
|
38
|
-
"@earendil-works/pi-ai": "0.75.
|
|
39
|
-
"@earendil-works/pi-coding-agent": "0.75.
|
|
32
|
+
"@earendil-works/pi-ai": ">=0.75.0",
|
|
33
|
+
"@earendil-works/pi-coding-agent": ">=0.75.0"
|
|
40
34
|
},
|
|
41
35
|
"pi": {
|
|
42
36
|
"extensions": [
|
|
43
37
|
"./index.ts"
|
|
44
38
|
]
|
|
39
|
+
},
|
|
40
|
+
"repository": {
|
|
41
|
+
"type": "git",
|
|
42
|
+
"url": "git+https://github.com/mcowger/pi-plexus.git",
|
|
43
|
+
"directory": "packages/pi-plexus"
|
|
44
|
+
},
|
|
45
|
+
"publishConfig": {
|
|
46
|
+
"access": "public"
|
|
45
47
|
}
|
|
46
48
|
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
Api,
|
|
3
|
+
Model,
|
|
4
|
+
OpenAICompletionsCompat,
|
|
5
|
+
OpenAIResponsesCompat,
|
|
6
|
+
AnthropicMessagesCompat,
|
|
7
|
+
} from "@earendil-works/pi-ai";
|
|
8
|
+
import type { PlexusModelDescriptor } from "@mcowger/plexus-models";
|
|
9
|
+
import { adjustBaseUrl, detectOpenAICompletionsCompat } from "@mcowger/plexus-models";
|
|
10
|
+
import { lookupModel } from "./pi-compat.js";
|
|
11
|
+
|
|
12
|
+
export type PiModel = Model<Api>;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Look up a curated model definition from pi's built-in MODELS registry
|
|
16
|
+
* using the piProvider/piModel hints from the descriptor.
|
|
17
|
+
* Returns null if either hint is missing or the model isn't found.
|
|
18
|
+
*/
|
|
19
|
+
const lookupPiModel = (piProvider?: string, piModel?: string): Model<Api> | null => {
|
|
20
|
+
if (!piProvider || !piModel) return null;
|
|
21
|
+
return (lookupModel as (p: string, m: string) => Model<Api> | undefined)(piProvider, piModel) ?? null;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Resolve a fully-specified compat object for a plexus-proxied model by
|
|
26
|
+
* merging the pi model's stored compat overrides onto the detected defaults
|
|
27
|
+
* from the pi model's original provider/baseUrl.
|
|
28
|
+
*/
|
|
29
|
+
const resolveCompat = (
|
|
30
|
+
piModel: Model<Api>,
|
|
31
|
+
): OpenAICompletionsCompat | OpenAIResponsesCompat | AnthropicMessagesCompat | undefined => {
|
|
32
|
+
if (piModel.api === "openai-completions") {
|
|
33
|
+
const detected = detectOpenAICompletionsCompat(piModel.provider, piModel.baseUrl) as OpenAICompletionsCompat;
|
|
34
|
+
const overrides = piModel.compat as OpenAICompletionsCompat | undefined;
|
|
35
|
+
if (!overrides) return detected;
|
|
36
|
+
return {
|
|
37
|
+
supportsStore: overrides.supportsStore ?? detected.supportsStore,
|
|
38
|
+
supportsDeveloperRole: overrides.supportsDeveloperRole ?? detected.supportsDeveloperRole,
|
|
39
|
+
supportsReasoningEffort: overrides.supportsReasoningEffort ?? detected.supportsReasoningEffort,
|
|
40
|
+
supportsUsageInStreaming: overrides.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,
|
|
41
|
+
maxTokensField: overrides.maxTokensField ?? detected.maxTokensField,
|
|
42
|
+
requiresToolResultName: overrides.requiresToolResultName ?? detected.requiresToolResultName,
|
|
43
|
+
requiresAssistantAfterToolResult:
|
|
44
|
+
overrides.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,
|
|
45
|
+
requiresThinkingAsText: overrides.requiresThinkingAsText ?? detected.requiresThinkingAsText,
|
|
46
|
+
requiresReasoningContentOnAssistantMessages:
|
|
47
|
+
overrides.requiresReasoningContentOnAssistantMessages ?? detected.requiresReasoningContentOnAssistantMessages,
|
|
48
|
+
thinkingFormat: overrides.thinkingFormat ?? detected.thinkingFormat,
|
|
49
|
+
openRouterRouting: overrides.openRouterRouting ?? detected.openRouterRouting,
|
|
50
|
+
vercelGatewayRouting: overrides.vercelGatewayRouting ?? detected.vercelGatewayRouting,
|
|
51
|
+
zaiToolStream: overrides.zaiToolStream ?? detected.zaiToolStream,
|
|
52
|
+
supportsStrictMode: overrides.supportsStrictMode ?? detected.supportsStrictMode,
|
|
53
|
+
cacheControlFormat: overrides.cacheControlFormat ?? detected.cacheControlFormat,
|
|
54
|
+
sendSessionAffinityHeaders: overrides.sendSessionAffinityHeaders ?? detected.sendSessionAffinityHeaders,
|
|
55
|
+
supportsLongCacheRetention: overrides.supportsLongCacheRetention ?? detected.supportsLongCacheRetention,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
return piModel.compat;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Map a PlexusModelDescriptor to a pi PiModel (Model<Api>).
|
|
63
|
+
*
|
|
64
|
+
* When piProvider/piModel hints are present, looks up the curated definition
|
|
65
|
+
* from pi's MODELS registry and merges it with plexus-specific fields for
|
|
66
|
+
* maximum fidelity (correct compat, thinkingLevelMap, etc.).
|
|
67
|
+
*
|
|
68
|
+
* Falls back to the descriptor's own fields when no registry match is found.
|
|
69
|
+
*/
|
|
70
|
+
export const mapDescriptorToPiModel = (descriptor: PlexusModelDescriptor, baseUrl: string): PiModel => {
|
|
71
|
+
const piModelDef = lookupPiModel(descriptor.piProvider, descriptor.piModel);
|
|
72
|
+
|
|
73
|
+
if (piModelDef) {
|
|
74
|
+
const resolvedCompat = resolveCompat(piModelDef);
|
|
75
|
+
return {
|
|
76
|
+
id: descriptor.id,
|
|
77
|
+
name: descriptor.name ?? piModelDef.name ?? descriptor.id,
|
|
78
|
+
api: piModelDef.api,
|
|
79
|
+
provider: "plexus",
|
|
80
|
+
baseUrl: adjustBaseUrl(baseUrl, piModelDef.api),
|
|
81
|
+
reasoning: piModelDef.reasoning,
|
|
82
|
+
...(piModelDef.thinkingLevelMap && { thinkingLevelMap: piModelDef.thinkingLevelMap }),
|
|
83
|
+
input: piModelDef.input,
|
|
84
|
+
cost: {
|
|
85
|
+
input: descriptor.cost.input || piModelDef.cost.input,
|
|
86
|
+
output: descriptor.cost.output || piModelDef.cost.output,
|
|
87
|
+
cacheRead: descriptor.cost.cacheRead || piModelDef.cost.cacheRead,
|
|
88
|
+
cacheWrite: descriptor.cost.cacheWrite || piModelDef.cost.cacheWrite,
|
|
89
|
+
},
|
|
90
|
+
contextWindow: piModelDef.contextWindow,
|
|
91
|
+
maxTokens: piModelDef.maxTokens,
|
|
92
|
+
...(resolvedCompat && { compat: resolvedCompat }),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// No registry match — use descriptor fields directly
|
|
97
|
+
return {
|
|
98
|
+
id: descriptor.id,
|
|
99
|
+
name: descriptor.name,
|
|
100
|
+
api: descriptor.preferredApi as Api,
|
|
101
|
+
provider: "plexus",
|
|
102
|
+
baseUrl: descriptor.baseUrl,
|
|
103
|
+
reasoning: descriptor.reasoning,
|
|
104
|
+
input: descriptor.input,
|
|
105
|
+
cost: descriptor.cost,
|
|
106
|
+
contextWindow: descriptor.contextWindow,
|
|
107
|
+
maxTokens: descriptor.maxTokens,
|
|
108
|
+
};
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
export const mapDescriptorsToPiModels = (descriptors: PlexusModelDescriptor[], baseUrl: string): PiModel[] =>
|
|
112
|
+
descriptors.map((d) => mapDescriptorToPiModel(d, baseUrl));
|
package/src/pi-compat.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { getModel } from "@earendil-works/pi-ai";
|
|
3
|
+
|
|
4
|
+
export { getAgentDir };
|
|
5
|
+
|
|
6
|
+
// biome-ignore lint/suspicious/noExplicitAny: getModel uses branded generic types; dynamic string args require any
|
|
7
|
+
export const lookupModel = getModel as (...args: any[]) => any;
|
package/README.md
DELETED
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
# pi-plexus
|
|
2
|
-
|
|
3
|
-
A [pi](https://github.com/earendil-works/pi-mono) extension that adds [Plexus](https://github.com/mcowger/plexus) as a provider, dynamically discovering models from your Plexus instance.
|
|
4
|
-
|
|
5
|
-
## Requirements
|
|
6
|
-
|
|
7
|
-
- pi `0.74.0` or later
|
|
8
|
-
- A running Plexus instance with a valid API key
|
|
9
|
-
|
|
10
|
-
## Installation
|
|
11
|
-
|
|
12
|
-
### Via npm (recommended)
|
|
13
|
-
|
|
14
|
-
```bash
|
|
15
|
-
pi install npm:@mcowger/pi-plexus
|
|
16
|
-
```
|
|
17
|
-
|
|
18
|
-
### Via git
|
|
19
|
-
|
|
20
|
-
```bash
|
|
21
|
-
pi install git:github.com/mcowger/pi-plexus
|
|
22
|
-
```
|
|
23
|
-
|
|
24
|
-
## Configuration
|
|
25
|
-
|
|
26
|
-
Once installed, run the login command inside pi:
|
|
27
|
-
|
|
28
|
-
```
|
|
29
|
-
/plexus login
|
|
30
|
-
```
|
|
31
|
-
|
|
32
|
-
You will be prompted for:
|
|
33
|
-
1. **Base URL** — the root URL of your Plexus instance, e.g. `https://plexus.example.com` (no `/v1` suffix needed)
|
|
34
|
-
2. **API key** — your Plexus API key
|
|
35
|
-
3. **Default model** (optional) — the model ID to use by default, e.g. `glm-5.1` (use the raw model name, not the `plexus/` prefix)
|
|
36
|
-
|
|
37
|
-
Credentials are stored in `~/.pi/agent/auth.json` (API key, managed by pi) and `~/.pi/agent/extensions/plexus/config.json` (base URL and default model).
|
|
38
|
-
|
|
39
|
-
### Environment variables
|
|
40
|
-
|
|
41
|
-
As an alternative to `/plexus login`, you can set environment variables before starting pi:
|
|
42
|
-
|
|
43
|
-
```bash
|
|
44
|
-
export PLEXUS_BASE_URL=https://plexus.example.com
|
|
45
|
-
export PLEXUS_API_KEY=sk-...
|
|
46
|
-
```
|
|
47
|
-
|
|
48
|
-
## Commands
|
|
49
|
-
|
|
50
|
-
| Command | Description |
|
|
51
|
-
|---|---|
|
|
52
|
-
| `/plexus login` | Configure base URL and API key |
|
|
53
|
-
| `/plexus refresh` | Re-fetch the model list from your Plexus instance and update the local cache |
|
|
54
|
-
|
|
55
|
-
## How it works
|
|
56
|
-
|
|
57
|
-
On startup, the extension loads a cached model list from `~/.pi/agent/extensions/plexus/plexus-models-cache.json` so models are available immediately. On each session start it attempts a live refresh from `/v1/models` to pick up any new or removed models.
|
|
58
|
-
|
|
59
|
-
Models are registered under the `plexus` provider and appear in `/model` alongside all other configured providers.
|
|
60
|
-
|
|
61
|
-
### Provider-specific model fidelity via `pi_provider` / `pi_model`
|
|
62
|
-
|
|
63
|
-
Many models require provider-specific compatibility settings (e.g. DeepSeek needs `system` role instead of `developer`, Qwen uses a different thinking format, etc.). pi already knows these settings for built-in providers, but when models are proxied through Plexus, pi can't auto-detect them because the provider and base URL belong to Plexus, not the original provider.
|
|
64
|
-
|
|
65
|
-
To solve this, configure Plexus to expose `pi_provider` and `pi_model` in its `/v1/models` response. When these fields are set, the extension looks up the full model definition from pi's built-in MODELS registry and uses it for maximum fidelity — picking up the correct `api`, `compat`, `thinkingLevelMap`, `reasoning`, `contextWindow`, `maxTokens`, and `input` modalities, all sourced from pi's curated configuration rather than inferred from Plexus fields.
|
|
66
|
-
|
|
67
|
-
In your Plexus model configuration, enable the **pi Provider** and **pi Model** fields:
|
|
68
|
-
|
|
69
|
-

|
|
70
|
-
|
|
71
|
-
For example, a DeepSeek V4 Flash entry configured with `pi_provider: deepseek` and `pi_model: deepseek-v4-flash` will automatically get the correct compat settings (including `supportsDeveloperRole: false` and `thinkingFormat: deepseek`), ensuring requests are formatted correctly for DeepSeek even though they're routed through Plexus.
|
|
72
|
-
|
|
73
|
-
If `pi_provider` / `pi_model` are not set for a model, the extension falls back to inferring settings from the Plexus API fields (preferred_api, supported_parameters, architecture, etc.) — which works fine for simpler models but won't include provider-specific compat overrides.
|
|
74
|
-
|
|
75
|
-
## Troubleshooting
|
|
76
|
-
|
|
77
|
-
The extension writes a debug log to `~/.pi/agent/extensions/plexus/plexus.log`. If models are missing or requests are failing, check that file first:
|
|
78
|
-
|
|
79
|
-
```bash
|
|
80
|
-
cat ~/.pi/agent/extensions/plexus/plexus.log
|
|
81
|
-
```
|
package/src/plexus-cache.ts
DELETED
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
-
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
3
|
-
import { join } from "node:path";
|
|
4
|
-
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
5
|
-
import type { PlexusApiResponse } from "./plexus-models.js";
|
|
6
|
-
import type { PiModel } from "./plexus-models.js";
|
|
7
|
-
|
|
8
|
-
const getCacheDir = (): string => join(getAgentDir(), "extensions", "plexus");
|
|
9
|
-
|
|
10
|
-
const getModelsCachePath = (): string => join(getCacheDir(), "plexus-models-cache.json");
|
|
11
|
-
|
|
12
|
-
const getResponseCachePath = (): string => join(getCacheDir(), "plexus-models-response.json");
|
|
13
|
-
|
|
14
|
-
interface ModelCache {
|
|
15
|
-
models: PiModel[];
|
|
16
|
-
timestamp: number;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export const readCachedModels = async (): Promise<ModelCache | null> => {
|
|
20
|
-
try {
|
|
21
|
-
const content = await readFile(getModelsCachePath(), "utf8");
|
|
22
|
-
const cache = JSON.parse(content) as ModelCache;
|
|
23
|
-
if (!Array.isArray(cache.models)) return null;
|
|
24
|
-
return cache;
|
|
25
|
-
} catch {
|
|
26
|
-
return null;
|
|
27
|
-
}
|
|
28
|
-
};
|
|
29
|
-
|
|
30
|
-
export const readCachedModelsSync = (): ModelCache | null => {
|
|
31
|
-
try {
|
|
32
|
-
const path = getModelsCachePath();
|
|
33
|
-
if (!existsSync(path)) return null;
|
|
34
|
-
const content = readFileSync(path, "utf8");
|
|
35
|
-
const cache = JSON.parse(content) as ModelCache;
|
|
36
|
-
if (!Array.isArray(cache.models)) return null;
|
|
37
|
-
return cache;
|
|
38
|
-
} catch {
|
|
39
|
-
return null;
|
|
40
|
-
}
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
export const writeCachedModels = async (models: PiModel[]): Promise<void> => {
|
|
44
|
-
const cache: ModelCache = { models, timestamp: Date.now() };
|
|
45
|
-
await mkdir(getCacheDir(), { recursive: true });
|
|
46
|
-
await writeFile(getModelsCachePath(), `${JSON.stringify(cache, null, 2)}\n`, "utf8");
|
|
47
|
-
};
|
|
48
|
-
|
|
49
|
-
export const writeRawResponse = async (data: PlexusApiResponse): Promise<void> => {
|
|
50
|
-
await mkdir(getCacheDir(), { recursive: true });
|
|
51
|
-
await writeFile(getResponseCachePath(), `${JSON.stringify(data, null, 2)}\n`, "utf8");
|
|
52
|
-
};
|
package/src/plexus-config.ts
DELETED
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
import { mkdir, writeFile } from "node:fs/promises";
|
|
2
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
3
|
-
import { join } from "node:path";
|
|
4
|
-
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
5
|
-
|
|
6
|
-
const getConfigDir = (): string => join(getAgentDir(), "extensions", "plexus");
|
|
7
|
-
const getConfigPath = (): string => join(getConfigDir(), "config.json");
|
|
8
|
-
|
|
9
|
-
interface PlexusConfig {
|
|
10
|
-
baseUrl?: string;
|
|
11
|
-
defaultModel?: string;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
const normalizeRoot = (raw: string): string => raw.replace(/\/+$/, "");
|
|
15
|
-
|
|
16
|
-
export const getConfigSync = (): PlexusConfig => {
|
|
17
|
-
try {
|
|
18
|
-
if (existsSync(getConfigPath())) {
|
|
19
|
-
return JSON.parse(readFileSync(getConfigPath(), "utf8")) as PlexusConfig;
|
|
20
|
-
}
|
|
21
|
-
} catch {}
|
|
22
|
-
return {};
|
|
23
|
-
};
|
|
24
|
-
|
|
25
|
-
export const saveBaseUrl = async (baseUrl: string, defaultModel?: string): Promise<void> => {
|
|
26
|
-
await mkdir(getConfigDir(), { recursive: true });
|
|
27
|
-
const existing = getConfigSync();
|
|
28
|
-
const config: PlexusConfig = {
|
|
29
|
-
...existing,
|
|
30
|
-
baseUrl: normalizeRoot(baseUrl),
|
|
31
|
-
...(defaultModel !== undefined && { defaultModel }),
|
|
32
|
-
};
|
|
33
|
-
await writeFile(getConfigPath(), `${JSON.stringify(config, null, 2)}\n`, "utf8");
|
|
34
|
-
};
|
|
35
|
-
|
|
36
|
-
export const getRawBaseUrl = (): string | null => {
|
|
37
|
-
const config = getConfigSync();
|
|
38
|
-
if (config.baseUrl) return config.baseUrl;
|
|
39
|
-
return process.env.PLEXUS_BASE_URL ?? null;
|
|
40
|
-
};
|
|
41
|
-
|
|
42
|
-
export const getModelsUrl = (): string | null => {
|
|
43
|
-
const raw = getRawBaseUrl();
|
|
44
|
-
return raw ? `${normalizeRoot(raw)}/v1/models` : null;
|
|
45
|
-
};
|
|
46
|
-
|
|
47
|
-
export const getBaseUrlSync = (): string | null => {
|
|
48
|
-
const raw = getRawBaseUrl();
|
|
49
|
-
return raw ? `${normalizeRoot(raw)}/v1` : null;
|
|
50
|
-
};
|
|
51
|
-
|
|
52
|
-
// Alias for backward compatibility
|
|
53
|
-
export const getBaseUrl = getBaseUrlSync;
|
|
54
|
-
|
|
55
|
-
export const getDefaultModel = (): string | null => {
|
|
56
|
-
const config = getConfigSync();
|
|
57
|
-
return config.defaultModel ?? null;
|
|
58
|
-
};
|
package/src/plexus-log.ts
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { appendFileSync, mkdirSync } from "node:fs";
|
|
2
|
-
import { join } from "node:path";
|
|
3
|
-
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
4
|
-
|
|
5
|
-
const getLogPath = (): string => join(getAgentDir(), "extensions", "plexus", "plexus.log");
|
|
6
|
-
|
|
7
|
-
const getCacheDir = (): string => join(getAgentDir(), "extensions", "plexus");
|
|
8
|
-
|
|
9
|
-
export const log = (message: string, data?: Record<string, unknown>): void => {
|
|
10
|
-
try {
|
|
11
|
-
mkdirSync(getCacheDir(), { recursive: true });
|
|
12
|
-
const line = `${new Date().toISOString()} ${message}${data ? ` ${JSON.stringify(data)}` : ""}\n`;
|
|
13
|
-
appendFileSync(getLogPath(), line, "utf8");
|
|
14
|
-
} catch {
|
|
15
|
-
// never throw from logging
|
|
16
|
-
}
|
|
17
|
-
};
|
package/src/plexus-models.ts
DELETED
|
@@ -1,318 +0,0 @@
|
|
|
1
|
-
import { getModel } from "@earendil-works/pi-ai";
|
|
2
|
-
import type {
|
|
3
|
-
Api,
|
|
4
|
-
Model,
|
|
5
|
-
OpenAICompletionsCompat,
|
|
6
|
-
OpenAIResponsesCompat,
|
|
7
|
-
AnthropicMessagesCompat,
|
|
8
|
-
} from "@earendil-works/pi-ai";
|
|
9
|
-
|
|
10
|
-
export interface PlexusModelArchitecture {
|
|
11
|
-
modality?: string;
|
|
12
|
-
input_modalities?: string[];
|
|
13
|
-
output_modalities?: string[];
|
|
14
|
-
tokenizer?: string;
|
|
15
|
-
instruct_type?: string | null;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export interface PlexusModelPricing {
|
|
19
|
-
prompt?: string;
|
|
20
|
-
completion?: string;
|
|
21
|
-
input_cache_read?: string;
|
|
22
|
-
input_cache_write?: string;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export interface PlexusTopProvider {
|
|
26
|
-
context_length?: number | null;
|
|
27
|
-
max_completion_tokens?: number | null;
|
|
28
|
-
is_moderated?: boolean;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export interface PlexusApiModel {
|
|
32
|
-
id: string;
|
|
33
|
-
object?: string;
|
|
34
|
-
created?: number;
|
|
35
|
-
owned_by?: string;
|
|
36
|
-
preferred_api?: string | string[];
|
|
37
|
-
name?: string;
|
|
38
|
-
description?: string;
|
|
39
|
-
context_length?: number | null;
|
|
40
|
-
architecture?: PlexusModelArchitecture;
|
|
41
|
-
pricing?: PlexusModelPricing;
|
|
42
|
-
supported_parameters?: string[];
|
|
43
|
-
top_provider?: PlexusTopProvider;
|
|
44
|
-
/** When set, look up the full model definition from pi's MODELS for maximum fidelity. */
|
|
45
|
-
pi_provider?: string;
|
|
46
|
-
pi_model?: string;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export interface PlexusApiResponse {
|
|
50
|
-
object: string;
|
|
51
|
-
data: PlexusApiModel[];
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export type PiModel = Model<Api>;
|
|
55
|
-
|
|
56
|
-
const DEFAULT_CONTEXT_WINDOW = 8192;
|
|
57
|
-
const REASONING_PARAMS = new Set(["reasoning", "include_reasoning", "reasoning_effort"]);
|
|
58
|
-
|
|
59
|
-
const parsePrice = (value: string | undefined): number => {
|
|
60
|
-
if (!value) return 0;
|
|
61
|
-
const parsed = parseFloat(value);
|
|
62
|
-
return Number.isNaN(parsed) ? 0 : parsed;
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
const mapPreferredApi = (preferred_api: string | string[] | undefined): Api => {
|
|
66
|
-
const SUPPORTED_MAP: Record<string, Api> = {
|
|
67
|
-
chat_completions: "openai-completions",
|
|
68
|
-
messages: "anthropic-messages",
|
|
69
|
-
gemini: "google-generative-ai",
|
|
70
|
-
responses: "openai-responses",
|
|
71
|
-
};
|
|
72
|
-
|
|
73
|
-
if (!preferred_api) return "openai-completions";
|
|
74
|
-
|
|
75
|
-
const candidates = Array.isArray(preferred_api) ? preferred_api : [preferred_api];
|
|
76
|
-
|
|
77
|
-
for (const candidate of candidates) {
|
|
78
|
-
const mapped = SUPPORTED_MAP[candidate];
|
|
79
|
-
if (mapped) return mapped;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
return "openai-completions";
|
|
83
|
-
};
|
|
84
|
-
|
|
85
|
-
const mapInputModalities = (architecture: PlexusModelArchitecture | undefined): ("text" | "image")[] => {
|
|
86
|
-
const modalities = architecture?.input_modalities ?? [];
|
|
87
|
-
const result: ("text" | "image")[] = [];
|
|
88
|
-
|
|
89
|
-
if (modalities.includes("text")) result.push("text");
|
|
90
|
-
if (modalities.includes("image")) result.push("image");
|
|
91
|
-
|
|
92
|
-
return result.length > 0 ? result : ["text"];
|
|
93
|
-
};
|
|
94
|
-
|
|
95
|
-
const inferReasoning = (supported_parameters: string[] | undefined): boolean => {
|
|
96
|
-
if (!supported_parameters) return false;
|
|
97
|
-
return supported_parameters.some((p) => REASONING_PARAMS.has(p));
|
|
98
|
-
};
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* Attempt to look up a model definition from pi's built-in MODELS registry
|
|
102
|
-
* using the pi_provider and pi_model hints from the plexus API.
|
|
103
|
-
* Returns null if either hint is missing or the model isn't found.
|
|
104
|
-
*/
|
|
105
|
-
const lookupPiModel = (piProvider?: string, piModel?: string): Model<Api> | null => {
|
|
106
|
-
if (!piProvider || !piModel) return null;
|
|
107
|
-
|
|
108
|
-
// pi_provider/pi_model are dynamic strings from the plexus API,
|
|
109
|
-
// so we cast to bypass the branded type constraints on getModel.
|
|
110
|
-
// biome-ignore lint/suspicious/noExplicitAny: dynamic string args don't satisfy generic constraints
|
|
111
|
-
return getModel(piProvider as any, piModel as any) ?? null;
|
|
112
|
-
};
|
|
113
|
-
|
|
114
|
-
/**
|
|
115
|
-
* Detect OpenAI completions compat settings from the provider and baseUrl of a
|
|
116
|
-
* pi model definition. This mirrors the internal detectCompat() in pi's
|
|
117
|
-
* openai-completions provider so that we can produce a fully-resolved compat
|
|
118
|
-
* object for plexus-proxied models.
|
|
119
|
-
*
|
|
120
|
-
* Without this, providers like deepseek that are proxied through plexus won't
|
|
121
|
-
* get the correct implied compat (e.g. supportsDeveloperRole: false) because
|
|
122
|
-
* pi's runtime auto-detection checks model.provider and model.baseUrl, which
|
|
123
|
-
* are "plexus" and the plexus URL — not the original provider.
|
|
124
|
-
*/
|
|
125
|
-
const detectOpenAICompletionsCompat = (piModel: Model<Api>): OpenAICompletionsCompat => {
|
|
126
|
-
const provider = piModel.provider;
|
|
127
|
-
const baseUrl = piModel.baseUrl;
|
|
128
|
-
|
|
129
|
-
const isZai = provider === "zai" || baseUrl.includes("api.z.ai");
|
|
130
|
-
const isMoonshot = provider === "moonshotai" || provider === "moonshotai-cn" || baseUrl.includes("api.moonshot.");
|
|
131
|
-
const isCloudflareWorkersAI = provider === "cloudflare-workers-ai" || baseUrl.includes("api.cloudflare.com");
|
|
132
|
-
const isCloudflareAiGateway = provider === "cloudflare-ai-gateway" || baseUrl.includes("gateway.ai.cloudflare.com");
|
|
133
|
-
const isNonStandard =
|
|
134
|
-
provider === "cerebras" ||
|
|
135
|
-
baseUrl.includes("cerebras.ai") ||
|
|
136
|
-
provider === "xai" ||
|
|
137
|
-
baseUrl.includes("api.x.ai") ||
|
|
138
|
-
baseUrl.includes("chutes.ai") ||
|
|
139
|
-
baseUrl.includes("deepseek.com") ||
|
|
140
|
-
isZai ||
|
|
141
|
-
isMoonshot ||
|
|
142
|
-
provider === "opencode" ||
|
|
143
|
-
baseUrl.includes("opencode.ai") ||
|
|
144
|
-
isCloudflareWorkersAI ||
|
|
145
|
-
isCloudflareAiGateway;
|
|
146
|
-
const useMaxTokens = baseUrl.includes("chutes.ai") || isMoonshot || isCloudflareAiGateway;
|
|
147
|
-
const isGrok = provider === "xai" || baseUrl.includes("api.x.ai");
|
|
148
|
-
const isDeepSeek = provider === "deepseek" || baseUrl.includes("deepseek.com");
|
|
149
|
-
const cacheControlFormat = provider === "openrouter" && piModel.id.startsWith("anthropic/") ? "anthropic" : undefined;
|
|
150
|
-
|
|
151
|
-
const detected: OpenAICompletionsCompat = {
|
|
152
|
-
supportsStore: !isNonStandard,
|
|
153
|
-
supportsDeveloperRole: !isNonStandard,
|
|
154
|
-
supportsReasoningEffort: !isGrok && !isZai && !isMoonshot && !isCloudflareAiGateway,
|
|
155
|
-
supportsUsageInStreaming: true,
|
|
156
|
-
maxTokensField: useMaxTokens ? "max_tokens" : "max_completion_tokens",
|
|
157
|
-
requiresToolResultName: false,
|
|
158
|
-
requiresAssistantAfterToolResult: false,
|
|
159
|
-
requiresThinkingAsText: false,
|
|
160
|
-
requiresReasoningContentOnAssistantMessages: isDeepSeek,
|
|
161
|
-
thinkingFormat: isDeepSeek
|
|
162
|
-
? "deepseek"
|
|
163
|
-
: isZai
|
|
164
|
-
? "zai"
|
|
165
|
-
: provider === "openrouter" || baseUrl.includes("openrouter.ai")
|
|
166
|
-
? "openrouter"
|
|
167
|
-
: "openai",
|
|
168
|
-
openRouterRouting: {},
|
|
169
|
-
vercelGatewayRouting: {},
|
|
170
|
-
zaiToolStream: false,
|
|
171
|
-
supportsStrictMode: !isMoonshot && !isCloudflareAiGateway,
|
|
172
|
-
cacheControlFormat,
|
|
173
|
-
sendSessionAffinityHeaders: false,
|
|
174
|
-
supportsLongCacheRetention: !(isCloudflareWorkersAI || isCloudflareAiGateway),
|
|
175
|
-
};
|
|
176
|
-
|
|
177
|
-
return detected;
|
|
178
|
-
};
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Resolve a fully-specified compat object for a plexus-proxied model by
|
|
182
|
-
* merging the pi model's stored compat overrides onto the detected defaults
|
|
183
|
-
* from the pi model's original provider/baseUrl.
|
|
184
|
-
*
|
|
185
|
-
* This produces the same result that pi's getCompat() would compute for the
|
|
186
|
-
* original model, ensuring that implied compat fields (like
|
|
187
|
-
* supportsDeveloperRole: false for deepseek) are correct even though the
|
|
188
|
-
* plexus model has provider="plexus" and a plexus baseUrl.
|
|
189
|
-
*/
|
|
190
|
-
const resolveCompat = (
|
|
191
|
-
piModel: Model<Api>,
|
|
192
|
-
): OpenAICompletionsCompat | OpenAIResponsesCompat | AnthropicMessagesCompat | undefined => {
|
|
193
|
-
if (piModel.api === "openai-completions") {
|
|
194
|
-
const detected = detectOpenAICompletionsCompat(piModel);
|
|
195
|
-
const overrides = piModel.compat as OpenAICompletionsCompat | undefined;
|
|
196
|
-
if (!overrides) return detected;
|
|
197
|
-
return {
|
|
198
|
-
supportsStore: overrides.supportsStore ?? detected.supportsStore,
|
|
199
|
-
supportsDeveloperRole: overrides.supportsDeveloperRole ?? detected.supportsDeveloperRole,
|
|
200
|
-
supportsReasoningEffort: overrides.supportsReasoningEffort ?? detected.supportsReasoningEffort,
|
|
201
|
-
supportsUsageInStreaming: overrides.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,
|
|
202
|
-
maxTokensField: overrides.maxTokensField ?? detected.maxTokensField,
|
|
203
|
-
requiresToolResultName: overrides.requiresToolResultName ?? detected.requiresToolResultName,
|
|
204
|
-
requiresAssistantAfterToolResult:
|
|
205
|
-
overrides.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,
|
|
206
|
-
requiresThinkingAsText: overrides.requiresThinkingAsText ?? detected.requiresThinkingAsText,
|
|
207
|
-
requiresReasoningContentOnAssistantMessages:
|
|
208
|
-
overrides.requiresReasoningContentOnAssistantMessages ?? detected.requiresReasoningContentOnAssistantMessages,
|
|
209
|
-
thinkingFormat: overrides.thinkingFormat ?? detected.thinkingFormat,
|
|
210
|
-
openRouterRouting: overrides.openRouterRouting ?? detected.openRouterRouting,
|
|
211
|
-
vercelGatewayRouting: overrides.vercelGatewayRouting ?? detected.vercelGatewayRouting,
|
|
212
|
-
zaiToolStream: overrides.zaiToolStream ?? detected.zaiToolStream,
|
|
213
|
-
supportsStrictMode: overrides.supportsStrictMode ?? detected.supportsStrictMode,
|
|
214
|
-
cacheControlFormat: overrides.cacheControlFormat ?? detected.cacheControlFormat,
|
|
215
|
-
sendSessionAffinityHeaders: overrides.sendSessionAffinityHeaders ?? detected.sendSessionAffinityHeaders,
|
|
216
|
-
supportsLongCacheRetention: overrides.supportsLongCacheRetention ?? detected.supportsLongCacheRetention,
|
|
217
|
-
};
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
// For other APIs, fall back to the stored compat as-is.
|
|
221
|
-
// At runtime, pi's provider will still merge with detected defaults,
|
|
222
|
-
// but the plexus baseUrl won't match any known provider patterns,
|
|
223
|
-
// so defaults are generally safe for anthropic-messages and openai-responses.
|
|
224
|
-
return piModel.compat;
|
|
225
|
-
};
|
|
226
|
-
|
|
227
|
-
const adjustBaseUrl = (baseUrl: string, api: Api): string => {
|
|
228
|
-
if (api === "anthropic-messages") {
|
|
229
|
-
return baseUrl.replace(/\/v1\/?$/, "");
|
|
230
|
-
}
|
|
231
|
-
if (api === "google-generative-ai") {
|
|
232
|
-
return baseUrl.replace(/\/v1\/?$/, "/v1beta");
|
|
233
|
-
}
|
|
234
|
-
return baseUrl;
|
|
235
|
-
};
|
|
236
|
-
|
|
237
|
-
export const convertToPiModel = (apiModel: PlexusApiModel, baseUrl: string): PiModel => {
|
|
238
|
-
const piModelDef = lookupPiModel(apiModel.pi_provider, apiModel.pi_model);
|
|
239
|
-
|
|
240
|
-
// When pi's MODELS has this model, use its curated definition for maximum fidelity,
|
|
241
|
-
// overriding with plexus-specific fields (id, provider, baseUrl, cost from plexus pricing).
|
|
242
|
-
if (piModelDef) {
|
|
243
|
-
const resolvedCompat = resolveCompat(piModelDef);
|
|
244
|
-
return {
|
|
245
|
-
id: apiModel.id,
|
|
246
|
-
name: apiModel.name ?? piModelDef.name ?? apiModel.id,
|
|
247
|
-
api: piModelDef.api,
|
|
248
|
-
provider: "plexus",
|
|
249
|
-
baseUrl: adjustBaseUrl(baseUrl, piModelDef.api),
|
|
250
|
-
reasoning: piModelDef.reasoning,
|
|
251
|
-
...(piModelDef.thinkingLevelMap && { thinkingLevelMap: piModelDef.thinkingLevelMap }),
|
|
252
|
-
input: piModelDef.input,
|
|
253
|
-
cost: {
|
|
254
|
-
input: parsePrice(apiModel.pricing?.prompt) || piModelDef.cost.input,
|
|
255
|
-
output: parsePrice(apiModel.pricing?.completion) || piModelDef.cost.output,
|
|
256
|
-
cacheRead: parsePrice(apiModel.pricing?.input_cache_read) || piModelDef.cost.cacheRead,
|
|
257
|
-
cacheWrite: parsePrice(apiModel.pricing?.input_cache_write) || piModelDef.cost.cacheWrite,
|
|
258
|
-
},
|
|
259
|
-
contextWindow: piModelDef.contextWindow,
|
|
260
|
-
maxTokens: piModelDef.maxTokens,
|
|
261
|
-
...(resolvedCompat && { compat: resolvedCompat }),
|
|
262
|
-
};
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
// No pi MODELS match – fall back to parsing the plexus API fields.
|
|
266
|
-
const contextWindow = apiModel.context_length ?? apiModel.top_provider?.context_length ?? DEFAULT_CONTEXT_WINDOW;
|
|
267
|
-
|
|
268
|
-
const maxTokens = apiModel.top_provider?.max_completion_tokens ?? contextWindow;
|
|
269
|
-
const fallbackApi = mapPreferredApi(apiModel.preferred_api);
|
|
270
|
-
|
|
271
|
-
return {
|
|
272
|
-
id: apiModel.id,
|
|
273
|
-
name: apiModel.name ?? apiModel.id,
|
|
274
|
-
api: fallbackApi,
|
|
275
|
-
provider: "plexus",
|
|
276
|
-
baseUrl: adjustBaseUrl(baseUrl, fallbackApi),
|
|
277
|
-
reasoning: inferReasoning(apiModel.supported_parameters),
|
|
278
|
-
input: mapInputModalities(apiModel.architecture),
|
|
279
|
-
cost: {
|
|
280
|
-
input: parsePrice(apiModel.pricing?.prompt),
|
|
281
|
-
output: parsePrice(apiModel.pricing?.completion),
|
|
282
|
-
cacheRead: parsePrice(apiModel.pricing?.input_cache_read),
|
|
283
|
-
cacheWrite: parsePrice(apiModel.pricing?.input_cache_write),
|
|
284
|
-
},
|
|
285
|
-
contextWindow,
|
|
286
|
-
maxTokens,
|
|
287
|
-
};
|
|
288
|
-
};
|
|
289
|
-
|
|
290
|
-
export const fetchPlexusModels = async (
|
|
291
|
-
apiKey: string,
|
|
292
|
-
modelsUrl: string,
|
|
293
|
-
): Promise<{ models: PlexusApiModel[]; raw: PlexusApiResponse }> => {
|
|
294
|
-
const response = await fetch(modelsUrl, {
|
|
295
|
-
headers: {
|
|
296
|
-
Accept: "application/json",
|
|
297
|
-
Authorization: `Bearer ${apiKey}`,
|
|
298
|
-
},
|
|
299
|
-
});
|
|
300
|
-
|
|
301
|
-
if (!response.ok) {
|
|
302
|
-
throw new Error(`Plexus API error: ${response.status} ${response.statusText}`);
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
const raw = (await response.json()) as PlexusApiResponse;
|
|
306
|
-
return { models: raw.data ?? [], raw };
|
|
307
|
-
};
|
|
308
|
-
|
|
309
|
-
export const convertModels = (apiModels: PlexusApiModel[], baseUrl: string): PiModel[] => {
|
|
310
|
-
const result: PiModel[] = [];
|
|
311
|
-
|
|
312
|
-
for (const apiModel of apiModels) {
|
|
313
|
-
if (!apiModel.id) continue;
|
|
314
|
-
result.push(convertToPiModel(apiModel, baseUrl));
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
return result;
|
|
318
|
-
};
|