dsh-autorouter 0.0.0-stage → 0.2.1

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/src/http.js ADDED
@@ -0,0 +1,371 @@
1
+ /**
2
+ * Same-origin JSON surface for the Settings page. It runs on the harness's own
3
+ * port (`webServer.register`), is authenticated by the harness, and is the only
4
+ * place that calls `settings.replace` — so every save stays revision-checked.
5
+ *
6
+ * It never returns credentials, prompts or message bodies.
7
+ */
8
+
9
+ import { ENTRY_ID, PROVIDER_ID, matchSettingsEntry, normalizeConfig } from './config.js'
10
+
11
+ const MAX_BODY = 2 * 1024 * 1024
12
+
13
+ function json(res, status, body) {
14
+ const text = JSON.stringify(body)
15
+ res.writeHead(status, {
16
+ 'content-type': 'application/json; charset=utf-8',
17
+ 'cache-control': 'no-store',
18
+ 'content-length': Buffer.byteLength(text),
19
+ })
20
+ res.end(text)
21
+ }
22
+
23
+ function readJson(req) {
24
+ return new Promise((resolve, reject) => {
25
+ let size = 0
26
+ const chunks = []
27
+ req.on('data', (chunk) => {
28
+ size += chunk.length
29
+ if (size > MAX_BODY) {
30
+ reject(Object.assign(new Error('body too large'), { statusCode: 413 }))
31
+ req.destroy()
32
+ return
33
+ }
34
+ chunks.push(chunk)
35
+ })
36
+ req.on('end', () => {
37
+ if (chunks.length === 0) {
38
+ resolve({})
39
+ return
40
+ }
41
+ try {
42
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))
43
+ } catch (error) {
44
+ reject(Object.assign(new Error(`invalid JSON: ${error.message}`), { statusCode: 400 }))
45
+ }
46
+ })
47
+ req.on('error', reject)
48
+ })
49
+ }
50
+
51
+ function redact(config) {
52
+ const { token, ...service } = config.service
53
+ return { ...config, service: { ...service, token: '', hasToken: typeof token === 'string' && token !== '' } }
54
+ }
55
+
56
+ export function installRoutes(deps) {
57
+ const { webServer, version, getConfig, getSettings, getLlm, getState, getSelection, onConfigSaved, onConfigWritten, logger } = deps
58
+ let catalogCache
59
+
60
+ async function providerDirectory(llm) {
61
+ // The directory method has been named differently across harness builds;
62
+ // probe the known shapes instead of pinning one and silently listing
63
+ // nothing on another.
64
+ for (const method of ['listProviders', 'listProviderDirectory', 'listConfigurableProviders']) {
65
+ if (typeof llm[method] !== 'function') continue
66
+ try {
67
+ const listed = await Promise.resolve(llm[method]())
68
+ if (Array.isArray(listed)) return listed
69
+ } catch (error) {
70
+ logger?.debug?.(`llm-autorouter: ${method} failed: ${error.message}`)
71
+ }
72
+ }
73
+ return []
74
+ }
75
+
76
+ async function buildCatalog(force = false) {
77
+ const now = Date.now()
78
+ if (!force && catalogCache !== undefined && now - catalogCache.at < 30_000) return catalogCache.value
79
+ const llm = getLlm()
80
+ if (llm === undefined) return { at: now, providers: [] }
81
+ const listed = await providerDirectory(llm)
82
+ const providers = await Promise.all(
83
+ listed.map(async (provider) => {
84
+ const id = typeof provider?.id === 'string' ? provider.id : provider?.provider
85
+ if (typeof id !== 'string' || id === '' || id === PROVIDER_ID) return undefined
86
+ let models = []
87
+ try {
88
+ models = await Promise.resolve(llm.listModels(id))
89
+ } catch {
90
+ models = []
91
+ }
92
+ return {
93
+ id,
94
+ name: typeof provider.name === 'string' ? provider.name : typeof provider.displayName === 'string' ? provider.displayName : id,
95
+ models: (Array.isArray(models) ? models : [])
96
+ .map((model) => ({
97
+ id: model.id,
98
+ name: typeof model.name === 'string' ? model.name : model.id,
99
+ ...(Array.isArray(model.inputModalities) ? { inputModalities: model.inputModalities } : {}),
100
+ }))
101
+ .sort((left, right) => left.id.localeCompare(right.id)),
102
+ }
103
+ }),
104
+ )
105
+ const value = { at: now, providers: providers.filter((provider) => provider !== undefined) }
106
+ catalogCache = { at: now, value }
107
+ return value
108
+ }
109
+
110
+ const routes = [
111
+ {
112
+ kind: 'exact',
113
+ path: '/api/autorouter/state',
114
+ auth: 'required',
115
+ handler: async (req, res) => {
116
+ if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' })
117
+ const settings = getSettings()
118
+ let descriptor
119
+ try {
120
+ descriptor = matchSettingsEntry(settings?.describe?.())
121
+ } catch (error) {
122
+ logger?.warn?.(`llm-autorouter: settings.describe failed: ${error.message}`)
123
+ }
124
+ const config = getConfig()
125
+ const state = getState()
126
+ json(res, 200, {
127
+ entryId: ENTRY_ID,
128
+ providerId: PROVIDER_ID,
129
+ revision: descriptor?.revision,
130
+ config: redact(config),
131
+ status: { ...state.snapshot(config, Date.now()), version },
132
+ })
133
+ },
134
+ },
135
+ {
136
+ kind: 'exact',
137
+ path: '/api/autorouter/config',
138
+ auth: 'required',
139
+ handler: async (req, res) => {
140
+ if (req.method === 'GET') {
141
+ const settings = getSettings()
142
+ let descriptor
143
+ try {
144
+ descriptor = matchSettingsEntry(settings?.describe?.())
145
+ } catch {
146
+ descriptor = undefined
147
+ }
148
+ return json(res, 200, {
149
+ revision: descriptor?.revision,
150
+ config: redact(getConfig()),
151
+ })
152
+ }
153
+ if (req.method !== 'PUT') return json(res, 405, { error: 'method not allowed' })
154
+ const settings = getSettings()
155
+ if (settings === undefined) return json(res, 503, { error: 'settings service unavailable' })
156
+ let body
157
+ try {
158
+ body = await readJson(req)
159
+ } catch (error) {
160
+ return json(res, error.statusCode ?? 400, { error: error.message })
161
+ }
162
+ if (typeof body !== 'object' || body === null || typeof body.value !== 'object') {
163
+ return json(res, 400, { error: 'expected { value, revision }' })
164
+ }
165
+ const current = getConfig()
166
+ const next = normalizeConfig(body.value, { fallback: current })
167
+ if (next.service.token === '' && current.service.token !== '') next.service.token = current.service.token
168
+ let descriptor
169
+ try {
170
+ descriptor = matchSettingsEntry(settings.describe())
171
+ } catch (error) {
172
+ return json(res, 503, { error: `settings unavailable: ${error.message}` })
173
+ }
174
+ if (descriptor === undefined) {
175
+ return json(res, 404, { error: `no profile entry "${ENTRY_ID}" — install or enable the bundle first` })
176
+ }
177
+ const expected = Number(body.revision)
178
+ if (Number.isFinite(expected) && descriptor.revision !== expected) {
179
+ return json(res, 409, {
180
+ error: 'revision conflict: the config was saved somewhere else',
181
+ revision: descriptor.revision,
182
+ config: redact(normalizeConfig(descriptor.value ?? current, { fallback: current })),
183
+ })
184
+ }
185
+ try {
186
+ await settings.replace(descriptor.ns, next, descriptor.revision)
187
+ } catch (error) {
188
+ return json(res, 409, { error: `save failed: ${error.message}`, revision: descriptor.revision })
189
+ }
190
+ // Hand back what was just written. Re-projecting through describe() here
191
+ // returns the pre-write document whenever the loader snapshot has not
192
+ // caught up yet, which makes Save look like it silently reverted.
193
+ onConfigWritten?.(next)
194
+ onConfigSaved?.()
195
+ let fresh
196
+ try {
197
+ fresh = matchSettingsEntry(settings.describe())
198
+ } catch {
199
+ fresh = undefined
200
+ }
201
+ json(res, 200, { ok: true, revision: fresh?.revision ?? descriptor.revision + 1, config: redact(next) })
202
+ },
203
+ },
204
+ {
205
+ kind: 'exact',
206
+ path: '/api/autorouter/catalog',
207
+ auth: 'required',
208
+ handler: async (req, res) => {
209
+ if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' })
210
+ const catalog = await buildCatalog(true)
211
+ json(res, 200, catalog)
212
+ },
213
+ },
214
+ {
215
+ kind: 'exact',
216
+ path: '/api/autorouter/probe',
217
+ auth: 'required',
218
+ handler: async (req, res) => {
219
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
220
+ let body
221
+ try {
222
+ body = await readJson(req)
223
+ } catch (error) {
224
+ return json(res, error.statusCode ?? 400, { error: error.message })
225
+ }
226
+ const provider = typeof body.provider === 'string' ? body.provider : ''
227
+ const model = typeof body.model === 'string' ? body.model : ''
228
+ const llm = getLlm()
229
+ if (provider === '' || model === '' || llm === undefined) {
230
+ return json(res, 400, { ok: false, error: 'provider and model are required' })
231
+ }
232
+ const startedAt = Date.now()
233
+ try {
234
+ const models = await Promise.resolve(llm.listModels(provider))
235
+ const found = Array.isArray(models) && models.some((item) => item.id === model)
236
+ if (!found) {
237
+ return json(res, 200, { ok: false, found: false, error: 'model not in this provider catalog' })
238
+ }
239
+ const info = await Promise.resolve(llm.resolveModelInfo(provider, model))
240
+ json(res, 200, {
241
+ ok: true,
242
+ found: true,
243
+ ms: Date.now() - startedAt,
244
+ info: {
245
+ name: info?.name,
246
+ context: info?.context,
247
+ reasoning: info?.reasoning,
248
+ toolUpdate: info?.toolUpdate,
249
+ },
250
+ })
251
+ } catch (error) {
252
+ json(res, 200, { ok: false, found: false, error: error.message, ms: Date.now() - startedAt })
253
+ }
254
+ },
255
+ },
256
+ {
257
+ kind: 'exact',
258
+ path: '/api/autorouter/try',
259
+ auth: 'required',
260
+ handler: async (req, res) => {
261
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
262
+ const llm = getLlm()
263
+ if (llm === undefined || typeof llm.stream !== 'function') {
264
+ return json(res, 200, { ok: false, error: 'llm runtime unavailable' })
265
+ }
266
+ let body
267
+ try {
268
+ body = await readJson(req)
269
+ } catch (error) {
270
+ return json(res, error.statusCode ?? 400, { error: error.message })
271
+ }
272
+ const config = getConfig()
273
+ const profile =
274
+ typeof body.profile === 'string' && body.profile !== ''
275
+ ? body.profile
276
+ : (config.profiles ?? []).find((item) => item.enabled !== false)?.id
277
+ if (typeof profile !== 'string' || profile === '') {
278
+ return json(res, 200, { ok: false, error: 'no profile to try' })
279
+ }
280
+ const prompt =
281
+ typeof body.prompt === 'string' && body.prompt.trim() !== ''
282
+ ? body.prompt
283
+ : 'Reply with the single word: ok'
284
+ const maxTokens = Number.isFinite(body.maxTokens) ? Math.max(8, Math.min(256, body.maxTokens)) : 24
285
+ const startedAt = Date.now()
286
+ let text = ''
287
+ let finish
288
+ try {
289
+ const stream = llm.stream({
290
+ provider: PROVIDER_ID,
291
+ model: profile,
292
+ messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
293
+ temperature: 0,
294
+ maxTokens,
295
+ })
296
+ for await (const chunk of stream) {
297
+ if (chunk?.type === 'text-delta' && typeof chunk.text === 'string') text += chunk.text
298
+ else if (chunk?.type === 'finish') finish = chunk
299
+ }
300
+ } catch (error) {
301
+ return json(res, 200, { ok: false, profile, ms: Date.now() - startedAt, error: error.message })
302
+ }
303
+ // The host reports a terminal outcome as {kind, failure}; older adapters
304
+ // used a bare string. Normalise, so a failure never reads as success.
305
+ const rawReason = finish?.reason
306
+ const reason = typeof rawReason === 'string' ? rawReason : rawReason?.kind
307
+ const failure = typeof rawReason === 'object' && rawReason !== null ? rawReason.failure : finish?.failure
308
+ const ok = reason !== undefined && reason !== 'error' && reason !== 'aborted'
309
+ json(res, 200, {
310
+ ok,
311
+ profile,
312
+ ms: Date.now() - startedAt,
313
+ route: getState().stats.lastRoute,
314
+ reason,
315
+ text: text.slice(0, 400),
316
+ usage: finish?.usage,
317
+ error: ok ? undefined : (failure?.message ?? 'the routed call did not complete'),
318
+ })
319
+ },
320
+ },
321
+ {
322
+ kind: 'exact',
323
+ path: '/api/autorouter/cooldown',
324
+ auth: 'required',
325
+ handler: async (req, res) => {
326
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
327
+ let body
328
+ try {
329
+ body = await readJson(req)
330
+ } catch (error) {
331
+ return json(res, error.statusCode ?? 400, { error: error.message })
332
+ }
333
+ const state = getState()
334
+ if (typeof body.key === 'string' && body.key !== '') state.clearCooldown(body.key)
335
+ else state.cooldowns.clear()
336
+ json(res, 200, { ok: true })
337
+ },
338
+ },
339
+ {
340
+ kind: 'exact',
341
+ path: '/api/autorouter/selection',
342
+ auth: 'required',
343
+ handler: async (req, res) => {
344
+ if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' })
345
+ json(res, 200, getSelection())
346
+ },
347
+ },
348
+ ]
349
+
350
+ const disposers = []
351
+ for (const route of routes) {
352
+ try {
353
+ disposers.push(webServer.register(route))
354
+ } catch (error) {
355
+ if (String(error?.message ?? '').includes('already')) {
356
+ logger?.debug?.(`llm-autorouter: route ${route.path} already registered`)
357
+ continue
358
+ }
359
+ throw error
360
+ }
361
+ }
362
+ return () => {
363
+ for (const dispose of disposers) {
364
+ try {
365
+ dispose()
366
+ } catch {
367
+ /* disposed with the fiber */
368
+ }
369
+ }
370
+ }
371
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Failure classification. Pure: no DSH imports, no clock, no I/O.
3
+ */
4
+
5
+ export const ROUTE_DEAD_CODES = new Set([
6
+ 'UNKNOWN_MODEL',
7
+ 'MISSING_CREDENTIAL',
8
+ 'INVALID_CREDENTIAL',
9
+ 'NO_CREDENTIAL_STORE',
10
+ 'ACCOUNT_SIGN_IN_REQUIRED',
11
+ 'ACCOUNT_TOKEN_INVALID',
12
+ ])
13
+
14
+ /** Failures that say "this request cannot work", not "this route is unhealthy". */
15
+ export const REQUEST_SCOPED_CODES = new Set([
16
+ 'CONTEXT_WINDOW_EXCEEDED',
17
+ 'MODEL_UNSUPPORTED',
18
+ 'UNSUPPORTED_OPTION',
19
+ 'UNSUPPORTED_CONTENT',
20
+ 'UNSUPPORTED_REASONING_EFFORT',
21
+ 'INVALID_REQUEST',
22
+ ])
23
+
24
+ const NETWORK_PATTERN =
25
+ /fetch failed|ECONN(?:REFUSED|RESET|ABORTED)|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket hang up|network|timed? ?out/i
26
+
27
+ const OAUTH_SUBJECT = /oauth[\s_-]*(?:refresh|token|grant)|token[\s_-]?refresh|refresh[\s_-]?token|authorization\s+grant/i
28
+ const OAUTH_TRANSIENT = /\btimeout\b|\bnetwork\b|fetch failed|ECONN(?:REFUSED|RESET|ABORTED)|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket hang up|\b(?:408|425|429|5\d{2})\b|rate[ _-]?limit|too many requests|temporar(?:y|ily)|unavailable/i
29
+
30
+ export function failureOf(error) {
31
+ if (error === undefined || error === null) return { message: 'unknown failure', code: undefined }
32
+ if (typeof error === 'object' && typeof error.failure === 'object' && error.failure !== null) return error.failure
33
+ return {
34
+ message: typeof error.message === 'string' ? error.message : String(error),
35
+ code: typeof error.code === 'string' ? error.code : undefined,
36
+ status: typeof error.status === 'number' ? error.status : undefined,
37
+ providerRetryAfterMs:
38
+ typeof error.providerRetryAfterMs === 'number' ? error.providerRetryAfterMs : undefined,
39
+ requestId: typeof error.requestId === 'string' ? error.requestId : undefined,
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Decide whether a failure may advance the chain.
45
+ *
46
+ * @returns {{retryable: boolean, code: string, status?: number, reason: string,
47
+ * requestScoped: boolean, retryAfterMs?: number, authish: boolean}}
48
+ */
49
+ export function classifyFailure(failure, policy, { alreadyCommitted = false } = {}) {
50
+ const message = typeof failure?.message === 'string' ? failure.message : ''
51
+ const rawCode = typeof failure?.code === 'string' ? failure.code : ''
52
+ const status = typeof failure?.status === 'number' ? failure.status : undefined
53
+ const authish =
54
+ rawCode === 'AUTH' ||
55
+ rawCode === 'UNAUTHORIZED' ||
56
+ status === 401 ||
57
+ status === 403 ||
58
+ (OAUTH_SUBJECT.test(message) && !OAUTH_TRANSIENT.test(message))
59
+ let code = rawCode === '' ? (authish ? 'AUTH' : 'UNKNOWN_ERROR') : rawCode
60
+ if (authish && code !== 'AUTH') code = 'AUTH'
61
+
62
+ const requestScoped = REQUEST_SCOPED_CODES.has(code)
63
+ const triggerCodes = policy.triggerCodes ?? []
64
+ const triggerStatuses = policy.triggerStatuses ?? []
65
+
66
+ let retryable = ROUTE_DEAD_CODES.has(code) || triggerCodes.includes(code)
67
+ if (!retryable && status !== undefined && triggerStatuses.includes(status)) retryable = true
68
+ if (!retryable && policy.retryOnNetwork !== false && NETWORK_PATTERN.test(message)) {
69
+ retryable = true
70
+ code = 'NETWORK_ERROR'
71
+ }
72
+ if (alreadyCommitted) retryable = false
73
+
74
+ const retryAfterMs =
75
+ policy.honorRetryAfter !== false && typeof failure?.providerRetryAfterMs === 'number'
76
+ ? Math.max(0, failure.providerRetryAfterMs)
77
+ : undefined
78
+
79
+ return {
80
+ retryable,
81
+ code,
82
+ status,
83
+ reason: message === '' ? code : message,
84
+ requestScoped,
85
+ retryAfterMs,
86
+ authish,
87
+ }
88
+ }
89
+
90
+ export function describeFailure(failure) {
91
+ const code = typeof failure?.code === 'string' ? failure.code : 'ERROR'
92
+ const message = typeof failure?.message === 'string' ? failure.message : ''
93
+ return `${code}${message === '' ? '' : `: ${message}`}`
94
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Reasoning-effort inheritance.
3
+ *
4
+ * The virtual model advertises the union of the efforts its chain can accept,
5
+ * so a caller asking for `max` keeps working even when one upstream only knows
6
+ * `high`. Each attempt then maps the requested effort onto what the target
7
+ * actually declares. `llm.resolveCallConfig` refuses an effort the *virtual*
8
+ * model does not advertise, so the union is what keeps the request alive; the
9
+ * per-target mapping is what keeps the upstream from rejecting it.
10
+ */
11
+
12
+ import { EFFORT_ORDER } from '../config.js'
13
+
14
+ const RANK = new Map(EFFORT_ORDER.map((id, index) => [id, index]))
15
+
16
+ export function sortEfforts(efforts) {
17
+ return [...efforts].sort((left, right) => {
18
+ const leftRank = RANK.get(left.id)
19
+ const rightRank = RANK.get(right.id)
20
+ if (leftRank !== undefined && rightRank !== undefined) return leftRank - rightRank
21
+ if (leftRank !== undefined) return -1
22
+ if (rightRank !== undefined) return 1
23
+ return 0
24
+ })
25
+ }
26
+
27
+ /**
28
+ * @param {Array<{efforts?: Array<{id: string, name?: string}>, defaultEffort?: string}>} infos
29
+ * @returns {{efforts: Array<{id: string, name: string}>, defaultEffort?: string} | undefined}
30
+ */
31
+ export function unionEfforts(infos) {
32
+ const byId = new Map()
33
+ let declared = false
34
+ let defaultEffort
35
+ for (const info of infos) {
36
+ if (info === undefined || info === null) continue
37
+ const efforts = info.efforts
38
+ if (!Array.isArray(efforts)) continue
39
+ declared = true
40
+ for (const effort of efforts) {
41
+ const id = typeof effort?.id === 'string' ? effort.id : undefined
42
+ if (id === undefined || id === '' || byId.has(id)) continue
43
+ byId.set(id, { id, name: typeof effort.name === 'string' && effort.name !== '' ? effort.name : id })
44
+ }
45
+ if (typeof info.defaultEffort === 'string' && byId.has(info.defaultEffort)) defaultEffort = info.defaultEffort
46
+ }
47
+ // An upstream that declares an empty list is not evidence of "no reasoning",
48
+ // and the host refuses an advertised model with zero efforts. Say nothing.
49
+ if (!declared || byId.size === 0) return undefined
50
+ return {
51
+ efforts: sortEfforts([...byId.values()]),
52
+ ...(defaultEffort === undefined ? {} : { defaultEffort }),
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Map one requested effort onto one target.
58
+ *
59
+ * @param {string | undefined} requested
60
+ * @param {{efforts?: Array<{id: string}>, defaultEffort?: string} | undefined} target
61
+ * @param {Record<string, string | null>} effortMap
62
+ * @param {{effortPolicy?: 'clamp' | 'drop' | 'fail'}} policy
63
+ * @returns {{effort?: string, coerced: boolean, reason: string, error?: Error}}
64
+ */
65
+ export function mapEffort(requested, target, effortMap = {}, policy = {}) {
66
+ if (requested === undefined || requested === null || requested === '') {
67
+ return { effort: undefined, coerced: false, reason: 'inherit-none' }
68
+ }
69
+ if (Object.prototype.hasOwnProperty.call(effortMap, requested)) {
70
+ const mapped = effortMap[requested]
71
+ if (mapped === null || mapped === '') {
72
+ return { effort: undefined, coerced: true, reason: `mapped-off:${requested}` }
73
+ }
74
+ return { effort: mapped, coerced: mapped !== requested, reason: `mapped:${requested}->${mapped}` }
75
+ }
76
+ const efforts = target?.efforts
77
+ if (target === null) {
78
+ // The adapter already reported this model with no reasoning metadata at
79
+ // all. The host refuses an explicit effort for such a model before the
80
+ // request leaves the process, so passing it through cannot work.
81
+ const mode = policy.effortPolicy ?? 'clamp'
82
+ if (mode === 'fail') {
83
+ return {
84
+ effort: undefined,
85
+ coerced: true,
86
+ reason: `unsupported:${requested}`,
87
+ error: Object.assign(new Error(`AutoRouter: the target declares no reasoning efforts`), {
88
+ code: 'UNSUPPORTED_REASONING_EFFORT',
89
+ }),
90
+ }
91
+ }
92
+ return { effort: undefined, coerced: true, reason: `no-reasoning:${requested}` }
93
+ }
94
+ if (!Array.isArray(efforts)) {
95
+ // No metadata could be read at all: an unknown upstream is not evidence
96
+ // that it rejects the parameter, so the request goes out as asked.
97
+ return { effort: requested, coerced: false, reason: 'target-unknown' }
98
+ }
99
+ if (efforts.length === 0) {
100
+ const mode = policy.effortPolicy ?? 'clamp'
101
+ if (mode === 'fail') {
102
+ return {
103
+ effort: undefined,
104
+ coerced: true,
105
+ reason: `unsupported:${requested}`,
106
+ error: Object.assign(new Error(`AutoRouter: the target declares no reasoning efforts`), {
107
+ code: 'UNSUPPORTED_REASONING_EFFORT',
108
+ }),
109
+ }
110
+ }
111
+ return { effort: undefined, coerced: true, reason: `no-reasoning:${requested}` }
112
+ }
113
+ if (efforts.some((effort) => effort?.id === requested)) {
114
+ return { effort: requested, coerced: false, reason: 'exact' }
115
+ }
116
+ const fallback = target?.defaultEffort
117
+ if (typeof fallback === 'string' && fallback !== '' && efforts.some((effort) => effort?.id === fallback)) {
118
+ if ((policy.effortPolicy ?? 'clamp') === 'fail') {
119
+ return {
120
+ effort: undefined,
121
+ coerced: true,
122
+ reason: `unsupported:${requested}`,
123
+ error: Object.assign(new Error(`AutoRouter: target does not support reasoning effort "${requested}"`), {
124
+ code: 'UNSUPPORTED_REASONING_EFFORT',
125
+ }),
126
+ }
127
+ }
128
+ return { effort: fallback, coerced: true, reason: `clamped:${requested}->${fallback}` }
129
+ }
130
+ const mode = policy.effortPolicy ?? 'clamp'
131
+ if (mode === 'fail') {
132
+ return {
133
+ effort: undefined,
134
+ coerced: true,
135
+ reason: `unsupported:${requested}`,
136
+ error: Object.assign(new Error(`AutoRouter: target does not support reasoning effort "${requested}"`), {
137
+ code: 'UNSUPPORTED_REASONING_EFFORT',
138
+ }),
139
+ }
140
+ }
141
+ return { effort: undefined, coerced: true, reason: `dropped:${requested}` }
142
+ }