@aliou/pi-neuralwatt 0.18.0 → 0.19.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +624 -0
  2. package/README.md +40 -51
  3. package/dist/provider/index.d.ts +28 -0
  4. package/dist/provider/index.js +1142 -0
  5. package/extensions/_shared/config/index.ts +1 -0
  6. package/{src → extensions/_shared}/config/loader.ts +11 -25
  7. package/{src → extensions/_shared}/config/migration/02-flat-to-nested-config.ts +1 -1
  8. package/extensions/command-quotas/command.ts +12 -3
  9. package/extensions/command-quotas/components/quota-tabs.ts +1 -1
  10. package/extensions/command-quotas/components/quotas-display.ts +2 -1
  11. package/extensions/command-quotas/index.ts +15 -5
  12. package/extensions/provider/commands/settings/api-base-url-editor.ts +2 -6
  13. package/extensions/provider/commands/settings/index.ts +31 -5
  14. package/extensions/provider/index.ts +50 -33
  15. package/extensions/provider/quota-store.ts +2 -1
  16. package/extensions/quota-warnings/index.ts +4 -1
  17. package/extensions/shared/truncate.ts +292 -0
  18. package/package.json +27 -17
  19. package/schema.json +14 -0
  20. package/{extensions/provider → src}/api/anthropic-messages.ts +22 -8
  21. package/{extensions/provider → src}/api/openai-completions.ts +38 -7
  22. package/{extensions/provider → src}/api/system-one.ts +5 -3
  23. package/src/config/index.ts +1 -2
  24. package/src/config/resolve.ts +25 -0
  25. package/src/config/types.ts +11 -0
  26. package/{extensions/provider → src}/constants.ts +1 -0
  27. package/src/lib/neuralwatt-api.ts +15 -7
  28. package/{extensions/provider → src}/models/build.ts +10 -10
  29. package/{extensions/provider → src}/models/catalog.ts +1 -1
  30. package/{extensions/provider → src}/models/public-models.ts +0 -44
  31. package/{extensions/provider → src}/models/refresh.ts +16 -9
  32. package/{extensions/provider → src}/provider.ts +81 -46
  33. package/{extensions/provider → src}/sse-quotas.ts +5 -4
  34. package/{extensions/provider → src}/stream-simple.ts +3 -3
  35. /package/{src → extensions/_shared}/config/migration/03-rename-hidden-to-early-access.ts +0 -0
  36. /package/{src → extensions/_shared}/config/migration/04-remove-sub-bar-integration.ts +0 -0
  37. /package/{src → extensions/_shared}/config/migration/index.ts +0 -0
  38. /package/{extensions/provider → src}/api/types.ts +0 -0
  39. /package/{extensions/provider → src}/models/index.ts +0 -0
  40. /package/{extensions/provider → src}/rate-limit-error.ts +0 -0
