@sagmans/dsh-provider-extra 0.4.0 → 0.5.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/README.md +87 -20
- package/dist/catalog-default.js +39 -0
- package/dist/catalog-protocols.js +15 -0
- package/dist/catalog-routes.js +369 -0
- package/dist/catalog-runtime.js +135 -0
- package/dist/catalog.js +65 -0
- package/dist/codex.js +30 -4
- package/dist/extra-models.js +47 -6
- package/dist/index.js +96 -141
- package/dist/login-attempt.js +29 -7
- package/dist/login-choice.js +25 -14
- package/dist/login-command.js +16 -9
- package/dist/login-contract.js +3 -1
- package/dist/login-host.js +196 -0
- package/dist/login-verify.js +10 -5
- package/dist/opencode-go.js +9 -5
- package/docs/catalog-v1.example.json +40 -0
- package/docs/catalog.md +218 -0
- package/package.json +3 -1
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { PiAiAdapter } from '@deepseek-ai/dsh-llm-pi-ai';
|
|
2
|
+
import { LlmError, assertUsableApiKey, resolveImageAttachmentAccess } from '@deepseek-ai/dsh-llm';
|
|
3
|
+
import { codexAuth } from "./codex.js";
|
|
4
|
+
import { catalogDefault } from "./catalog-default.js";
|
|
5
|
+
import { mountLoginCommand } from "./login-host.js";
|
|
6
|
+
const PLUGIN_NAME = 'dsh-provider-extra';
|
|
7
|
+
const OWNER_COLLISION = 'CATALOG_OWNER_COLLISION';
|
|
8
|
+
/** Preflight prevents even an unrelated competing row from expanding managed membership. */
|
|
9
|
+
function assertCatalogOwnership(ctx, ownedRoutes = [], defaultOwner) {
|
|
10
|
+
const currentDefault = ctx.get('agentDefaultModel');
|
|
11
|
+
if ((currentDefault !== undefined && currentDefault !== defaultOwner)
|
|
12
|
+
|| ctx.llm.listProviders().some(provider => !ownedRoutes.includes(provider.id))
|
|
13
|
+
|| ctx.llm.listConfigurableProviders().length > 0) {
|
|
14
|
+
throw new LlmError('dsh-provider-extra: ' + OWNER_COLLISION + ': disable competing provider and agent-default-model rows in this opted-in profile before mounting catalog', OWNER_COLLISION);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** Immutable closures also keep prepared and in-flight calls on their original revision. */
|
|
18
|
+
export function mountCatalog(ctx, snapshot, config) {
|
|
19
|
+
assertCatalogOwnership(ctx);
|
|
20
|
+
let ownershipError;
|
|
21
|
+
const requireOwnership = () => {
|
|
22
|
+
if (ownershipError !== undefined)
|
|
23
|
+
throw ownershipError;
|
|
24
|
+
};
|
|
25
|
+
const auth = codexAuth(() => ctx.get('credentials'));
|
|
26
|
+
const credentialId = (route) => {
|
|
27
|
+
const configured = snapshot.providers.get(route)?.auth;
|
|
28
|
+
return configured !== undefined && 'credentialProvider' in configured ? configured.credentialProvider : route;
|
|
29
|
+
};
|
|
30
|
+
const adapter = new PiAiAdapter({
|
|
31
|
+
profiles: () => { requireOwnership(); return snapshot.profiles; },
|
|
32
|
+
auth: {
|
|
33
|
+
...auth,
|
|
34
|
+
// Route aliases must share the source provider's existing OAuth grant.
|
|
35
|
+
credentials: {
|
|
36
|
+
read: async (route) => {
|
|
37
|
+
requireOwnership();
|
|
38
|
+
try {
|
|
39
|
+
return await auth.credentials.read(credentialId(route));
|
|
40
|
+
}
|
|
41
|
+
finally {
|
|
42
|
+
requireOwnership();
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
modify: async (route, change) => {
|
|
46
|
+
requireOwnership();
|
|
47
|
+
try {
|
|
48
|
+
return await auth.credentials.modify(credentialId(route), current => {
|
|
49
|
+
// A rotated token must persist; the outer guard still blocks model dispatch.
|
|
50
|
+
requireOwnership();
|
|
51
|
+
return change(current);
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
requireOwnership();
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
delete: route => {
|
|
59
|
+
requireOwnership();
|
|
60
|
+
return auth.credentials.delete(credentialId(route));
|
|
61
|
+
},
|
|
62
|
+
list: async () => {
|
|
63
|
+
// Stored grants are part of the same owned membership: a conflicting
|
|
64
|
+
// composition must not report routes it can no longer dispatch to.
|
|
65
|
+
requireOwnership();
|
|
66
|
+
const stored = await auth.credentials.list();
|
|
67
|
+
return [...snapshot.providers.values()].flatMap(provider => {
|
|
68
|
+
if (provider.auth === undefined || !('credentialProvider' in provider.auth))
|
|
69
|
+
return [];
|
|
70
|
+
const record = stored.find(item => item.providerId === credentialId(provider.id));
|
|
71
|
+
return record === undefined ? [] : [{ ...record, providerId: provider.id }];
|
|
72
|
+
});
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
},
|
|
76
|
+
resolveApiKey: async (route) => {
|
|
77
|
+
// Prepared calls retain their snapshot and bypass profiles(); this gate
|
|
78
|
+
// stops a newly conflicting composition before credential-backed dispatch.
|
|
79
|
+
requireOwnership();
|
|
80
|
+
const configured = snapshot.providers.get(route);
|
|
81
|
+
if (configured === undefined)
|
|
82
|
+
throw new LlmError('dsh-provider-extra: unknown catalog route "' + route + '"', 'UNKNOWN_PROVIDER');
|
|
83
|
+
if (configured.auth === undefined || !('apiKeyRef' in configured.auth))
|
|
84
|
+
return undefined;
|
|
85
|
+
const ref = configured.auth.apiKeyRef;
|
|
86
|
+
const credentials = ctx.get('credentials');
|
|
87
|
+
const key = credentials === undefined ? process.env[ref] : (await credentials.resolve(ref))?.value;
|
|
88
|
+
requireOwnership();
|
|
89
|
+
if (key !== undefined && key.length > 0)
|
|
90
|
+
return assertUsableApiKey(key, PLUGIN_NAME, ref);
|
|
91
|
+
throw new LlmError('dsh-provider-extra: no credential for route "' + route + '"; its Config references ' + ref, 'MISSING_CREDENTIAL');
|
|
92
|
+
},
|
|
93
|
+
resolveAttachments: () => ctx.get('attachments'),
|
|
94
|
+
resolveImageAccess: (attachments, ref) => resolveImageAttachmentAccess(attachments, hostPath => ctx.get('fs')?.processPathFromHostPath(hostPath), ref),
|
|
95
|
+
onReplayDegrade: ({ provider, model, reason }) => {
|
|
96
|
+
ctx.logger.warn('dsh-provider-extra: unusable replay state for "' + provider + '/' + model + '" (' + reason + ')');
|
|
97
|
+
},
|
|
98
|
+
});
|
|
99
|
+
const routes = [...snapshot.profiles.keys()];
|
|
100
|
+
// The runtime rejects an empty registration; an explicitly empty catalog
|
|
101
|
+
// instead owns only the default contract, which reports NO_DEFAULT_MODEL.
|
|
102
|
+
if (routes.length > 0)
|
|
103
|
+
ctx.llm.registerAdapter(routes, adapter);
|
|
104
|
+
const defaults = catalogDefault(ctx, snapshot, requireOwnership);
|
|
105
|
+
ctx.provide('agentDefaultModel', defaults);
|
|
106
|
+
// Notifications follow registry commit: diagnose, never veto or mutate the
|
|
107
|
+
// other owner. Disposing this listener leaves retained valid calls intact.
|
|
108
|
+
const refreshOwnership = () => {
|
|
109
|
+
try {
|
|
110
|
+
assertCatalogOwnership(ctx, routes, defaults);
|
|
111
|
+
ownershipError = undefined;
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
const previous = ownershipError;
|
|
115
|
+
ownershipError = error;
|
|
116
|
+
if (previous === undefined)
|
|
117
|
+
ctx.logger.error(error);
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
ctx.on('llm/adapters-updated', refreshOwnership);
|
|
121
|
+
refreshOwnership();
|
|
122
|
+
// A public update veto runs before disposal, so a competing late-mounted
|
|
123
|
+
// adapter cannot turn a refused reload into loss of the last valid catalog.
|
|
124
|
+
ctx.on('internal/update', (next, _noSave, proceed) => {
|
|
125
|
+
if (next.catalog !== undefined)
|
|
126
|
+
assertCatalogOwnership(ctx, routes, defaults);
|
|
127
|
+
return proceed();
|
|
128
|
+
});
|
|
129
|
+
mountLoginCommand(ctx, config, { catalog: snapshot, profiles: () => snapshot.profiles, requireOwnership });
|
|
130
|
+
ctx.inject(['settings'], (child) => {
|
|
131
|
+
const settings = child.get('settings');
|
|
132
|
+
if (typeof settings.configure === 'function')
|
|
133
|
+
child.effect(() => settings.configure({ auto: false }, ctx.fiber));
|
|
134
|
+
});
|
|
135
|
+
}
|
package/dist/catalog.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { getSupportedThinkingLevels } from '@earendil-works/pi-ai';
|
|
2
|
+
import { buildCatalogProfile, catalogError, catalogMap, catalogRecord, catalogString, freezeCatalogValue } from "./catalog-routes.js";
|
|
3
|
+
const CONFIG_VERSION = 1;
|
|
4
|
+
const CONFIG_FIELDS = ['version', 'providers', 'default'];
|
|
5
|
+
const SELECTION_FIELDS = ['provider', 'model', 'reasoningEffort'];
|
|
6
|
+
/** Absence keeps legacy ownership separate from a managed empty catalog. */
|
|
7
|
+
export function compileCatalog(config) {
|
|
8
|
+
if (config === undefined)
|
|
9
|
+
return undefined;
|
|
10
|
+
const raw = catalogRecord(config, CONFIG_FIELDS, 'config');
|
|
11
|
+
if (raw.version !== CONFIG_VERSION)
|
|
12
|
+
catalogError('version', 'expected version 1');
|
|
13
|
+
if (!Array.isArray(raw.providers))
|
|
14
|
+
catalogError('providers', 'expected an explicit array');
|
|
15
|
+
const profiles = new Map();
|
|
16
|
+
for (const declaration of raw.providers) {
|
|
17
|
+
const profile = buildCatalogProfile(declaration);
|
|
18
|
+
if (profiles.has(profile.provider))
|
|
19
|
+
catalogError('providers', 'duplicate provider ' + profile.provider);
|
|
20
|
+
profiles.set(profile.provider, profile);
|
|
21
|
+
}
|
|
22
|
+
const normalized = structuredClone(raw);
|
|
23
|
+
const providers = catalogMap(normalized.providers.map(provider => [provider.id, provider]));
|
|
24
|
+
const aliases = new Map();
|
|
25
|
+
let count = 0;
|
|
26
|
+
for (const provider of normalized.providers) {
|
|
27
|
+
const routeAliases = new Map();
|
|
28
|
+
// Served models, not declarations: a filtered route owns ids it never spells out.
|
|
29
|
+
for (const model of profiles.get(provider.id).piProvider.getModels()) {
|
|
30
|
+
routeAliases.set(model.id, model.id);
|
|
31
|
+
count++;
|
|
32
|
+
}
|
|
33
|
+
for (const model of provider.models ?? []) {
|
|
34
|
+
for (const alias of model.aliases ?? [])
|
|
35
|
+
routeAliases.set(alias, model.id);
|
|
36
|
+
}
|
|
37
|
+
aliases.set(provider.id, routeAliases);
|
|
38
|
+
}
|
|
39
|
+
const resolveSelection = (input) => {
|
|
40
|
+
const candidate = catalogRecord(input, SELECTION_FIELDS, 'selection');
|
|
41
|
+
catalogString(candidate.provider, 'selection.provider');
|
|
42
|
+
catalogString(candidate.model, 'selection.model');
|
|
43
|
+
const modelId = aliases.get(candidate.provider)?.get(candidate.model);
|
|
44
|
+
if (modelId === undefined)
|
|
45
|
+
catalogError('selection', 'provider/model is outside the managed selection');
|
|
46
|
+
const model = profiles.get(candidate.provider).piProvider.getModels().find(model => model.id === modelId);
|
|
47
|
+
if ('reasoningEffort' in candidate && !getSupportedThinkingLevels(model).includes(candidate.reasoningEffort)) {
|
|
48
|
+
catalogError('selection.reasoningEffort', 'effort is not supported by the selected model');
|
|
49
|
+
}
|
|
50
|
+
return freezeCatalogValue({
|
|
51
|
+
provider: candidate.provider, model: modelId,
|
|
52
|
+
...('reasoningEffort' in candidate ? { reasoningEffort: candidate.reasoningEffort } : {}),
|
|
53
|
+
});
|
|
54
|
+
};
|
|
55
|
+
if (count === 0) {
|
|
56
|
+
if (normalized.default !== null)
|
|
57
|
+
catalogError('default', 'empty catalog requires null');
|
|
58
|
+
}
|
|
59
|
+
else
|
|
60
|
+
normalized.default = resolveSelection(normalized.default);
|
|
61
|
+
return freezeCatalogValue({
|
|
62
|
+
config: normalized, profiles: catalogMap(profiles), providers,
|
|
63
|
+
selection: normalized.default, resolveSelection,
|
|
64
|
+
});
|
|
65
|
+
}
|
package/dist/codex.js
CHANGED
|
@@ -14,7 +14,7 @@ import { defaultProviderAuthContext } from '@earendil-works/pi-ai';
|
|
|
14
14
|
import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
|
|
15
15
|
import { credentialKey, credentialKeyId, credentialKeyScope, isCredentialKeySegment, } from '@deepseek-ai/dsh-credentials';
|
|
16
16
|
import { LlmError, resolveRetryPolicy } from '@deepseek-ai/dsh-llm';
|
|
17
|
-
import { resolveExtraModels } from "./extra-models.js";
|
|
17
|
+
import { resolveExtraModels, selectWhitelistedModels } from "./extra-models.js";
|
|
18
18
|
/** pi-ai catalog id of the ChatGPT-subscription provider this route serves. */
|
|
19
19
|
export const CODEX_CATALOG_ID = 'openai-codex';
|
|
20
20
|
/**
|
|
@@ -25,6 +25,14 @@ export const CODEX_CATALOG_ID = 'openai-codex';
|
|
|
25
25
|
export const DEFAULT_CODEX_ROUTE_ID = CODEX_CATALOG_ID;
|
|
26
26
|
/** Display name for selectors, matching pi-ai's subscription label. */
|
|
27
27
|
export const DEFAULT_CODEX_DISPLAY_NAME = 'OpenAI Codex';
|
|
28
|
+
/**
|
|
29
|
+
* Transports pi-ai's Codex API accepts, as that API declares them. Named here
|
|
30
|
+
* because a profile pins one: the websocket path keeps a connection-scoped
|
|
31
|
+
* continuation cache, which some networks and proxies never let complete.
|
|
32
|
+
* Mirrors @earendil-works/pi-ai/dist/types.d.ts:41 (Transport); review this
|
|
33
|
+
* schema alongside dependency upgrades so added transports are not silently excluded.
|
|
34
|
+
*/
|
|
35
|
+
export const CODEX_TRANSPORTS = ['sse', 'websocket', 'websocket-cached', 'auto'];
|
|
28
36
|
/**
|
|
29
37
|
* Record scope for the OAuth grant. Identical to dsh-llm-pi-ai's own scope,
|
|
30
38
|
* which is what makes a grant written by the login script readable by core's
|
|
@@ -133,6 +141,20 @@ export class HarnessCredentialStore {
|
|
|
133
141
|
await this.credentials()?.deleteRecord(recordKeyFor(providerId));
|
|
134
142
|
}
|
|
135
143
|
}
|
|
144
|
+
/**
|
|
145
|
+
* Stamp the pinned transport onto one request's stream options. pi-ai selects
|
|
146
|
+
* its Codex transport per request, so this is the only boundary where a profile
|
|
147
|
+
* can choose one; a route that pins none hands pi-ai's options through exactly
|
|
148
|
+
* as it received them.
|
|
149
|
+
* @param options - the per-request stream options pi-ai is about to dispatch.
|
|
150
|
+
* @param config - the route configuration.
|
|
151
|
+
* @returns the options with the transport pinned, or unchanged when none is.
|
|
152
|
+
*/
|
|
153
|
+
export function withTransport(options, config) {
|
|
154
|
+
if (config.transport === undefined || options === undefined)
|
|
155
|
+
return options;
|
|
156
|
+
return { ...options, transport: config.transport };
|
|
157
|
+
}
|
|
136
158
|
/**
|
|
137
159
|
* The installed pi-ai catalog's Codex provider, whose API implementation,
|
|
138
160
|
* OAuth auth, and model list this route reuses rather than reconstructing.
|
|
@@ -166,8 +188,8 @@ function routeProvider(config, catalog, models) {
|
|
|
166
188
|
name: config.displayName,
|
|
167
189
|
auth: catalog.auth,
|
|
168
190
|
getModels: () => routed,
|
|
169
|
-
stream: (model, context, options) => catalog.stream(model, context, options),
|
|
170
|
-
streamSimple: (model, context, options) => catalog.streamSimple(model, context, options),
|
|
191
|
+
stream: (model, context, options) => catalog.stream(model, context, withTransport(options, config)),
|
|
192
|
+
streamSimple: (model, context, options) => catalog.streamSimple(model, context, withTransport(options, config)),
|
|
171
193
|
};
|
|
172
194
|
}
|
|
173
195
|
// The resolved profile defaults below mirror dsh-llm-pi-ai's config
|
|
@@ -193,6 +215,10 @@ export function buildCodexProfile(config) {
|
|
|
193
215
|
// would be dispatched as if the subscription served it, so a declaration
|
|
194
216
|
// that names none is reported instead of cloned.
|
|
195
217
|
const extras = resolveExtraModels(catalog.getModels(), config.extraModels ?? []);
|
|
218
|
+
// Selection runs last so a whitelist may name a declared extra exactly as it
|
|
219
|
+
// names a catalog model, and so a typo in either is refused here rather than
|
|
220
|
+
// served as a route quietly missing a model.
|
|
221
|
+
const models = selectWhitelistedModels(config.provider, [...catalog.getModels(), ...extras.models], config.models);
|
|
196
222
|
return {
|
|
197
223
|
provider: config.provider,
|
|
198
224
|
displayName: config.displayName,
|
|
@@ -203,7 +229,7 @@ export function buildCodexProfile(config) {
|
|
|
203
229
|
retryPolicy: resolveRetryPolicy(undefined, 'dsh-provider-extra: openai-codex'),
|
|
204
230
|
modelErrors: extras.modelErrors,
|
|
205
231
|
configuredMaxTokens: new Map(),
|
|
206
|
-
piProvider: routeProvider(config, catalog,
|
|
232
|
+
piProvider: routeProvider(config, catalog, models),
|
|
207
233
|
};
|
|
208
234
|
}
|
|
209
235
|
/**
|
package/dist/extra-models.js
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Declared models, shared by every route this plugin owns.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
4
|
+
* Two declarations share this module. An extra adds an id the installed
|
|
5
|
+
* catalog predates, cloning a template sibling's wire behavior instead of
|
|
6
|
+
* restating it; a declaration that cannot resolve lands in the route's model
|
|
7
|
+
* diagnostics beside its serviceable models, because one mistyped template
|
|
8
|
+
* must not silence a whole route. A whitelist instead selects which of the
|
|
9
|
+
* resolved models a route serves, and refuses the whole route when it names an
|
|
10
|
+
* id nothing provides — a configuration typo there is a broken deployment, not
|
|
11
|
+
* a diagnosable one-model problem.
|
|
9
12
|
*
|
|
10
13
|
* @module dsh-provider-extra/extra-models
|
|
11
14
|
*/
|
|
15
|
+
import { LlmError } from '@deepseek-ai/dsh-llm';
|
|
12
16
|
/**
|
|
13
17
|
* Resolve declared extras against the installed catalog. Later specs win over
|
|
14
18
|
* earlier ones by id, so a settings entry reshapes a shipped default under the
|
|
@@ -50,3 +54,40 @@ export function resolveExtraModels(catalog, specs, fallbackTemplate) {
|
|
|
50
54
|
}
|
|
51
55
|
return { models, modelErrors };
|
|
52
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* Narrow one route's resolved models to a declared whitelist and put them in
|
|
59
|
+
* the declared order. Absent means the route serves everything it resolved;
|
|
60
|
+
* present means exactly those ids, so the picker and the gateway agree.
|
|
61
|
+
* Resolution order — the installed catalog, then the route's shipped extras,
|
|
62
|
+
* then the declared ones — stays the authority on which id exists, and a
|
|
63
|
+
* whitelist may therefore name a catalog id, a shipped extra, or a declared
|
|
64
|
+
* extra.
|
|
65
|
+
* @param route - route id the refusal names.
|
|
66
|
+
* @param models - resolved catalog and extra models, in resolution order.
|
|
67
|
+
* @param whitelist - exact ids to serve, or undefined to serve every model.
|
|
68
|
+
* @returns the selected models in declared order.
|
|
69
|
+
* @throws {LlmError} when the whitelist names an id nothing resolves; failing
|
|
70
|
+
* the route loud is the only alternative that cannot silently serve less than
|
|
71
|
+
* the deployment asked for.
|
|
72
|
+
*/
|
|
73
|
+
export function selectWhitelistedModels(route, models, whitelist) {
|
|
74
|
+
if (whitelist === undefined)
|
|
75
|
+
return [...models];
|
|
76
|
+
const byId = new Map(models.map(model => [model.id, model]));
|
|
77
|
+
const selected = [];
|
|
78
|
+
const seen = new Set();
|
|
79
|
+
for (const id of whitelist) {
|
|
80
|
+
// A repeated id is one model, kept at its first position: advertising the
|
|
81
|
+
// same id twice would offer the picker two entries no request distinguishes.
|
|
82
|
+
if (seen.has(id))
|
|
83
|
+
continue;
|
|
84
|
+
seen.add(id);
|
|
85
|
+
const model = byId.get(id);
|
|
86
|
+
if (model === undefined) {
|
|
87
|
+
throw new LlmError('dsh-provider-extra: route "' + route + '" declares model "' + id + '" in its model selection,'
|
|
88
|
+
+ ' but neither the installed pi-ai catalog nor an extra model declaration provides it', 'UNKNOWN_MODEL');
|
|
89
|
+
}
|
|
90
|
+
selected.push(model);
|
|
91
|
+
}
|
|
92
|
+
return selected;
|
|
93
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* dsh-provider-extra: extra LLM provider routes for DeepSeek Harness.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* Without a catalog, mounts two additive routes. An opted-in catalog owns
|
|
5
|
+
* the profile's complete model selection and default instead.
|
|
6
|
+
* OpenCode Go stamps the x-opencode-session header
|
|
5
7
|
* from the live dsh session id, which the gateway requires for routing and
|
|
6
8
|
* prompt-cache affinity and which the shipped adapters do not send. OpenAI
|
|
7
9
|
* Codex serves a ChatGPT subscription through pi-ai's OAuth: the grant lives
|
|
@@ -29,30 +31,19 @@
|
|
|
29
31
|
import Schema from '@deepseek-ai/schemastery';
|
|
30
32
|
import { PiAiAdapter } from '@deepseek-ai/dsh-llm-pi-ai';
|
|
31
33
|
import { LlmError, assertUsableApiKey, resolveImageAttachmentAccess } from '@deepseek-ai/dsh-llm';
|
|
32
|
-
import { createModels } from '@earendil-works/pi-ai';
|
|
33
|
-
import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
|
|
34
34
|
import { DEFAULT_EXTRA_MODEL_TEMPLATE, DEFAULT_OPENCODE_API_KEY_ENV, OPENCODE_GO_PROVIDER_ID, buildOpenCodeGoProfile, } from "./opencode-go.js";
|
|
35
|
-
import { DEFAULT_CODEX_DISPLAY_NAME, DEFAULT_CODEX_ROUTE_ID, buildCodexProfile, codexApiKey, codexAuth,
|
|
36
|
-
import {
|
|
37
|
-
import {
|
|
38
|
-
import {
|
|
35
|
+
import { DEFAULT_CODEX_DISPLAY_NAME, DEFAULT_CODEX_ROUTE_ID, buildCodexProfile, codexApiKey, codexAuth, } from "./codex.js";
|
|
36
|
+
import { CODEX_TRANSPORTS } from "./codex.js";
|
|
37
|
+
import { DEFAULT_LOGIN_COMMAND_NAME } from "./login-command.js";
|
|
38
|
+
import { mountLoginCommand } from "./login-host.js";
|
|
39
|
+
import { compileCatalog } from "./catalog.js";
|
|
40
|
+
import { mountCatalog } from "./catalog-runtime.js";
|
|
41
|
+
export { compileCatalog } from "./catalog.js";
|
|
42
|
+
export { buildCatalogProfile } from "./catalog-routes.js";
|
|
39
43
|
/** Settings namespace configuration surfaces address this plugin's section by. */
|
|
40
44
|
const SETTINGS_NS = 'dsh-provider-extra';
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
routeId: Schema.string().default(OPENCODE_GO_PROVIDER_ID),
|
|
44
|
-
displayName: Schema.string().default('OpenCode Go'),
|
|
45
|
-
baseURL: Schema.string(),
|
|
46
|
-
fallbackSessionId: Schema.string(),
|
|
47
|
-
headers: Schema.dict(Schema.string()),
|
|
48
|
-
codexEnabled: Schema.boolean().default(true),
|
|
49
|
-
codexRouteId: Schema.string().default(DEFAULT_CODEX_ROUTE_ID),
|
|
50
|
-
codexDisplayName: Schema.string().default(DEFAULT_CODEX_DISPLAY_NAME),
|
|
51
|
-
loginCommandEnabled: Schema.boolean().default(true),
|
|
52
|
-
loginCommandName: Schema.string().default(DEFAULT_LOGIN_COMMAND_NAME),
|
|
53
|
-
});
|
|
54
|
-
export const name = 'dsh-provider-extra';
|
|
55
|
-
export const inject = ['llm'];
|
|
45
|
+
// Declared extra models: the composition entry and the settings section share
|
|
46
|
+
// these two shapes, so one document's declaration is valid in the other.
|
|
56
47
|
const goExtraModelSchema = Schema.object({
|
|
57
48
|
id: Schema.string().required(),
|
|
58
49
|
name: Schema.string(),
|
|
@@ -66,48 +57,58 @@ const codexExtraModelSchema = Schema.object({
|
|
|
66
57
|
name: Schema.string(),
|
|
67
58
|
template: Schema.string(),
|
|
68
59
|
});
|
|
60
|
+
// The assertion carries the one thing schemastery cannot state: every array in
|
|
61
|
+
// this entry is read-only to the plugin, which only ever copies it, while an
|
|
62
|
+
// array member schema is typed as the mutable array it validates.
|
|
63
|
+
export const Config = Schema.transform(Schema.object({
|
|
64
|
+
// Keep raw catalog presence: schemastery otherwise materializes absent arrays.
|
|
65
|
+
catalog: Schema.any(),
|
|
66
|
+
apiKeyEnv: Schema.string().role('credential-ref').default(DEFAULT_OPENCODE_API_KEY_ENV),
|
|
67
|
+
routeId: Schema.string().default(OPENCODE_GO_PROVIDER_ID),
|
|
68
|
+
displayName: Schema.string().default('OpenCode Go'),
|
|
69
|
+
baseURL: Schema.string(),
|
|
70
|
+
fallbackSessionId: Schema.string(),
|
|
71
|
+
headers: Schema.dict(Schema.string()),
|
|
72
|
+
extraModels: Schema.array(goExtraModelSchema),
|
|
73
|
+
models: Schema.array(Schema.string()),
|
|
74
|
+
codexEnabled: Schema.boolean().default(true),
|
|
75
|
+
codexRouteId: Schema.string().default(DEFAULT_CODEX_ROUTE_ID),
|
|
76
|
+
codexDisplayName: Schema.string().default(DEFAULT_CODEX_DISPLAY_NAME),
|
|
77
|
+
codexExtraModels: Schema.array(codexExtraModelSchema),
|
|
78
|
+
codexModels: Schema.array(Schema.string()),
|
|
79
|
+
codexTransport: Schema.union(CODEX_TRANSPORTS),
|
|
80
|
+
loginCommandEnabled: Schema.boolean().default(true),
|
|
81
|
+
loginCommandName: Schema.string().default(DEFAULT_LOGIN_COMMAND_NAME),
|
|
82
|
+
}), (value) => {
|
|
83
|
+
// Object-level validation also sees explicit null, which field transforms skip.
|
|
84
|
+
// Loader validates before disposal, retaining the previous snapshot on failure.
|
|
85
|
+
compileCatalog(value.catalog);
|
|
86
|
+
return value;
|
|
87
|
+
}, true);
|
|
88
|
+
/**
|
|
89
|
+
* One configured model selection, or nothing when the entry declared none.
|
|
90
|
+
* schemastery materializes an undeclared array member as an empty array, so an
|
|
91
|
+
* empty declaration is the absence of a selection: the route serves everything
|
|
92
|
+
* its catalog and extras resolved, exactly as a profile that never named the
|
|
93
|
+
* field does.
|
|
94
|
+
*/
|
|
95
|
+
function selection(declared) {
|
|
96
|
+
return declared === undefined || declared.length === 0 ? undefined : declared;
|
|
97
|
+
}
|
|
98
|
+
export const name = 'dsh-provider-extra';
|
|
99
|
+
export const inject = ['llm'];
|
|
69
100
|
const SectionSchema = Schema.object({
|
|
70
101
|
extraModels: Schema.array(goExtraModelSchema).default([]),
|
|
71
102
|
codexExtraModels: Schema.array(codexExtraModelSchema).default([]),
|
|
72
103
|
});
|
|
73
|
-
/**
|
|
74
|
-
* Every catalog provider that ships an interactive login, in catalog order.
|
|
75
|
-
* The catalog is the authority on how a provider signs in — which methods it
|
|
76
|
-
* offers, and what each is called — so the picker never re-decides that here.
|
|
77
|
-
*/
|
|
78
|
-
function loginChoices() {
|
|
79
|
-
const choices = [];
|
|
80
|
-
for (const provider of builtinProviders()) {
|
|
81
|
-
const oauth = provider.auth?.oauth;
|
|
82
|
-
if (oauth?.login !== undefined) {
|
|
83
|
-
choices.push({
|
|
84
|
-
providerId: provider.id,
|
|
85
|
-
providerName: provider.name,
|
|
86
|
-
authType: 'oauth',
|
|
87
|
-
methodLabel: oauth.loginLabel ?? oauth.name,
|
|
88
|
-
});
|
|
89
|
-
}
|
|
90
|
-
const apiKey = provider.auth?.apiKey;
|
|
91
|
-
if (apiKey?.login !== undefined) {
|
|
92
|
-
choices.push({
|
|
93
|
-
providerId: provider.id,
|
|
94
|
-
providerName: provider.name,
|
|
95
|
-
authType: 'api_key',
|
|
96
|
-
methodLabel: apiKey.name,
|
|
97
|
-
});
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
return choices;
|
|
101
|
-
}
|
|
102
|
-
/** The catalog provider behind one sign-in choice. */
|
|
103
|
-
function catalogLoginProvider(providerId) {
|
|
104
|
-
const found = builtinProviders().find(provider => provider.id === providerId);
|
|
105
|
-
if (found === undefined) {
|
|
106
|
-
throw new Error('dsh-provider-extra: the installed pi-ai catalog no longer ships provider "' + providerId + '"');
|
|
107
|
-
}
|
|
108
|
-
return found;
|
|
109
|
-
}
|
|
110
104
|
export function apply(ctx, config) {
|
|
105
|
+
const snapshot = compileCatalog(config.catalog);
|
|
106
|
+
if (snapshot !== undefined) {
|
|
107
|
+
mountCatalog(ctx, snapshot, config);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const models = selection(config.models);
|
|
111
|
+
const codexModels = selection(config.codexModels);
|
|
111
112
|
const route = {
|
|
112
113
|
provider: config.routeId,
|
|
113
114
|
displayName: config.displayName,
|
|
@@ -115,11 +116,31 @@ export function apply(ctx, config) {
|
|
|
115
116
|
...config.baseURL === undefined ? {} : { baseURL: config.baseURL },
|
|
116
117
|
...config.fallbackSessionId === undefined ? {} : { fallbackSessionId: config.fallbackSessionId },
|
|
117
118
|
...config.headers === undefined ? {} : { headers: { ...config.headers } },
|
|
119
|
+
...models === undefined ? {} : { models },
|
|
118
120
|
};
|
|
119
121
|
const codex = {
|
|
120
122
|
provider: config.codexRouteId,
|
|
121
123
|
displayName: config.codexDisplayName,
|
|
124
|
+
...codexModels === undefined ? {} : { models: codexModels },
|
|
125
|
+
...config.codexTransport === undefined ? {} : { transport: config.codexTransport },
|
|
126
|
+
};
|
|
127
|
+
// The entry's own declarations are the base layer the settings section sits
|
|
128
|
+
// over, and the value the routes serve on a harness with no settings document
|
|
129
|
+
// at all — which is why they seed the thunk below instead of only the base.
|
|
130
|
+
const entry = {
|
|
131
|
+
extraModels: [...config.extraModels ?? []],
|
|
132
|
+
codexExtraModels: [...config.codexExtraModels ?? []],
|
|
122
133
|
};
|
|
134
|
+
// A declared selection is configuration, not a request fact, so it is proven
|
|
135
|
+
// once here. Registration resolves a profile for its route metadata and
|
|
136
|
+
// reports a failure as a refused route, which would bury the one message that
|
|
137
|
+
// names the misconfigured id; resolving per request would bury it the same
|
|
138
|
+
// way. The extras a selection resolves against at this point are the entry's
|
|
139
|
+
// own, because a settings document may not have arrived yet.
|
|
140
|
+
if (models !== undefined)
|
|
141
|
+
buildOpenCodeGoProfile({ ...route, extraModels: entry.extraModels });
|
|
142
|
+
if (codexModels !== undefined)
|
|
143
|
+
buildCodexProfile({ ...codex, extraModels: entry.codexExtraModels });
|
|
123
144
|
// The catalog check stays boot-time even though settings can now extend the
|
|
124
145
|
// profile per request: a catalog drift (pi-ai no longer shipping Codex) must
|
|
125
146
|
// stand this route down once, loudly, here, instead of failing every request
|
|
@@ -127,7 +148,9 @@ export function apply(ctx, config) {
|
|
|
127
148
|
let codexServable = false;
|
|
128
149
|
if (config.codexEnabled) {
|
|
129
150
|
try {
|
|
130
|
-
|
|
151
|
+
// Catalog drift alone: the selection was already proven above, so it
|
|
152
|
+
// cannot be what this check reports.
|
|
153
|
+
buildCodexProfile({ provider: codex.provider, displayName: codex.displayName });
|
|
131
154
|
codexServable = true;
|
|
132
155
|
}
|
|
133
156
|
catch (error) {
|
|
@@ -138,14 +161,19 @@ export function apply(ctx, config) {
|
|
|
138
161
|
// Route wiring is boot-time, but the model list is per-request: the section
|
|
139
162
|
// thunk below tracks the settings overlay, so a committed extras change
|
|
140
163
|
// reaches the next operation with no rebuild and no restart.
|
|
141
|
-
let currentSection = () =>
|
|
164
|
+
let currentSection = () => entry;
|
|
142
165
|
const profiles = () => {
|
|
143
166
|
const section = currentSection();
|
|
167
|
+
// Selections stay bound to the entry extras that passed mount-time validation.
|
|
144
168
|
const entries = [
|
|
145
|
-
[route.provider, buildOpenCodeGoProfile({
|
|
169
|
+
[route.provider, buildOpenCodeGoProfile({
|
|
170
|
+
...route, extraModels: models !== undefined ? entry.extraModels : section.extraModels,
|
|
171
|
+
})],
|
|
146
172
|
];
|
|
147
173
|
if (codexServable) {
|
|
148
|
-
entries.push([codex.provider, buildCodexProfile({
|
|
174
|
+
entries.push([codex.provider, buildCodexProfile({
|
|
175
|
+
...codex, extraModels: codexModels !== undefined ? entry.codexExtraModels : section.codexExtraModels,
|
|
176
|
+
})]);
|
|
149
177
|
}
|
|
150
178
|
return new Map(entries);
|
|
151
179
|
};
|
|
@@ -227,7 +255,10 @@ export function apply(ctx, config) {
|
|
|
227
255
|
ctx.logger.warn(error);
|
|
228
256
|
}
|
|
229
257
|
ctx.inject(['settings'], (settingsCtx) => {
|
|
230
|
-
|
|
258
|
+
// The section overrides the entry where a settings document exists and
|
|
259
|
+
// stands in for it where none does; the settings service falls back to this
|
|
260
|
+
// same value when it detaches.
|
|
261
|
+
settingsCtx.settings.installSection(ctx, SETTINGS_NS, SectionSchema, entry, {
|
|
231
262
|
setSource: (source) => { currentSection = source; },
|
|
232
263
|
// No registration facts derive from the section: the route set is fixed
|
|
233
264
|
// at composition and the adapter rebuilds its snapshot on every
|
|
@@ -235,81 +266,5 @@ export function apply(ctx, config) {
|
|
|
235
266
|
onChange: () => { },
|
|
236
267
|
});
|
|
237
268
|
});
|
|
238
|
-
|
|
239
|
-
// it runs in this process, so the credential lands in the store the routes
|
|
240
|
-
// already read and no bin path or peer tree is involved. It signs into any
|
|
241
|
-
// provider the installed catalog ships a login for, not only the two routes
|
|
242
|
-
// this plugin mounts, because a human asking to sign in means the provider
|
|
243
|
-
// they name and nothing narrower. Profiles without a command registry
|
|
244
|
-
// (headless compositions) keep the package bin.
|
|
245
|
-
if (config.loginCommandEnabled) {
|
|
246
|
-
ctx.inject(['commands'], (commandCtx) => {
|
|
247
|
-
const host = {
|
|
248
|
-
choices: loginChoices,
|
|
249
|
-
login: async (choice, interaction) => {
|
|
250
|
-
const credentials = () => ctx.get('credentials');
|
|
251
|
-
const auth = codexAuth(credentials);
|
|
252
|
-
const models = createModels(auth);
|
|
253
|
-
// pi-ai's collection starts empty: the catalog provider carrying the
|
|
254
|
-
// login implementation has to be handed to it before the flow runs.
|
|
255
|
-
models.setProvider(catalogLoginProvider(choice.providerId));
|
|
256
|
-
if (choice.authType !== 'api_key') {
|
|
257
|
-
await models.login(choice.providerId, choice.authType, interaction);
|
|
258
|
-
return await declareProviderRoute(ctx.get('settings'), choice.providerId);
|
|
259
|
-
}
|
|
260
|
-
// A grant the provider minted proves itself, but a key proves nothing
|
|
261
|
-
// until a request carries it, so the key is spent from a store that
|
|
262
|
-
// forgets and the profile hears of it only once it has been accepted.
|
|
263
|
-
const pending = createModels({ credentials: new PendingCredentialStore(), authContext: auth.authContext });
|
|
264
|
-
pending.setProvider(catalogLoginProvider(choice.providerId));
|
|
265
|
-
const credential = await pending.login(choice.providerId, choice.authType, interaction);
|
|
266
|
-
await proveApiKey(pending, choice.providerId);
|
|
267
|
-
await auth.credentials.modify(choice.providerId, async () => credential);
|
|
268
|
-
// The credential is only reachable through a declared route, so the
|
|
269
|
-
// sign-in is not finished until one exists.
|
|
270
|
-
return await declareProviderRoute(ctx.get('settings'), choice.providerId);
|
|
271
|
-
},
|
|
272
|
-
stored: async (providerId) => {
|
|
273
|
-
const credentials = ctx.get('credentials');
|
|
274
|
-
if (credentials === undefined)
|
|
275
|
-
return undefined;
|
|
276
|
-
const record = await credentials.readRecord(recordKeyFor(providerId));
|
|
277
|
-
if (record === undefined)
|
|
278
|
-
return undefined;
|
|
279
|
-
return record.kind === 'api-key' ? 'api_key' : 'oauth';
|
|
280
|
-
},
|
|
281
|
-
reference: async (providerId) => {
|
|
282
|
-
// A route this plugin mounts names its reference in this plugin's
|
|
283
|
-
// config; every other route is whatever llm-pi-ai was configured
|
|
284
|
-
// with, which is the same document a sign-in declares into.
|
|
285
|
-
const ref = declaredCredentialRef(ctx.get('settings'), providerId)
|
|
286
|
-
?? (providerId === route.provider ? route.apiKeyEnv : undefined);
|
|
287
|
-
if (ref === undefined || ref.length === 0)
|
|
288
|
-
return undefined;
|
|
289
|
-
const credentials = ctx.get('credentials');
|
|
290
|
-
if (credentials === undefined)
|
|
291
|
-
return { ref };
|
|
292
|
-
const info = await credentials.describe(ref);
|
|
293
|
-
return { ref, ...info.configured && info.source !== undefined ? { source: info.source } : {} };
|
|
294
|
-
},
|
|
295
|
-
// Resolved per call, never at mount: a composition that mounts no
|
|
296
|
-
// session UI still gets the command, and says so when it runs.
|
|
297
|
-
ask: async (request) => {
|
|
298
|
-
const userQuestions = ctx.get('userQuestions');
|
|
299
|
-
if (userQuestions === undefined) {
|
|
300
|
-
throw new Error('dsh-provider-extra: this composition mounts no session UI that can ask the sign-in questions');
|
|
301
|
-
}
|
|
302
|
-
return await userQuestions.ask({
|
|
303
|
-
questions: [...request.questions],
|
|
304
|
-
agent: request.agent,
|
|
305
|
-
...request.signal === undefined ? {} : { signal: request.signal },
|
|
306
|
-
});
|
|
307
|
-
},
|
|
308
|
-
};
|
|
309
|
-
commandCtx.commands.register(createLoginCommand(host, config.loginCommandName));
|
|
310
|
-
// Registration is silent otherwise, and the command is the one surface a
|
|
311
|
-
// user cannot see in a config dump: saying it exists is the diagnosis.
|
|
312
|
-
ctx.logger.info('dsh-provider-extra: /' + config.loginCommandName + ' signs in any provider with an interactive login');
|
|
313
|
-
});
|
|
314
|
-
}
|
|
269
|
+
mountLoginCommand(ctx, config, { profiles });
|
|
315
270
|
}
|