@zoraxylia/dsh-codex-adapter 0.1.5 → 0.1.7
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/.claude-plugin/plugin.json +1 -1
- package/lib/server.mjs +6 -1
- package/package.json +1 -1
- package/src/hub/index.mjs +128 -15
- package/src/install/install.mjs +5 -0
- package/src/model-caps.mjs +251 -0
- package/src/server.mjs +1 -1
package/lib/server.mjs
CHANGED
|
@@ -14437,6 +14437,11 @@ var GLOBAL_CONFIG_DEFAULTS = {
|
|
|
14437
14437
|
// effort changes instead of being treated as a deliberate pin.
|
|
14438
14438
|
flash_auto: false,
|
|
14439
14439
|
pro_auto: false,
|
|
14440
|
+
// Optional per-provider endpoints for upstream capability lookup. Empty
|
|
14441
|
+
// entries fall back to the baseURL/apiKeyEnv found in the DSH profile patch.
|
|
14442
|
+
upstream_caps: {},
|
|
14443
|
+
// How long an upstream catalog stays authoritative, in seconds.
|
|
14444
|
+
caps_ttl_seconds: 21600,
|
|
14440
14445
|
// Hub-mode agent preset per tier: 'default' follows the DSH roster default.
|
|
14441
14446
|
preset_flash: "minimal",
|
|
14442
14447
|
preset_pro: "default"
|
|
@@ -15064,7 +15069,7 @@ function describeBindings(config = {}) {
|
|
|
15064
15069
|
}
|
|
15065
15070
|
|
|
15066
15071
|
// src/server.mjs
|
|
15067
|
-
var server = new McpServer({ name: "dsh-adapter", version: "0.1.
|
|
15072
|
+
var server = new McpServer({ name: "dsh-adapter", version: "0.1.7" });
|
|
15068
15073
|
var tierSchema = external_exports.enum(["flash", "pro"]).optional().describe("Worker model tier. flash = mechanical, well-scoped work (single-file edits, lookups, formatting); pro = multi-file changes, debugging, design judgment. Omit to use the session default. Ignored when worker= is set.");
|
|
15069
15074
|
var effortSchema = external_exports.enum(["off", "high", "max"]).optional().describe("Reasoning effort for the worker. Omit to use the session default. With worker= it only applies when passed explicitly and the profile supports it (agy maps to low/medium/high).");
|
|
15070
15075
|
var workerSchema = external_exports.string().optional().describe('Named CLI worker profile (e.g. "agy" or "grok"). Explicit opt-in only: set it when the user explicitly asks for that external coding CLI, never as a default. When set, dispatch bypasses tier/mode and runs the task through that CLI; the profile pins backend\xD7model\xD7effort. See dsh_worker_config output, worker_profiles field, for the available profiles.');
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zoraxylia/dsh-codex-adapter",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.7",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./src/hub/index.mjs",
|
|
6
6
|
"description": "DeepSeek Harness plugin: dispatch work to DSH agents from Claude Code / Codex, as native subagents with live progress",
|
package/src/hub/index.mjs
CHANGED
|
@@ -84,6 +84,8 @@ const ROUTE_BASE = '/_dsh/dsh-adapter';
|
|
|
84
84
|
// caller may override per dispatch, and the hub's own config is the fallback
|
|
85
85
|
// when it does not (the same shape the preset lookup below uses).
|
|
86
86
|
import { describeBindings, resolveTierBinding, TIERS } from '../tier-binding.mjs';
|
|
87
|
+
import { readGlobalConfig, writeGlobalConfig } from '../install/install.mjs';
|
|
88
|
+
import { readCapsCache, writeCapsCache, capsFor, resolveProviderEndpoint, fetchUpstreamCaps } from '../model-caps.mjs';
|
|
87
89
|
const CONFIG_DIR = join(homedir(), '.config', 'dsh-adapter');
|
|
88
90
|
|
|
89
91
|
// ---------- job registry ----------
|
|
@@ -122,6 +124,67 @@ export class WorkerRegistry {
|
|
|
122
124
|
this.shard.publish([...this.jobs.values()].map((j) => this.view(j)));
|
|
123
125
|
}
|
|
124
126
|
|
|
127
|
+
/**
|
|
128
|
+
* Ask the host what reasoning efforts this exact model accepts. DSH resolves
|
|
129
|
+
* model metadata through the adapter (the same call that rejects an
|
|
130
|
+
* unsupported effort before any provider I/O), so this is the authoritative
|
|
131
|
+
* dictionary - no provider-specific guessing. Returns {effort} for the value
|
|
132
|
+
* to dispatch with, or null when the adapter offers no reasoning metadata.
|
|
133
|
+
*/
|
|
134
|
+
/** The provider's own catalog, cached on disk; undefined when unreachable. */
|
|
135
|
+
async upstreamCaps(provider) {
|
|
136
|
+
const cfg = this.getConfig?.() ?? {};
|
|
137
|
+
const ttl = Number(cfg.caps_ttl_seconds) || undefined;
|
|
138
|
+
this.capsCache ??= readCapsCache();
|
|
139
|
+
const cached = capsFor(this.capsCache, provider, ttl);
|
|
140
|
+
if (cached) return cached;
|
|
141
|
+
const endpoint = resolveProviderEndpoint(provider, (cfg.upstream_caps ?? {})[provider]);
|
|
142
|
+
if (!endpoint) return undefined;
|
|
143
|
+
const entry = await fetchUpstreamCaps(provider, endpoint, { ttlSeconds: ttl });
|
|
144
|
+
this.capsCache = writeCapsCache(provider, entry);
|
|
145
|
+
return entry;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Which effort to dispatch with, using the upstream catalog when it answers
|
|
150
|
+
* and the host's local metadata as the fallback. Both describe the same model,
|
|
151
|
+
* so only the intersection is safe: the upstream may have dropped a level the
|
|
152
|
+
* profile still declares (the pro-model thrash this plugin kept hitting).
|
|
153
|
+
* { effort } dispatch this effort (undefined = no reasoning option)
|
|
154
|
+
* { skip: true } the two sources disagree; do not bind this model
|
|
155
|
+
* null no local reasoning metadata at all; let the probe decide
|
|
156
|
+
*/
|
|
157
|
+
async effortForModel(llm, binding, desired) {
|
|
158
|
+
if (typeof llm.resolveModelInfo !== 'function') return null;
|
|
159
|
+
let info;
|
|
160
|
+
try { info = await llm.resolveModelInfo(binding.provider, binding.model); }
|
|
161
|
+
catch { return null; }
|
|
162
|
+
const reasoning = info?.reasoning;
|
|
163
|
+
if (!reasoning) return { effort: undefined, supported: [] };
|
|
164
|
+
const local = (reasoning.efforts ?? []).map((e) => e.id).filter((id) => typeof id === 'string');
|
|
165
|
+
if (local.length === 0) return null;
|
|
166
|
+
|
|
167
|
+
let upstream;
|
|
168
|
+
try {
|
|
169
|
+
const caps = await this.upstreamCaps(binding.provider);
|
|
170
|
+
const entry = caps?.models?.[binding.model];
|
|
171
|
+
if (entry && Array.isArray(entry.efforts)) upstream = entry.efforts;
|
|
172
|
+
} catch { /* catalog optional */ }
|
|
173
|
+
|
|
174
|
+
const allowed = upstream ? local.filter((id) => upstream.includes(id)) : local;
|
|
175
|
+
const source = upstream ? 'upstream' : 'local';
|
|
176
|
+
if (allowed.length === 0) return { skip: true, supported: [], source };
|
|
177
|
+
const pick = (wanted) => {
|
|
178
|
+
if (wanted === undefined) return reasoning.defaultEffort && allowed.includes(reasoning.defaultEffort) ? reasoning.defaultEffort : allowed[0];
|
|
179
|
+
if (allowed.includes(wanted)) return wanted;
|
|
180
|
+
for (const candidate of ['max', 'high', 'medium', 'low', 'off']) {
|
|
181
|
+
if (allowed.includes(candidate)) return candidate;
|
|
182
|
+
}
|
|
183
|
+
return allowed[0];
|
|
184
|
+
};
|
|
185
|
+
return { effort: pick(desired), supported: allowed, source };
|
|
186
|
+
}
|
|
187
|
+
|
|
125
188
|
/** One bounded capability probe; the route counts as usable when it streams. */
|
|
126
189
|
async probeRoute(llm, binding, effort) {
|
|
127
190
|
try {
|
|
@@ -158,22 +221,35 @@ export class WorkerRegistry {
|
|
|
158
221
|
for (const m of models.slice(0, 3)) candidates.push({ provider: id, model: m.id });
|
|
159
222
|
if (candidates.length >= 5) break;
|
|
160
223
|
}
|
|
161
|
-
const
|
|
162
|
-
|
|
163
|
-
|
|
224
|
+
for (const candidate of candidates) {
|
|
225
|
+
const known = await this.effortForModel(llm, candidate, effort);
|
|
226
|
+
let attemptEffort;
|
|
227
|
+
if (known?.skip) continue;
|
|
228
|
+
if (known) {
|
|
229
|
+
// The host already answered which efforts this model accepts; the
|
|
230
|
+
// probe below only proves the route streams.
|
|
231
|
+
attemptEffort = known.supported.length === 0 ? undefined : known.effort;
|
|
164
232
|
if (!(await this.probeRoute(llm, candidate, attemptEffort))) continue;
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
} catch { /* read-only home: keep the in-memory choice */ }
|
|
174
|
-
this.ctx?.logger?.info?.(`dsh-adapter: ${tier} auto-bound to ${candidate.provider}/${candidate.model} @ ${attemptEffort}`);
|
|
175
|
-
return chosen;
|
|
233
|
+
} else {
|
|
234
|
+
// No reasoning metadata from the adapter: probe the wanted effort, then
|
|
235
|
+
// 'off', which is the cheapest compatible setting.
|
|
236
|
+
attemptEffort = undefined;
|
|
237
|
+
for (const candidateEffort of effort && effort !== 'off' ? [effort, 'off'] : [effort ?? undefined]) {
|
|
238
|
+
if (await this.probeRoute(llm, candidate, candidateEffort)) { attemptEffort = candidateEffort; break; }
|
|
239
|
+
}
|
|
240
|
+
if (attemptEffort === undefined && !(await this.probeRoute(llm, candidate, undefined))) continue;
|
|
176
241
|
}
|
|
242
|
+
const chosen = { binding: candidate, effort: attemptEffort };
|
|
243
|
+
this.autoTier[cacheKey] = chosen;
|
|
244
|
+
try {
|
|
245
|
+
writeGlobalConfig({
|
|
246
|
+
[`${tier}_provider`]: candidate.provider,
|
|
247
|
+
[`${tier}_model`]: candidate.model,
|
|
248
|
+
[`${tier}_auto`]: true,
|
|
249
|
+
});
|
|
250
|
+
} catch { /* read-only home: keep the in-memory choice */ }
|
|
251
|
+
this.ctx?.logger?.info?.(`dsh-adapter: ${tier} auto-bound to ${candidate.provider}/${candidate.model} @ ${attemptEffort ?? '(none)'} [${known?.source ?? 'probe'}]`);
|
|
252
|
+
return chosen;
|
|
177
253
|
}
|
|
178
254
|
this.ctx?.logger?.warn?.(`dsh-adapter: no usable ${tier} route; keeping ${bound.provider}/${bound.model}`);
|
|
179
255
|
return { binding: bound, effort };
|
|
@@ -643,8 +719,18 @@ export async function apply(ctx) {
|
|
|
643
719
|
const providers = [];
|
|
644
720
|
for (const p of ctx.llm.listProviders()) {
|
|
645
721
|
let models = [];
|
|
722
|
+
const modelInfo = {};
|
|
646
723
|
try { models = (await ctx.llm.listModels(p.id)).map((m) => m.id); } catch { /* adapter without a catalog */ }
|
|
647
|
-
|
|
724
|
+
for (const id of models) {
|
|
725
|
+
try {
|
|
726
|
+
const info = await ctx.llm.resolveModelInfo(p.id, id);
|
|
727
|
+
modelInfo[id] = {
|
|
728
|
+
efforts: (info?.reasoning?.efforts ?? []).map((e) => e.id),
|
|
729
|
+
...(info?.reasoning?.defaultEffort === undefined ? {} : { defaultEffort: info.reasoning.defaultEffort }),
|
|
730
|
+
};
|
|
731
|
+
} catch { /* metadata optional */ }
|
|
732
|
+
}
|
|
733
|
+
providers.push({ id: p.id, name: p.name ?? p.id, models, model_info: modelInfo });
|
|
648
734
|
}
|
|
649
735
|
return sendJson(res, 200, {
|
|
650
736
|
ok: true,
|
|
@@ -657,6 +743,33 @@ export async function apply(ctx) {
|
|
|
657
743
|
},
|
|
658
744
|
}));
|
|
659
745
|
|
|
746
|
+
disposers.push(webServer.register({
|
|
747
|
+
kind: 'exact', path: `${ROUTE_BASE}/model-caps`,
|
|
748
|
+
handler: async (req, res) => {
|
|
749
|
+
if (!isLoopbackRequest(req)) return sendJson(res, 403, { ok: false, error: 'loopback only' });
|
|
750
|
+
try {
|
|
751
|
+
const cfg = readGlobalConfig();
|
|
752
|
+
if (req.method === 'POST') {
|
|
753
|
+
const body = await readBody(req);
|
|
754
|
+
const provider = typeof body?.provider === 'string' ? body.provider.trim() : '';
|
|
755
|
+
if (!provider) return sendJson(res, 400, { ok: false, error: 'provider required' });
|
|
756
|
+
const endpoint = resolveProviderEndpoint(provider, (cfg.upstream_caps ?? {})[provider]);
|
|
757
|
+
const entry = await fetchUpstreamCaps(provider, endpoint, { ttlSeconds: cfg.caps_ttl_seconds });
|
|
758
|
+
const cache = writeCapsCache(provider, entry);
|
|
759
|
+
return sendJson(res, 200, { ok: true, entry, cached: cache.providers[provider] });
|
|
760
|
+
}
|
|
761
|
+
const endpoints = {};
|
|
762
|
+
for (const p of ctx.llm.listProviders()) {
|
|
763
|
+
const endpoint = resolveProviderEndpoint(p.id, (cfg.upstream_caps ?? {})[p.id]);
|
|
764
|
+
endpoints[p.id] = endpoint ? { baseUrl: endpoint.baseUrl, apiKeyEnv: endpoint.apiKeyEnv, source: endpoint.source } : null;
|
|
765
|
+
}
|
|
766
|
+
return sendJson(res, 200, { ok: true, cache: readCapsCache(), endpoints });
|
|
767
|
+
} catch (err) {
|
|
768
|
+
return sendJson(res, 500, { ok: false, error: err?.message ?? String(err) });
|
|
769
|
+
}
|
|
770
|
+
},
|
|
771
|
+
}));
|
|
772
|
+
|
|
660
773
|
disposers.push(webServer.register({
|
|
661
774
|
kind: 'exact', path: `${ROUTE_BASE}/vision-models`,
|
|
662
775
|
handler: async (req, res) => {
|
package/src/install/install.mjs
CHANGED
|
@@ -114,6 +114,11 @@ export const GLOBAL_CONFIG_DEFAULTS = {
|
|
|
114
114
|
// effort changes instead of being treated as a deliberate pin.
|
|
115
115
|
flash_auto: false,
|
|
116
116
|
pro_auto: false,
|
|
117
|
+
// Optional per-provider endpoints for upstream capability lookup. Empty
|
|
118
|
+
// entries fall back to the baseURL/apiKeyEnv found in the DSH profile patch.
|
|
119
|
+
upstream_caps: {},
|
|
120
|
+
// How long an upstream catalog stays authoritative, in seconds.
|
|
121
|
+
caps_ttl_seconds: 21600,
|
|
117
122
|
// Hub-mode agent preset per tier: 'default' follows the DSH roster default.
|
|
118
123
|
preset_flash: 'minimal',
|
|
119
124
|
preset_pro: 'default',
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
// Upstream model-capability lookup.
|
|
2
|
+
//
|
|
3
|
+
// DSH's own metadata (ctx.llm.resolveModelInfo) is a local declaration: the
|
|
4
|
+
// pi-ai adapter builds it from the profile's `reasoningEfforts`, so it can go
|
|
5
|
+
// stale the moment a gateway changes what a model actually accepts. This module
|
|
6
|
+
// asks the provider itself for its catalog, in whatever shape it returns, and
|
|
7
|
+
// caches the answer next to the plugin's config so the local dictionary learns
|
|
8
|
+
// what the upstream really offers.
|
|
9
|
+
//
|
|
10
|
+
// Supported payload shapes (best effort):
|
|
11
|
+
// { data: [ { id, ... } ] } OpenAI / vLLM / LM Studio / OpenRouter
|
|
12
|
+
// { models: [ ... ] } Ollama, llama.cpp server
|
|
13
|
+
// [ { id | model | name, ... } ] bare arrays
|
|
14
|
+
// Capability fields read from an entry:
|
|
15
|
+
// reasoning_efforts / reasoningEfforts / supported_reasoning_efforts /
|
|
16
|
+
// thinking_levels / effort_levels / capabilities.* / parameters
|
|
17
|
+
// supported_parameters: ["reasoning", ...] -> knows reasoning exists, not the levels
|
|
18
|
+
// Anything unrecognised is reported as unknown rather than guessed.
|
|
19
|
+
|
|
20
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
|
21
|
+
import { homedir } from 'node:os';
|
|
22
|
+
import { join } from 'node:path';
|
|
23
|
+
|
|
24
|
+
const CONFIG_DIR = join(homedir(), '.config', 'dsh-adapter');
|
|
25
|
+
const CACHE_FILE = join(CONFIG_DIR, 'model-caps.json');
|
|
26
|
+
const CREDENTIALS_FILE = join(homedir(), '.dsh', '.credentials.yaml');
|
|
27
|
+
|
|
28
|
+
const DEFAULT_TTL_SECONDS = 6 * 60 * 60;
|
|
29
|
+
|
|
30
|
+
function readJson(file, fallback) {
|
|
31
|
+
try { return JSON.parse(readFileSync(file, 'utf8')); } catch { return fallback; }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function readCapsCache() {
|
|
35
|
+
const data = readJson(CACHE_FILE, { providers: {} });
|
|
36
|
+
if (!data || typeof data !== 'object') return { providers: {} };
|
|
37
|
+
if (!data.providers || typeof data.providers !== 'object') data.providers = {};
|
|
38
|
+
return data;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function writeCapsCache(provider, entry) {
|
|
42
|
+
const data = readCapsCache();
|
|
43
|
+
data.providers[provider] = entry;
|
|
44
|
+
try {
|
|
45
|
+
mkdirSync(CONFIG_DIR, { recursive: true });
|
|
46
|
+
writeFileSync(CACHE_FILE, JSON.stringify(data, null, 2) + '\n');
|
|
47
|
+
} catch { /* read-only home: keep the in-memory copy */ }
|
|
48
|
+
return data;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function capsFor(cache, provider, ttlSeconds = DEFAULT_TTL_SECONDS) {
|
|
52
|
+
const entry = cache?.providers?.[provider];
|
|
53
|
+
if (!entry || typeof entry.fetchedAt !== 'string') return undefined;
|
|
54
|
+
const age = Date.now() - Date.parse(entry.fetchedAt);
|
|
55
|
+
if (!Number.isFinite(age) || age > ttlSeconds * 1000) return undefined;
|
|
56
|
+
return entry;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Find a provider's endpoint and key reference. Explicit config wins; otherwise
|
|
61
|
+
* the DSH profile patch is scanned, because that is where `llm-pi-ai` keeps
|
|
62
|
+
* `baseURL` / `apiKeyEnv` for each route.
|
|
63
|
+
*/
|
|
64
|
+
export function resolveProviderEndpoint(providerId, explicit = {}) {
|
|
65
|
+
if (explicit && (explicit.base_url || explicit.baseURL)) {
|
|
66
|
+
return {
|
|
67
|
+
baseUrl: String(explicit.base_url ?? explicit.baseURL).replace(/\/+$/, ''),
|
|
68
|
+
apiKeyEnv: explicit.api_key_env ?? explicit.apiKeyEnv,
|
|
69
|
+
headers: explicit.headers ?? {},
|
|
70
|
+
source: 'config',
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
const root = join(homedir(), '.dsh', 'profiles');
|
|
74
|
+
let dirs = [];
|
|
75
|
+
try { dirs = readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name); } catch { return undefined; }
|
|
76
|
+
for (const name of dirs) {
|
|
77
|
+
const file = join(root, name, 'cordis.patch.yml');
|
|
78
|
+
if (!existsSync(file)) continue;
|
|
79
|
+
let text = '';
|
|
80
|
+
try { text = readFileSync(file, 'utf8'); } catch { continue; }
|
|
81
|
+
const block = providerBlock(text, providerId);
|
|
82
|
+
if (!block) continue;
|
|
83
|
+
const baseUrl = matchValue(block, 'baseURL') ?? matchValue(block, 'base_url');
|
|
84
|
+
if (!baseUrl) continue;
|
|
85
|
+
return {
|
|
86
|
+
baseUrl: baseUrl.replace(/\/+$/, ''),
|
|
87
|
+
apiKeyEnv: matchValue(block, 'apiKeyEnv') ?? matchValue(block, 'api_key_env'),
|
|
88
|
+
headers: {},
|
|
89
|
+
source: 'profile:' + name,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function providerBlock(text, providerId) {
|
|
96
|
+
const lines = text.split(/\r?\n/);
|
|
97
|
+
const head = new RegExp(`^(\\s{2,})${providerId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*:\\s*$`);
|
|
98
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
99
|
+
const m = head.exec(lines[i]);
|
|
100
|
+
if (!m) continue;
|
|
101
|
+
const indent = m[1].length;
|
|
102
|
+
const out = [];
|
|
103
|
+
for (let j = i + 1; j < lines.length; j += 1) {
|
|
104
|
+
const line = lines[j];
|
|
105
|
+
if (line.trim() === '') { out.push(''); continue; }
|
|
106
|
+
const ind = line.length - line.trimStart().length;
|
|
107
|
+
if (ind <= indent) break;
|
|
108
|
+
out.push(line);
|
|
109
|
+
}
|
|
110
|
+
return out.join('\n');
|
|
111
|
+
}
|
|
112
|
+
return '';
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function matchValue(block, key) {
|
|
116
|
+
const m = new RegExp(`^\\s*${key}\\s*:\\s*['"]?([^'"\\n#]+)`, 'm').exec(block);
|
|
117
|
+
return m ? m[1].trim() : undefined;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The credentials file keeps `refs:` as plain name -> secret pairs. */
|
|
121
|
+
export function readCredentialRef(name) {
|
|
122
|
+
try {
|
|
123
|
+
const text = readFileSync(CREDENTIALS_FILE, 'utf8');
|
|
124
|
+
const start = text.indexOf('\nrefs:');
|
|
125
|
+
const slice = start === -1 ? text : text.slice(start);
|
|
126
|
+
const m = new RegExp(`^\\s{2}${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*:\\s*(\\S+)\\s*$`, 'm').exec(slice);
|
|
127
|
+
return m ? m[1] : undefined;
|
|
128
|
+
} catch { return undefined; }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function normalizeEffort(raw) {
|
|
132
|
+
if (typeof raw === 'string') {
|
|
133
|
+
const v = raw.trim().toLowerCase();
|
|
134
|
+
if (!v) return undefined;
|
|
135
|
+
if (v === 'none' || v === 'disabled') return 'off';
|
|
136
|
+
if (v === 'minimal') return 'low';
|
|
137
|
+
return v;
|
|
138
|
+
}
|
|
139
|
+
if (raw && typeof raw === 'object') {
|
|
140
|
+
const id = raw.id ?? raw.level ?? raw.name ?? raw.effort;
|
|
141
|
+
return normalizeEffort(id);
|
|
142
|
+
}
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function effortList(value) {
|
|
147
|
+
if (Array.isArray(value)) return value.map(normalizeEffort).filter(Boolean);
|
|
148
|
+
if (typeof value === 'string') return value.split(/[,\s|]+/).map(normalizeEffort).filter(Boolean);
|
|
149
|
+
if (value && typeof value === 'object') {
|
|
150
|
+
// { off: ..., high: ... } maps a declared level to its wire value.
|
|
151
|
+
return Object.keys(value).map(normalizeEffort).filter(Boolean);
|
|
152
|
+
}
|
|
153
|
+
return [];
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const EFFORT_FIELDS = [
|
|
157
|
+
'reasoning_efforts', 'reasoningEfforts', 'supported_reasoning_efforts', 'supportedReasoningEfforts',
|
|
158
|
+
'thinking_levels', 'thinkingLevels', 'effort_levels', 'effortLevels', 'reasoning_levels',
|
|
159
|
+
];
|
|
160
|
+
|
|
161
|
+
function extractEfforts(entry) {
|
|
162
|
+
for (const field of EFFORT_FIELDS) {
|
|
163
|
+
if (entry[field] !== undefined) {
|
|
164
|
+
const list = effortList(entry[field]);
|
|
165
|
+
if (list.length) return { efforts: list };
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
for (const container of ['capabilities', 'capability', 'features']) {
|
|
169
|
+
const value = entry[container];
|
|
170
|
+
if (!value || typeof value !== 'object') continue;
|
|
171
|
+
for (const field of EFFORT_FIELDS) {
|
|
172
|
+
if (value[field] !== undefined) {
|
|
173
|
+
const list = effortList(value[field]);
|
|
174
|
+
if (list.length) return { efforts: list };
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (value.reasoning === false) return { efforts: [] };
|
|
178
|
+
}
|
|
179
|
+
if (entry.reasoning === false) return { efforts: [] };
|
|
180
|
+
const params = entry.supported_parameters ?? entry.supportedParameters;
|
|
181
|
+
if (Array.isArray(params)) {
|
|
182
|
+
const names = params.map((p) => String(p).toLowerCase());
|
|
183
|
+
if (names.some((n) => n.includes('reasoning'))) return { efforts: undefined };
|
|
184
|
+
}
|
|
185
|
+
return undefined;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function entriesOf(payload) {
|
|
189
|
+
if (Array.isArray(payload)) return payload;
|
|
190
|
+
if (!payload || typeof payload !== 'object') return [];
|
|
191
|
+
for (const key of ['data', 'models', 'result', 'items']) {
|
|
192
|
+
if (Array.isArray(payload[key])) return payload[key];
|
|
193
|
+
}
|
|
194
|
+
return [];
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Parse one /models payload into { models: { id: { efforts } }, unknown } */
|
|
198
|
+
export function parseCapsPayload(payload) {
|
|
199
|
+
const models = {};
|
|
200
|
+
for (const entry of entriesOf(payload)) {
|
|
201
|
+
if (!entry || typeof entry !== 'object') continue;
|
|
202
|
+
const id = entry.id ?? entry.model ?? entry.name;
|
|
203
|
+
if (typeof id !== 'string' || id === '') continue;
|
|
204
|
+
const found = extractEfforts(entry);
|
|
205
|
+
if (!found) continue;
|
|
206
|
+
models[id] = found.efforts === undefined ? { unknown: true } : { efforts: found.efforts };
|
|
207
|
+
}
|
|
208
|
+
return models;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function getJson(url, headers, timeoutMs) {
|
|
212
|
+
const controller = new AbortController();
|
|
213
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
214
|
+
try {
|
|
215
|
+
const res = await fetch(url, { headers, signal: controller.signal });
|
|
216
|
+
if (!res.ok) return { error: 'HTTP ' + res.status };
|
|
217
|
+
return { json: await res.json() };
|
|
218
|
+
} catch (err) {
|
|
219
|
+
return { error: err?.name === 'AbortError' ? 'timeout' : String(err?.message ?? err) };
|
|
220
|
+
} finally { clearTimeout(timer); }
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Fetch a provider's catalog. Tries `{base}/v1/models` and `{base}/models`
|
|
225
|
+
* because gateways disagree about whether `baseURL` already ends in /v1.
|
|
226
|
+
*/
|
|
227
|
+
export async function fetchUpstreamCaps(providerId, endpoint, { timeoutMs = 8000, ttlSeconds } = {}) {
|
|
228
|
+
if (!endpoint?.baseUrl) return { provider: providerId, error: 'no base_url', tried: [] };
|
|
229
|
+
const headers = { accept: 'application/json', ...(endpoint.headers ?? {}) };
|
|
230
|
+
if (endpoint.apiKeyEnv) {
|
|
231
|
+
const key = process.env[endpoint.apiKeyEnv] ?? readCredentialRef(endpoint.apiKeyEnv);
|
|
232
|
+
if (key) headers.authorization = 'Bearer ' + key;
|
|
233
|
+
}
|
|
234
|
+
const base = endpoint.baseUrl.replace(/\/+$/, '');
|
|
235
|
+
const urls = [];
|
|
236
|
+
if (/\/v1$/.test(base)) urls.push(base + '/models');
|
|
237
|
+
else urls.push(base + '/v1/models', base + '/models');
|
|
238
|
+
const tried = [];
|
|
239
|
+
let lastError = 'unreachable';
|
|
240
|
+
for (const url of urls) {
|
|
241
|
+
const result = await getJson(url, headers, timeoutMs);
|
|
242
|
+
tried.push(url);
|
|
243
|
+
if (result.json === undefined) { lastError = result.error ?? lastError; continue; }
|
|
244
|
+
const models = parseCapsPayload(result.json);
|
|
245
|
+
if (Object.keys(models).length === 0) {
|
|
246
|
+
return { provider: providerId, baseUrl: base, fetchedAt: new Date().toISOString(), ttlSeconds, models, tried, note: 'catalog has no capability fields' };
|
|
247
|
+
}
|
|
248
|
+
return { provider: providerId, baseUrl: base, fetchedAt: new Date().toISOString(), ttlSeconds, models, tried };
|
|
249
|
+
}
|
|
250
|
+
return { provider: providerId, baseUrl: base, fetchedAt: new Date().toISOString(), ttlSeconds, models: {}, error: lastError, tried };
|
|
251
|
+
}
|
package/src/server.mjs
CHANGED
|
@@ -12,7 +12,7 @@ import { acquireCwdLock, releaseCwdLockByJobId, updateCwdLockHolder, getCwdLocks
|
|
|
12
12
|
import { resolveWorkerCwd } from './paths.mjs';
|
|
13
13
|
import { detectOrchestrator } from './process-info.mjs';
|
|
14
14
|
|
|
15
|
-
const server = new McpServer({ name: 'dsh-adapter', version: '0.1.
|
|
15
|
+
const server = new McpServer({ name: 'dsh-adapter', version: '0.1.7' });
|
|
16
16
|
|
|
17
17
|
const tierSchema = z.enum(['flash', 'pro']).optional().describe('Worker model tier. flash = mechanical, well-scoped work (single-file edits, lookups, formatting); pro = multi-file changes, debugging, design judgment. Omit to use the session default. Ignored when worker= is set.');
|
|
18
18
|
const effortSchema = z.enum(['off', 'high', 'max']).optional().describe('Reasoning effort for the worker. Omit to use the session default. With worker= it only applies when passed explicitly and the profile supports it (agy maps to low/medium/high).');
|