@@ -0,0 +1,1142 @@
1
+ import { anthropicMessagesApi } from "@earendil-works/pi-ai/api/anthropic-messages.lazy";
2
+ import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
3
+ import { createProvider } from "@earendil-works/pi-ai/models";
4
+ import { calculateCost } from "@earendil-works/pi-ai";
5
+ import { Type } from "typebox";
6
+ import { Check, Parse, ParseError } from "typebox/value";
7
+ // src/constants.ts
8
+ const NEURALWATT_PROVIDER_ID = "neuralwatt";
9
+ const NEURALWATT_BASE_URL = "https://api.neuralwatt.com/v1";
10
+ const NEURALWATT_API_KEY_ENV = "NEURALWATT_API_KEY";
11
+ const NEURALWATT_REQUEST_HEADERS = {
12
+ Referer: "https://pi.dev",
13
+ "X-Title": "npm:@aliou/pi-neuralwatt"
14
+ };
15
+ const NEURALWATT_TOOLS_OPT_OUT_HEADER = "X-NW-Tools-Opt-Out";
16
+ // src/models/build.ts
17
+ const NEURALWATT_SYSTEM_ONE_API = "typesafe-system-one";
18
+ /**
19
+ * Build the Pi thinking level map from the Neuralwatt reasoning contract.
20
+ *
21
+ * Pure identity mapping: a Pi level is enabled iff it appears in
22
+ * `supported_efforts` (mapped to its own name), `null` otherwise. `off` maps to
23
+ * `"none"` when the model permits disabling reasoning (`!mandatory` and
24
+ * `"none"` is supported).
25
+ *
26
+ * When the reasoning block is missing (e.g. Kimi K2.7 Code, whose API metadata
27
+ * exposes none), falls back to a conservative `high`-only map with `off: null`,
28
+ * matching the upstream binary thinking toggle.
29
+ *
30
+ * `effort_aliases` is deliberately ignored here (the openai-completions
31
+ * gateway aliases unsupported efforts server-side); it is consumed by the
32
+ * anthropic-messages map below.
33
+ */
34
+ function buildThinkingLevelMap(reasoning) {
35
+ const supported = new Set(reasoning?.supported_efforts ?? ["high"]);
36
+ return {
37
+ off: !(reasoning?.mandatory ?? true) && supported.has("none") ? "none" : null,
38
+ minimal: supported.has("minimal") ? "minimal" : null,
39
+ low: supported.has("low") ? "low" : null,
40
+ medium: supported.has("medium") ? "medium" : null,
41
+ high: supported.has("high") ? "high" : null,
42
+ xhigh: supported.has("xhigh") ? "xhigh" : null,
43
+ max: supported.has("max") ? "max" : null
44
+ };
45
+ }
46
+ /**
47
+ * Thinking level map for the anthropic-messages surface. vLLM's
48
+ * `output_config.effort` accepts only the model's native efforts, so
49
+ * unsupported Pi levels resolve through `effort_aliases` (or `null`). A level
50
+ * may resolve to `"none"` — off on this surface, handled by the payload
51
+ * injector in `api/anthropic-messages.ts`.
52
+ */
53
+ function buildAnthropicThinkingLevelMap(reasoning) {
54
+ const supported = new Set(reasoning?.supported_efforts ?? ["high"]);
55
+ const mandatory = reasoning?.mandatory ?? true;
56
+ const aliases = reasoning?.effort_aliases ?? {};
57
+ const resolve = (level) => {
58
+ if (supported.has(level)) return level;
59
+ const alias = aliases[level];
60
+ return alias && supported.has(alias) ? alias : null;
61
+ };
62
+ return {
63
+ off: !mandatory && supported.has("none") ? "none" : null,
64
+ minimal: resolve("minimal"),
65
+ low: resolve("low"),
66
+ medium: resolve("medium"),
67
+ high: resolve("high"),
68
+ xhigh: resolve("xhigh"),
69
+ max: resolve("max")
70
+ };
71
+ }
72
+ /**
73
+ * Neuralwatt reports `max_output_tokens: null` for models whose output is only
74
+ * bounded by the context window. Some models incorrectly report 0; treat 0
75
+ * like null so we never emit maxTokens: 0.
76
+ */
77
+ function resolveMaxTokens(maxOutputTokens, contextWindow) {
78
+ if (maxOutputTokens === 0) return contextWindow;
79
+ return maxOutputTokens ?? contextWindow;
80
+ }
81
+ function buildNeuralwattModel(family, variant) {
82
+ const vision = variant.vision ?? family.vision;
83
+ const compat = {
84
+ supportsDeveloperRole: false,
85
+ maxTokensField: "max_tokens"
86
+ };
87
+ const multiplier = variant.costMultiplier ?? 1;
88
+ const scale = (value) => multiplier === 1 ? value : Number((value * multiplier).toFixed(6));
89
+ const model = {
90
+ id: variant.id,
91
+ name: variant.name,
92
+ reasoning: variant.reasoning,
93
+ input: vision ? ["text", "image"] : ["text"],
94
+ cost: {
95
+ input: scale(variant.cost?.input ?? family.cost.input),
96
+ output: scale(variant.cost?.output ?? family.cost.output),
97
+ cacheRead: scale(variant.cost?.cacheRead ?? family.cost.cacheRead),
98
+ cacheWrite: 0
99
+ },
100
+ contextWindow: variant.contextWindow,
101
+ maxTokens: resolveMaxTokens(variant.maxOutputTokens, variant.contextWindow),
102
+ compat
103
+ };
104
+ if (variant.reasoning) {
105
+ const contract = variant.reasoningMetadata ?? family.reasoningMetadata;
106
+ model.thinkingLevelMap = { ...buildThinkingLevelMap(contract) };
107
+ model.reasoningContract = contract;
108
+ }
109
+ return model;
110
+ }
111
+ function buildNeuralwattFamily(family, variants) {
112
+ return variants.map((variant) => buildNeuralwattModel(family, variant));
113
+ }
114
+ // src/api/system-one.ts
115
+ const UsageSchema = Type.Object({
116
+ input_tokens: Type.Integer({ minimum: 0 }),
117
+ output_tokens: Type.Integer({ minimum: 0 })
118
+ });
119
+ const AnswerSchemas = {
120
+ choice: Type.Object({
121
+ type: Type.Literal("choice"),
122
+ choice: Type.String(),
123
+ probabilities: Type.Record(Type.String(), Type.Number()),
124
+ confidence: Type.Number()
125
+ }),
126
+ score: Type.Object({
127
+ type: Type.Literal("score"),
128
+ score: Type.Number(),
129
+ confidence: Type.Number()
130
+ }),
131
+ bool: Type.Object({
132
+ type: Type.Literal("noul"),
133
+ noul: Type.Number()
134
+ })
135
+ };
136
+ const ErrorSchema = Type.Union([Type.Object({ error: Type.Object({
137
+ message: Type.String(),
138
+ type: Type.String(),
139
+ code: Type.String()
140
+ }) }), Type.Object({ detail: Type.String() })]);
141
+ function responseSchema(context) {
142
+ return Type.Object({
143
+ answers: Type.Object(Object.fromEntries(Object.entries(context.questions).map(([id, question]) => [id, AnswerSchemas[question.type]]))),
144
+ usage: Type.Optional(UsageSchema)
145
+ });
146
+ }
147
+ function mapAnswer(value) {
148
+ if (value.type === "noul") return {
149
+ type: "bool",
150
+ probability: value.noul
151
+ };
152
+ if (value.type === "score") return {
153
+ type: "score",
154
+ score: value.score,
155
+ confidence: value.confidence
156
+ };
157
+ return {
158
+ type: "choice",
159
+ choice: value.choice,
160
+ probabilities: value.probabilities,
161
+ confidence: value.confidence
162
+ };
163
+ }
164
+ function mapUsage(model, value) {
165
+ if (!value) return void 0;
166
+ const { input_tokens: input, output_tokens: output } = value;
167
+ const usage = {
168
+ input,
169
+ output,
170
+ cacheRead: 0,
171
+ cacheWrite: 0,
172
+ totalTokens: input + output,
173
+ cost: {
174
+ input: 0,
175
+ output: 0,
176
+ cacheRead: 0,
177
+ cacheWrite: 0,
178
+ total: 0
179
+ }
180
+ };
181
+ calculateCost(model, usage);
182
+ return usage;
183
+ }
184
+ function billedUsageOnInvalidResponse(model, error) {
185
+ const usage = error.cause.value?.usage;
186
+ return Check(UsageSchema, usage) ? mapUsage(model, usage) : void 0;
187
+ }
188
+ function formatRequest(model, context) {
189
+ return {
190
+ model: model.id,
191
+ state: context.state,
192
+ questions: Object.fromEntries(Object.entries(context.questions).map(([id, question]) => [id, question.type === "bool" ? {
193
+ ...question,
194
+ type: "noul"
195
+ } : question]))
196
+ };
197
+ }
198
+ function requestHeaders(model, options) {
199
+ const headers = new Headers({
200
+ authorization: `Bearer ${options.apiKey || "-"}`,
201
+ "content-type": "application/json"
202
+ });
203
+ const overrides = [model.headers, options.headers].flatMap((source) => Object.entries(source ?? {}));
204
+ for (const [name, value] of overrides) if (value === null) headers.delete(name);
205
+ else headers.set(name, value);
206
+ return Object.fromEntries(headers);
207
+ }
208
+ function requestSignal({ signal, timeoutMs }) {
209
+ if (timeoutMs === void 0) return signal;
210
+ const timeout = AbortSignal.timeout(timeoutMs);
211
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
212
+ }
213
+ async function request(model, context, options) {
214
+ if (model.api !== "typesafe-system-one") throw new Error(`Unsupported classifier API: ${model.api}`);
215
+ if (context.images?.length) throw new Error("Neuralwatt classifier does not support image input");
216
+ options.signal?.throwIfAborted();
217
+ const rawPayload = formatRequest(model, context);
218
+ const payload = await options.onPayload?.(rawPayload, model) ?? rawPayload;
219
+ const url = new URL("systemone", `${model.baseUrl.replace(/\/+$/u, "")}/`);
220
+ const response = await (options.fetch ?? globalThis.fetch)(url, {
221
+ method: "POST",
222
+ headers: requestHeaders(model, options),
223
+ body: JSON.stringify(payload),
224
+ signal: requestSignal(options)
225
+ });
226
+ await options.onResponse?.({
227
+ status: response.status,
228
+ headers: Object.fromEntries(response.headers)
229
+ }, model);
230
+ const body = await response.json();
231
+ if (!response.ok) {
232
+ const failure = Parse(ErrorSchema, body);
233
+ const message = "error" in failure ? failure.error.message : failure.detail;
234
+ throw new Error(`Neuralwatt System One API returned ${response.status}: ${message}`);
235
+ }
236
+ return Parse(responseSchema(context), body);
237
+ }
238
+ const classify = async (model, context, options = {}) => {
239
+ const result = {
240
+ api: model.api,
241
+ provider: model.provider,
242
+ model: model.id,
243
+ answers: {},
244
+ stopReason: "stop",
245
+ timestamp: Date.now()
246
+ };
247
+ try {
248
+ const body = await request(model, context, options);
249
+ result.usage = mapUsage(model, body.usage);
250
+ result.answers = Object.fromEntries(Object.keys(context.questions).map((id) => [id, mapAnswer(body.answers[id])]));
251
+ } catch (error) {
252
+ result.stopReason = options.signal?.aborted ? "aborted" : "error";
253
+ if (error instanceof ParseError) {
254
+ result.usage = billedUsageOnInvalidResponse(model, error);
255
+ result.errorMessage = error.cause.errors.map(({ instancePath, message }) => `${instancePath}: ${message}`).join("; ");
256
+ return result;
257
+ }
258
+ result.errorMessage = error instanceof Error ? error.message : String(error);
259
+ }
260
+ return result;
261
+ };
262
+ function stampClassifierModels(models, baseUrl = NEURALWATT_BASE_URL) {
263
+ return models.map((model) => ({
264
+ ...model,
265
+ api: NEURALWATT_SYSTEM_ONE_API,
266
+ provider: NEURALWATT_PROVIDER_ID,
267
+ baseUrl: model.baseUrl ?? baseUrl,
268
+ headers: NEURALWATT_REQUEST_HEADERS
269
+ }));
270
+ }
271
+ const DEFAULT_CONFIG = {
272
+ quotaCommand: { enabled: true },
273
+ quotaWarnings: { enabled: true },
274
+ provider: {
275
+ api: "openai-completions",
276
+ apiBaseUrl: "https://api.neuralwatt.com/v1"
277
+ }
278
+ };
279
+ // src/config/resolve.ts
280
+ function resolveApiBaseUrl(value) {
281
+ const trimmed = value?.trim().replace(/\/+$/u, "");
282
+ if (!trimmed) return DEFAULT_CONFIG.provider.apiBaseUrl;
283
+ try {
284
+ const url = new URL(trimmed);
285
+ if (url.protocol !== "https:" && url.protocol !== "http:") return DEFAULT_CONFIG.provider.apiBaseUrl;
286
+ } catch {
287
+ return DEFAULT_CONFIG.provider.apiBaseUrl;
288
+ }
289
+ return trimmed;
290
+ }
291
+ // src/lib/neuralwatt-api.ts
292
+ const FETCH_TIMEOUT_MS = 15e3;
293
+ function authHeaders(apiKey) {
294
+ return apiKey && apiKey !== "-" ? { Authorization: `Bearer ${apiKey}` } : {};
295
+ }
296
+ function combineSignals(signal) {
297
+ const signals = [AbortSignal.timeout(FETCH_TIMEOUT_MS)];
298
+ if (signal) signals.push(signal);
299
+ return AbortSignal.any(signals);
300
+ }
301
+ async function neuralwattFetch(path, baseUrl, apiKey, signal, headers) {
302
+ return fetch(`${baseUrl}${path}`, {
303
+ headers: {
304
+ ...authHeaders(apiKey),
305
+ ...headers
306
+ },
307
+ signal: combineSignals(signal)
308
+ });
309
+ }
310
+ async function fetchNeuralwattModels(apiKey, baseUrl, signal) {
311
+ const combined = combineSignals(signal);
312
+ try {
313
+ const response = await neuralwattFetch("/models", baseUrl, apiKey, combined, {
314
+ Referer: "https://pi.dev",
315
+ "X-Title": "npm:@aliou/pi-neuralwatt"
316
+ });
317
+ if (!response.ok) return { success: false };
318
+ return {
319
+ success: true,
320
+ data: (await response.json()).data
321
+ };
322
+ } catch {
323
+ return { success: false };
324
+ }
325
+ }
326
+ const NEURALWATT_MODELS = [
327
+ [{
328
+ cost: {
329
+ input: .15,
330
+ output: .6,
331
+ cacheRead: .015
332
+ },
333
+ vision: true,
334
+ reasoningMetadata: {
335
+ supported_efforts: [
336
+ "max",
337
+ "xhigh",
338
+ "high",
339
+ "low",
340
+ "none"
341
+ ],
342
+ mandatory: false,
343
+ effort_aliases: {
344
+ medium: "high",
345
+ minimal: "low"
346
+ }
347
+ }
348
+ }, [
349
+ {
350
+ id: "deepseek-v4.1-flash",
351
+ name: "DeepSeek V4.1 Flash",
352
+ contextWindow: 1048560,
353
+ maxOutputTokens: 393216,
354
+ reasoning: true
355
+ },
356
+ {
357
+ id: "deepseek-v4.1-flash-flex",
358
+ name: "DeepSeek V4.1 Flash (flex)",
359
+ contextWindow: 1048560,
360
+ maxOutputTokens: 393216,
361
+ reasoning: true,
362
+ costMultiplier: .65
363
+ },
364
+ {
365
+ id: "deepseek-v4.1-flash-speed",
366
+ name: "DeepSeek V4.1 Flash (Speed)",
367
+ contextWindow: 1048560,
368
+ maxOutputTokens: 393216,
369
+ reasoning: true
370
+ }
371
+ ]],
372
+ [{
373
+ cost: {
374
+ input: .144,
375
+ output: .42,
376
+ cacheRead: .0144
377
+ },
378
+ vision: true,
379
+ reasoningMetadata: {
380
+ supported_efforts: ["max", "none"],
381
+ mandatory: false,
382
+ effort_aliases: {
383
+ xhigh: "max",
384
+ high: "max",
385
+ medium: "max",
386
+ low: "max",
387
+ minimal: "max"
388
+ }
389
+ }
390
+ }, [{
391
+ id: "gemma-4-31b",
392
+ name: "Gemma 4 31B",
393
+ contextWindow: 262128,
394
+ maxOutputTokens: 16384,
395
+ reasoning: true
396
+ }]],
397
+ [{
398
+ cost: {
399
+ input: 1.45,
400
+ output: 4.5,
401
+ cacheRead: .145
402
+ },
403
+ vision: false,
404
+ reasoningMetadata: {
405
+ supported_efforts: [
406
+ "max",
407
+ "high",
408
+ "low"
409
+ ],
410
+ mandatory: true,
411
+ effort_aliases: {
412
+ xhigh: "max",
413
+ medium: "high",
414
+ minimal: "low"
415
+ }
416
+ }
417
+ }, [{
418
+ id: "glm-5.3",
419
+ name: "GLM 5.3",
420
+ contextWindow: 1048560,
421
+ maxOutputTokens: null,
422
+ reasoning: true
423
+ }, {
424
+ id: "glm-5.3-flex",
425
+ name: "GLM 5.3 (flex)",
426
+ contextWindow: 1048560,
427
+ maxOutputTokens: null,
428
+ reasoning: true,
429
+ costMultiplier: .65
430
+ }]],
431
+ [{
432
+ cost: {
433
+ input: .15,
434
+ output: .5,
435
+ cacheRead: .03
436
+ },
437
+ vision: true,
438
+ reasoningMetadata: {
439
+ supported_efforts: [
440
+ "max",
441
+ "high",
442
+ "low"
443
+ ],
444
+ mandatory: true,
445
+ effort_aliases: {
446
+ xhigh: "max",
447
+ medium: "high",
448
+ minimal: "low"
449
+ }
450
+ }
451
+ }, [{
452
+ id: "glm-5.3-flash",
453
+ name: "GLM-5.3 Flash",
454
+ contextWindow: 1048560,
455
+ maxOutputTokens: null,
456
+ reasoning: true
457
+ }, {
458
+ id: "glm-5.3-flash-flex",
459
+ name: "GLM-5.3 Flash (flex)",
460
+ contextWindow: 1048560,
461
+ maxOutputTokens: null,
462
+ reasoning: true,
463
+ costMultiplier: .65
464
+ }]],
465
+ [{
466
+ cost: {
467
+ input: 3,
468
+ output: 15,
469
+ cacheRead: .3
470
+ },
471
+ vision: true,
472
+ reasoningMetadata: {
473
+ supported_efforts: [
474
+ "max",
475
+ "high",
476
+ "low",
477
+ "none"
478
+ ],
479
+ mandatory: false,
480
+ effort_aliases: {
481
+ xhigh: "max",
482
+ medium: "high",
483
+ minimal: "low"
484
+ }
485
+ }
486
+ }, [
487
+ {
488
+ id: "kimi-k3",
489
+ name: "Kimi K3",
490
+ contextWindow: 1048560,
491
+ maxOutputTokens: null,
492
+ reasoning: true
493
+ },
494
+ {
495
+ id: "kimi-k3-fast",
496
+ name: "Kimi K3 Fast",
497
+ contextWindow: 1048560,
498
+ maxOutputTokens: null,
499
+ reasoning: false
500
+ },
501
+ {
502
+ id: "kimi-k3-flex",
503
+ name: "Kimi K3 (flex)",
504
+ contextWindow: 1048560,
505
+ maxOutputTokens: null,
506
+ reasoning: true,
507
+ costMultiplier: .65
508
+ }
509
+ ]],
510
+ [{
511
+ cost: {
512
+ input: .87,
513
+ output: 1.74,
514
+ cacheRead: .036
515
+ },
516
+ vision: true,
517
+ reasoningMetadata: {
518
+ supported_efforts: ["high", "none"],
519
+ mandatory: false,
520
+ effort_aliases: {
521
+ max: "high",
522
+ xhigh: "high",
523
+ medium: "high",
524
+ low: "high",
525
+ minimal: "none"
526
+ }
527
+ }
528
+ }, [{
529
+ id: "mimo-v2.6-pro",
530
+ name: "MiMo-V2.6-Pro",
531
+ contextWindow: 1048560,
532
+ maxOutputTokens: 393216,
533
+ reasoning: true
534
+ }, {
535
+ id: "mimo-v2.6-pro-flex",
536
+ name: "MiMo-V2.6-Pro (flex)",
537
+ contextWindow: 1048560,
538
+ maxOutputTokens: 393216,
539
+ reasoning: true,
540
+ costMultiplier: .65
541
+ }]],
542
+ [{
543
+ cost: {
544
+ input: 3,
545
+ output: 15,
546
+ cacheRead: .3
547
+ },
548
+ vision: true,
549
+ reasoningMetadata: {
550
+ supported_efforts: [
551
+ "max",
552
+ "high",
553
+ "low",
554
+ "none"
555
+ ],
556
+ mandatory: false,
557
+ effort_aliases: {
558
+ xhigh: "max",
559
+ medium: "high",
560
+ minimal: "low"
561
+ }
562
+ }
563
+ }, [{
564
+ id: "nw-large",
565
+ name: "Neuralwatt Large",
566
+ contextWindow: 1048560,
567
+ maxOutputTokens: null,
568
+ reasoning: true
569
+ }, {
570
+ id: "nw-large-flex",
571
+ name: "Neuralwatt Large (flex)",
572
+ contextWindow: 1048560,
573
+ maxOutputTokens: null,
574
+ reasoning: true,
575
+ costMultiplier: .65
576
+ }]],
577
+ [{
578
+ cost: {
579
+ input: .15,
580
+ output: .6,
581
+ cacheRead: .015
582
+ },
583
+ vision: true,
584
+ reasoningMetadata: {
585
+ supported_efforts: [
586
+ "max",
587
+ "xhigh",
588
+ "high",
589
+ "low",
590
+ "none"
591
+ ],
592
+ mandatory: false,
593
+ effort_aliases: {
594
+ medium: "high",
595
+ minimal: "low"
596
+ }
597
+ }
598
+ }, [{
599
+ id: "nw-flash",
600
+ name: "Neuralwatt Flash",
601
+ contextWindow: 1048560,
602
+ maxOutputTokens: 393216,
603
+ reasoning: true
604
+ }, {
605
+ id: "nw-flash-flex",
606
+ name: "Neuralwatt Flash (flex)",
607
+ contextWindow: 1048560,
608
+ maxOutputTokens: 393216,
609
+ reasoning: true,
610
+ costMultiplier: .65
611
+ }]],
612
+ [{
613
+ cost: {
614
+ input: .45,
615
+ output: 3.2,
616
+ cacheRead: .25
617
+ },
618
+ vision: true,
619
+ reasoningMetadata: {
620
+ supported_efforts: [
621
+ "xhigh",
622
+ "medium",
623
+ "low",
624
+ "none"
625
+ ],
626
+ mandatory: false,
627
+ effort_aliases: {
628
+ max: "xhigh",
629
+ high: "xhigh",
630
+ minimal: "low"
631
+ }
632
+ }
633
+ }, [{
634
+ id: "nw-small",
635
+ name: "Neuralwatt Small",
636
+ contextWindow: 262128,
637
+ maxOutputTokens: 131072,
638
+ reasoning: true
639
+ }, {
640
+ id: "nw-small-flex",
641
+ name: "Neuralwatt Small (flex)",
642
+ contextWindow: 262128,
643
+ maxOutputTokens: 131072,
644
+ reasoning: true,
645
+ costMultiplier: .65
646
+ }]],
647
+ [{
648
+ cost: {
649
+ input: .29,
650
+ output: 1.15,
651
+ cacheRead: .029
652
+ },
653
+ vision: true,
654
+ reasoningMetadata: {
655
+ supported_efforts: ["high", "none"],
656
+ mandatory: false,
657
+ effort_aliases: {
658
+ max: "high",
659
+ xhigh: "high",
660
+ medium: "high",
661
+ low: "high",
662
+ minimal: "high"
663
+ }
664
+ }
665
+ }, [
666
+ {
667
+ id: "qwen3.6-35b",
668
+ name: "Qwen3.6 35B",
669
+ contextWindow: 262128,
670
+ maxOutputTokens: null,
671
+ reasoning: true
672
+ },
673
+ {
674
+ id: "qwen3.6-35b-fast",
675
+ name: "Qwen3.6 35B Fast",
676
+ contextWindow: 262128,
677
+ maxOutputTokens: null,
678
+ reasoning: false
679
+ },
680
+ {
681
+ id: "qwen3.6-35b-flex",
682
+ name: "Qwen3.6 35B (flex)",
683
+ contextWindow: 262128,
684
+ maxOutputTokens: null,
685
+ reasoning: true,
686
+ costMultiplier: .65
687
+ }
688
+ ]],
689
+ [{
690
+ cost: {
691
+ input: .45,
692
+ output: 3.2,
693
+ cacheRead: .25
694
+ },
695
+ vision: true,
696
+ reasoningMetadata: {
697
+ supported_efforts: [
698
+ "xhigh",
699
+ "medium",
700
+ "low",
701
+ "none"
702
+ ],
703
+ mandatory: false,
704
+ effort_aliases: {
705
+ max: "xhigh",
706
+ high: "xhigh",
707
+ minimal: "low"
708
+ }
709
+ }
710
+ }, [{
711
+ id: "qwen-3.8-27b",
712
+ name: "Qwen 3.8 27B",
713
+ contextWindow: 262128,
714
+ maxOutputTokens: 131072,
715
+ reasoning: true
716
+ }, {
717
+ id: "qwen-3.8-27b-flex",
718
+ name: "Qwen 3.8 27B (flex)",
719
+ contextWindow: 262128,
720
+ maxOutputTokens: 131072,
721
+ reasoning: true,
722
+ costMultiplier: .65
723
+ }]]
724
+ ].flatMap(([family, variants]) => buildNeuralwattFamily(family, variants));
725
+ // src/models/catalog.ts
726
+ function isNeuralwattClassifierModel(model) {
727
+ return model.type === "classifier";
728
+ }
729
+ function partitionNeuralwattModels(models) {
730
+ const chat = [];
731
+ const classifiers = [];
732
+ for (const model of models) if (isNeuralwattClassifierModel(model)) classifiers.push(model);
733
+ else chat.push(model);
734
+ return {
735
+ chat,
736
+ classifiers
737
+ };
738
+ }
739
+ const COMPAT_OVERRIDES = { "Qwen/Qwen3.8-27B-FP8": {
740
+ thinkingFormat: "chat-template",
741
+ chatTemplateKwargs: { enable_thinking: { $var: "thinking.enabled" } }
742
+ } };
743
+ function apiModelToClassifierModel(model) {
744
+ const meta = model.metadata;
745
+ if (!meta) throw new Error(`Neuralwatt API returned model "${model.id}" without metadata`);
746
+ return {
747
+ type: "classifier",
748
+ api: NEURALWATT_SYSTEM_ONE_API,
749
+ id: model.id,
750
+ name: meta.display_name ?? model.id,
751
+ input: meta.capabilities.vision ? ["text", "image"] : ["text"],
752
+ cost: {
753
+ input: meta.pricing.input_per_million,
754
+ output: meta.pricing.output_per_million,
755
+ cacheRead: meta.pricing.cached_input_per_million ?? 0,
756
+ cacheWrite: meta.pricing.cached_output_per_million ?? 0
757
+ },
758
+ contextWindow: model.max_model_len
759
+ };
760
+ }
761
+ function apiModelToProviderModel(model) {
762
+ const meta = model.metadata;
763
+ if (!meta) throw new Error(`Neuralwatt API returned model "${model.id}" without metadata`);
764
+ const reasoning = meta.capabilities.reasoning;
765
+ const compat = {
766
+ supportsDeveloperRole: meta.capabilities.developer_role,
767
+ maxTokensField: "max_tokens",
768
+ ...COMPAT_OVERRIDES[model.id]
769
+ };
770
+ const contextWindow = model.max_model_len;
771
+ const result = {
772
+ id: model.id,
773
+ name: meta.display_name ?? model.id,
774
+ reasoning,
775
+ input: meta.capabilities.vision ? ["text", "image"] : ["text"],
776
+ cost: {
777
+ input: meta.pricing.input_per_million,
778
+ output: meta.pricing.output_per_million,
779
+ cacheRead: meta.pricing.cached_input_per_million ?? 0,
780
+ cacheWrite: meta.pricing.cached_output_per_million ?? 0
781
+ },
782
+ contextWindow,
783
+ maxTokens: resolveMaxTokens(meta.limits.max_output_tokens, contextWindow),
784
+ compat
785
+ };
786
+ if (reasoning) {
787
+ result.thinkingLevelMap = buildThinkingLevelMap(meta.reasoning);
788
+ result.reasoningContract = meta.reasoning;
789
+ }
790
+ return result;
791
+ }
792
+ function buildNeuralwattProviderModels() {
793
+ return NEURALWATT_MODELS.map((model) => ({ ...model }));
794
+ }
795
+ function buildNeuralwattProviderModelsFromApi(apiModels) {
796
+ return apiModels.filter((m) => m.metadata && !m.metadata.deprecated && !m.metadata.pricing.pricing_tbd && !(m.metadata.capabilities.task && ![
797
+ "chat",
798
+ "completions",
799
+ "decision"
800
+ ].includes(m.metadata.capabilities.task))).map((m) => m.metadata?.capabilities.task === "decision" ? apiModelToClassifierModel(m) : apiModelToProviderModel(m));
801
+ }
802
+ function buildNeuralwattProviderModelsFromStore(storedModels) {
803
+ return storedModels.map((model) => ({ ...model }));
804
+ }
805
+ // src/models/refresh.ts
806
+ const MODEL_STORE_TTL_MS = 144e5;
807
+ /**
808
+ * Scope a store entry applies to. The public catalog is a subset of any
809
+ * key-scoped catalog (preview, grant-gated, private models), so an entry
810
+ * stamped "public" must not shadow a keyed refresh — and a key-scoped entry
811
+ * must not be replayed for an anonymous user. Matches the anonymous-key
812
+ * convention in src/lib/neuralwatt-api.ts (authHeaders). The base URL is part
813
+ * of the key because a gateway can serve a different catalog than upstream.
814
+ */
815
+ const CATALOG_SCOPE_VERSION = "v2";
816
+ function catalogScope(apiKey) {
817
+ return apiKey !== void 0 && apiKey !== "" && apiKey !== "-" ? "key" : "public";
818
+ }
819
+ function catalogKey(scope, baseUrl) {
820
+ return `${scope} ${CATALOG_SCOPE_VERSION} ${baseUrl}`;
821
+ }
822
+ function catalogKeyMatches(entry, scope, baseUrl) {
823
+ return entry !== void 0 && entry.catalogKey === catalogKey(scope, baseUrl);
824
+ }
825
+ function asStoredChatModels(models) {
826
+ return models;
827
+ }
828
+ function isFreshStoreEntry(entry) {
829
+ if (!entry) return false;
830
+ const checkedAt = entry.checkedAt ?? Date.now();
831
+ return Date.now() - checkedAt < MODEL_STORE_TTL_MS;
832
+ }
833
+ function isUsableStoreEntry(entry, scope, baseUrl) {
834
+ return isFreshStoreEntry(entry) && catalogKeyMatches(entry, scope, baseUrl);
835
+ }
836
+ function createNeuralwattRefreshModels(staticModels, fetchApiModels, buildFromApi, buildFromStore, baseUrl) {
837
+ return async (context) => {
838
+ context.signal.throwIfAborted();
839
+ const resolvedBaseUrl = typeof baseUrl === "function" ? baseUrl() : baseUrl;
840
+ const fallback = buildFromStore(staticModels);
841
+ try {
842
+ const apiKey = context.credential?.type === "api_key" ? context.credential.key : void 0;
843
+ const scope = catalogScope(apiKey);
844
+ const stored = context.stored;
845
+ if (!context.allowNetwork) return stored !== void 0 && catalogKeyMatches(stored, scope, resolvedBaseUrl) ? buildFromStore(asStoredChatModels(stored.models)) : fallback;
846
+ if (!context.force && isUsableStoreEntry(stored, scope, resolvedBaseUrl)) return buildFromStore(asStoredChatModels(stored.models));
847
+ const apiModels = await fetchApiModels(apiKey, context.signal);
848
+ context.signal.throwIfAborted();
849
+ const models = buildFromApi(apiModels);
850
+ const entry = {
851
+ models,
852
+ checkedAt: Date.now(),
853
+ catalogKey: catalogKey(scope, resolvedBaseUrl)
854
+ };
855
+ await context.publish({ persist: entry }).catch(() => void 0);
856
+ context.signal.throwIfAborted();
857
+ return models;
858
+ } catch (error) {
859
+ if (context.signal.aborted || error instanceof Error && error.name === "AbortError") throw error;
860
+ return fallback;
861
+ }
862
+ };
863
+ }
864
+ // src/api/anthropic-messages.ts
865
+ const EFFORT_OFF_VALUES = /* @__PURE__ */ new Set(["none", "minimal"]);
866
+ function applyReasoningOff(body) {
867
+ delete body.thinking;
868
+ delete body.output_config;
869
+ body.chat_template_kwargs = {
870
+ ...body.chat_template_kwargs ?? {},
871
+ enable_thinking: false
872
+ };
873
+ return body;
874
+ }
875
+ /**
876
+ * vLLM's reasoning controls differ from first-party Anthropic: positive levels
877
+ * go through `output_config.effort` (adaptive path, forced via compat) while
878
+ * `thinking:{type:"disabled"}` is accepted but ignored, so off is expressed
879
+ * through the chat-template kwarg instead.
880
+ */
881
+ function makeReasoningInjector(upstream) {
882
+ return async (payload, model) => {
883
+ const next = await upstream?.(payload, model);
884
+ const body = next !== void 0 ? next : payload;
885
+ if (body.thinking?.type === "disabled") return applyReasoningOff(body);
886
+ const effort = body.output_config?.effort;
887
+ if (effort && EFFORT_OFF_VALUES.has(effort)) return applyReasoningOff(body);
888
+ return body;
889
+ };
890
+ }
891
+ function toMessagesBaseUrl(baseUrl) {
892
+ return baseUrl.replace(/\/v1\/?$/, "");
893
+ }
894
+ function stampAnthropicModels(models, baseUrl) {
895
+ return models.map((model) => {
896
+ const { reasoningContract, ...compiled } = model;
897
+ const thinkingLevelMap = model.reasoning ? reasoningContract ? buildAnthropicThinkingLevelMap(reasoningContract) : model.thinkingLevelMap ? { ...model.thinkingLevelMap } : void 0 : void 0;
898
+ return {
899
+ ...compiled,
900
+ api: "anthropic-messages",
901
+ provider: NEURALWATT_PROVIDER_ID,
902
+ baseUrl: toMessagesBaseUrl(model.baseUrl ?? baseUrl),
903
+ headers: NEURALWATT_REQUEST_HEADERS,
904
+ compat: {
905
+ forceAdaptiveThinking: true,
906
+ supportsTemperature: true,
907
+ supportsStrictTools: false,
908
+ supportsCacheControlOnTools: false
909
+ },
910
+ ...thinkingLevelMap ? { thinkingLevelMap } : {}
911
+ };
912
+ });
913
+ }
914
+ function createAnthropicMessagesApi(options) {
915
+ const requireUpstream = () => {
916
+ if (!options?.upstream) throw new Error("createAnthropicMessagesApi requires an upstream: pass pi-ai's anthropicMessagesApi() streams");
917
+ return options.upstream;
918
+ };
919
+ const fallbackBaseUrl = options?.baseUrl ?? "https://api.neuralwatt.com/v1";
920
+ const withReasoning = (options) => ({
921
+ ...options,
922
+ onPayload: makeReasoningInjector(options?.onPayload)
923
+ });
924
+ return {
925
+ stampModels: (models) => stampAnthropicModels(models, fallbackBaseUrl),
926
+ stream: (model, context, streamOptions) => requireUpstream().stream(model, context, withReasoning(streamOptions)),
927
+ streamSimple: (model, context, simpleOptions) => (options?.streamSimple ?? requireUpstream().streamSimple)(model, context, withReasoning(simpleOptions))
928
+ };
929
+ }
930
+ // src/api/openai-completions.ts
931
+ /**
932
+ * Neuralwatt streams chain-of-thought in the `reasoning` field, and pi-ai
933
+ * replays prior thinking under the field name it recorded from the stream —
934
+ * also `reasoning`. The served chat templates only render `reasoning_content`
935
+ * (verified against the Kimi K3 template), so replayed thinking never reaches
936
+ * the model. Rename the replayed field on the wire. This is a move, not a
937
+ * copy: sending an empty `reasoning_content` next to a populated `reasoning`
938
+ * makes the gateway prefer the empty field and silently drops the replay.
939
+ */
940
+ function makeReasoningReplayInjector(upstream) {
941
+ return async (payload, model) => {
942
+ const next = await upstream?.(payload, model);
943
+ const body = next !== void 0 ? next : payload;
944
+ const messages = body.messages;
945
+ if (!Array.isArray(messages)) return body;
946
+ return {
947
+ ...body,
948
+ messages: messages.map((message) => {
949
+ if (message?.role !== "assistant" || !("reasoning" in message)) return message;
950
+ const { reasoning, ...rest } = message;
951
+ return typeof rest.reasoning_content === "string" && rest.reasoning_content.length > 0 ? rest : {
952
+ ...rest,
953
+ reasoning_content: reasoning
954
+ };
955
+ })
956
+ };
957
+ };
958
+ }
959
+ function createOpenAiCompletionsApi(options) {
960
+ const requireUpstream = () => {
961
+ if (!options?.upstream) throw new Error("createOpenAiCompletionsApi requires an upstream: pass pi-ai's openAICompletionsApi() streams");
962
+ return options.upstream;
963
+ };
964
+ const fallbackBaseUrl = options?.baseUrl ?? "https://api.neuralwatt.com/v1";
965
+ const withOptOutHeader = (requestOptions) => {
966
+ if (!options?.toolsOptOut?.()) return requestOptions;
967
+ return {
968
+ ...requestOptions,
969
+ headers: {
970
+ ...requestOptions?.headers,
971
+ [NEURALWATT_TOOLS_OPT_OUT_HEADER]: "true"
972
+ }
973
+ };
974
+ };
975
+ const withReasoningReplay = (options) => ({
976
+ ...options,
977
+ onPayload: makeReasoningReplayInjector(options?.onPayload)
978
+ });
979
+ return {
980
+ stampModels: (models) => models.map((model) => {
981
+ const { reasoningContract: _reasoningContract, ...compiled } = model;
982
+ return {
983
+ ...compiled,
984
+ api: "openai-completions",
985
+ provider: NEURALWATT_PROVIDER_ID,
986
+ baseUrl: model.baseUrl ?? fallbackBaseUrl,
987
+ headers: NEURALWATT_REQUEST_HEADERS
988
+ };
989
+ }),
990
+ stream: (model, context, streamOptions) => requireUpstream().stream(model, context, withOptOutHeader(withReasoningReplay(streamOptions))),
991
+ streamSimple: (model, context, simpleOptions) => (options?.streamSimple ?? requireUpstream().streamSimple)(model, context, withOptOutHeader(withReasoningReplay(simpleOptions)))
992
+ };
993
+ }
994
+ // src/provider.ts
995
+ function createNeuralwattApiKeyAuth() {
996
+ return { apiKey: {
997
+ name: "Neuralwatt API key",
998
+ login: async (interaction) => ({
999
+ type: "api_key",
1000
+ key: await interaction.prompt({
1001
+ type: "secret",
1002
+ message: "Enter Neuralwatt API key"
1003
+ })
1004
+ }),
1005
+ check: async ({ ctx, credential }) => {
1006
+ if (credential?.type === "api_key" && credential.key) return {
1007
+ type: "api_key",
1008
+ source: "stored credential"
1009
+ };
1010
+ if (await ctx.env("NEURALWATT_API_KEY")) return {
1011
+ type: "api_key",
1012
+ source: NEURALWATT_API_KEY_ENV
1013
+ };
1014
+ return {
1015
+ type: "api_key",
1016
+ source: "anonymous"
1017
+ };
1018
+ },
1019
+ resolve: async ({ ctx, credential, signal }) => {
1020
+ signal.throwIfAborted();
1021
+ if (credential?.type === "api_key" && credential.key) return {
1022
+ auth: { apiKey: credential.key },
1023
+ env: credential.env,
1024
+ source: "stored credential"
1025
+ };
1026
+ const envKey = await ctx.env(NEURALWATT_API_KEY_ENV);
1027
+ signal.throwIfAborted();
1028
+ if (envKey) return {
1029
+ auth: { apiKey: envKey },
1030
+ source: NEURALWATT_API_KEY_ENV
1031
+ };
1032
+ return {
1033
+ auth: { apiKey: "-" },
1034
+ source: "anonymous"
1035
+ };
1036
+ }
1037
+ } };
1038
+ }
1039
+ function createApiHandler(api, options) {
1040
+ const baseUrl = resolveBaseUrl(options);
1041
+ if (api === "anthropic-messages") return createAnthropicMessagesApi({
1042
+ upstream: options?.messagesUpstream,
1043
+ baseUrl,
1044
+ streamSimple: options?.messagesStreamSimple
1045
+ });
1046
+ return createOpenAiCompletionsApi({
1047
+ upstream: options?.openAiUpstream,
1048
+ baseUrl,
1049
+ toolsOptOut: options?.toolsOptOut,
1050
+ streamSimple: options?.openAiStreamSimple
1051
+ });
1052
+ }
1053
+ function resolveBaseUrl(options) {
1054
+ return (typeof options?.baseUrl === "function" ? options.baseUrl() : options?.baseUrl) ?? "https://api.neuralwatt.com/v1";
1055
+ }
1056
+ // provider/headers.ts
1057
+ const DEFAULT_ATTRIBUTION_URL = "https://pi.dev";
1058
+ const CONVERSATION_ID_HEADER = "X-NW-Conversation-ID";
1059
+ function provenanceRequestHeaders(options) {
1060
+ if (options?.enabled === false) return void 0;
1061
+ return { Referer: options?.referer ?? "https://pi.dev" };
1062
+ }
1063
+ function withProvenanceHeaders(streams, headers) {
1064
+ if (!headers) return streams;
1065
+ const withHeaders = (fn) => (model, mid, options) => {
1066
+ const provenance = options?.sessionId ? {
1067
+ ...headers,
1068
+ [CONVERSATION_ID_HEADER]: options.sessionId
1069
+ } : headers;
1070
+ return fn(model, mid, {
1071
+ ...options,
1072
+ headers: {
1073
+ ...provenance,
1074
+ ...options?.headers
1075
+ }
1076
+ });
1077
+ };
1078
+ const next = {
1079
+ stream: withHeaders(streams.stream),
1080
+ streamSimple: withHeaders(streams.streamSimple)
1081
+ };
1082
+ if (streams.fetchDeferred) next.fetchDeferred = withHeaders(streams.fetchDeferred);
1083
+ if (streams.cancelDeferred) next.cancelDeferred = withHeaders(streams.cancelDeferred);
1084
+ return next;
1085
+ }
1086
+ // provider/index.ts
1087
+ function fetchCatalogModels(baseUrl) {
1088
+ return async (apiKey, signal) => {
1089
+ const result = await fetchNeuralwattModels(apiKey, baseUrl, signal);
1090
+ if (!result.success) throw new Error("Neuralwatt models API request failed");
1091
+ return result.data;
1092
+ };
1093
+ }
1094
+ function toStreams(handler) {
1095
+ return {
1096
+ stream: (model, context, options) => handler.stream(model, context, options),
1097
+ streamSimple: (model, context, options) => handler.streamSimple(model, context, options)
1098
+ };
1099
+ }
1100
+ function createNeuralwattProvider(options = {}) {
1101
+ const api = options.api ?? "openai-completions";
1102
+ const baseUrl = resolveApiBaseUrl(options.baseUrl);
1103
+ const handler = createApiHandler(api, {
1104
+ ...options,
1105
+ baseUrl,
1106
+ openAiUpstream: openAICompletionsApi(),
1107
+ messagesUpstream: anthropicMessagesApi()
1108
+ });
1109
+ const staticModels = buildNeuralwattProviderModels();
1110
+ const refreshCatalog = createNeuralwattRefreshModels(staticModels, fetchCatalogModels(baseUrl), buildNeuralwattProviderModelsFromApi, buildNeuralwattProviderModelsFromStore, baseUrl);
1111
+ const { Referer: _referer, ...defaultHeaders } = NEURALWATT_REQUEST_HEADERS;
1112
+ const provenanceHeaders = provenanceRequestHeaders(options.provenance);
1113
+ const headers = {
1114
+ ...defaultHeaders,
1115
+ ...provenanceHeaders
1116
+ };
1117
+ const stamp = (models) => {
1118
+ const partitioned = partitionNeuralwattModels(models);
1119
+ return [...handler.stampModels(partitioned.chat), ...stampClassifierModels(partitioned.classifiers, baseUrl)].map((model) => ({
1120
+ ...model,
1121
+ headers
1122
+ }));
1123
+ };
1124
+ return createProvider({
1125
+ id: NEURALWATT_PROVIDER_ID,
1126
+ name: "Neuralwatt",
1127
+ baseUrl,
1128
+ headers,
1129
+ auth: createNeuralwattApiKeyAuth(),
1130
+ models: stamp(staticModels),
1131
+ fetchModels: async (context) => {
1132
+ const models = await refreshCatalog({
1133
+ ...context,
1134
+ publish: async () => true
1135
+ });
1136
+ return stamp(models);
1137
+ },
1138
+ api: withProvenanceHeaders(toStreams(handler), provenanceHeaders),
1139
+ classifiers: { [NEURALWATT_SYSTEM_ONE_API]: { classify } }
1140
+ });
1141
+ }
1142
+ export { CONVERSATION_ID_HEADER, DEFAULT_ATTRIBUTION_URL, NEURALWATT_API_KEY_ENV, NEURALWATT_BASE_URL, NEURALWATT_PROVIDER_ID, createNeuralwattProvider as default, provenanceRequestHeaders, withProvenanceHeaders };