@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
@@ -1,4 +1,3 @@
1
- import { configuredApiBaseUrl } from "../config/loader";
2
1
  import type {
3
2
  NeuralwattApiModel,
4
3
  NeuralwattApiModelsResponse,
@@ -27,11 +26,12 @@ function combineSignals(signal?: AbortSignal): AbortSignal {
27
26
 
28
27
  async function neuralwattFetch(
29
28
  path: string,
29
+ baseUrl: string,
30
30
  apiKey: string | undefined,
31
31
  signal?: AbortSignal,
32
32
  headers?: Record<string, string>,
33
33
  ): Promise<Response> {
34
- return fetch(`${configuredApiBaseUrl()}${path}`, {
34
+ return fetch(`${baseUrl}${path}`, {
35
35
  headers: { ...authHeaders(apiKey), ...headers },
36
36
  signal: combineSignals(signal),
37
37
  });
@@ -43,15 +43,22 @@ export type NeuralwattModelsResult =
43
43
 
44
44
  export async function fetchNeuralwattModels(
45
45
  apiKey: string | undefined,
46
+ baseUrl: string,
46
47
  signal?: AbortSignal,
47
48
  ): Promise<NeuralwattModelsResult> {
48
49
  const combined = combineSignals(signal);
49
50
 
50
51
  try {
51
- const response = await neuralwattFetch("/models", apiKey, combined, {
52
- Referer: "https://pi.dev",
53
- "X-Title": "npm:@aliou/pi-neuralwatt",
54
- });
52
+ const response = await neuralwattFetch(
53
+ "/models",
54
+ baseUrl,
55
+ apiKey,
56
+ combined,
57
+ {
58
+ Referer: "https://pi.dev",
59
+ "X-Title": "npm:@aliou/pi-neuralwatt",
60
+ },
61
+ );
55
62
 
56
63
  if (!response.ok) {
57
64
  return { success: false };
@@ -66,6 +73,7 @@ export async function fetchNeuralwattModels(
66
73
 
67
74
  export async function fetchQuotas(
68
75
  apiKey: string,
76
+ baseUrl: string,
69
77
  signal?: AbortSignal,
70
78
  ): Promise<QuotasResult> {
71
79
  if (!apiKey) {
@@ -78,7 +86,7 @@ export async function fetchQuotas(
78
86
  const combined = combineSignals(signal);
79
87
 
80
88
  try {
81
- const response = await neuralwattFetch("/quota", apiKey, combined);
89
+ const response = await neuralwattFetch("/quota", baseUrl, apiKey, combined);
82
90
 
83
91
  if (!response.ok) {
84
92
  let message = response.statusText;
@@ -1,18 +1,18 @@
1
- import type { ProviderModelConfig } from "@earendil-works/pi-coding-agent";
1
+ import type { Api, ClassifierModel, Model } from "@earendil-works/pi-ai";
2
2
  import type {
3
3
  NeuralwattApiModelReasoning,
4
4
  NeuralwattReasoningEffort,
5
- } from "../../../src/types/models-api";
5
+ } from "../types/models-api";
6
6
 
7
- export type ProviderChatModelConfig = Extract<
8
- ProviderModelConfig,
9
- { type?: "chat" }
10
- >;
7
+ export type ProviderChatModelConfig = Omit<
8
+ Model<Api>,
9
+ "api" | "provider" | "baseUrl"
10
+ > & { baseUrl?: string };
11
11
 
12
- export type ProviderClassifierModelConfig = Extract<
13
- ProviderModelConfig,
14
- { type: "classifier" }
15
- >;
12
+ export type ProviderClassifierModelConfig = Omit<
13
+ ClassifierModel<"typesafe-system-one">,
14
+ "api" | "provider" | "baseUrl"
15
+ > & { baseUrl?: string };
16
16
 
17
17
  export const NEURALWATT_SYSTEM_ONE_API = "typesafe-system-one" as const;
18
18
 
@@ -1,4 +1,4 @@
1
- import type { NeuralwattApiModel } from "../../../src/types/models-api";
1
+ import type { NeuralwattApiModel } from "../types/models-api";
2
2
  import {
3
3
  buildThinkingLevelMap,
4
4
  NEURALWATT_SYSTEM_ONE_API,
@@ -16,23 +16,6 @@ import {
16
16
  // unsupported levels through the aliases. See `models.test.ts` for the drift
17
17
  // check against the live catalog.
18
18
 
19
- // DeepSeek V4 Flash: efforts max/high/none, not mandatory.
20
- // https://api-docs.deepseek.com/guides/thinking_mode/
21
- const DEEPSEEK_V4_FLASH: NeuralwattModelFamily = {
22
- cost: { input: 0.14, output: 0.28, cacheRead: 0.028 },
23
- vision: false,
24
- reasoningMetadata: {
25
- supported_efforts: ["max", "high", "none"],
26
- mandatory: false,
27
- effort_aliases: {
28
- xhigh: "max",
29
- medium: "high",
30
- low: "high",
31
- minimal: "high",
32
- },
33
- },
34
- };
35
-
36
19
  // DeepSeek. V4.1 Flash is vision-capable, unlike V4 Flash, and admits
37
20
  // reasoning levels up to `xhigh`. Not mandatory (off defaults).
38
21
  const DEEPSEEK_V4_1_FLASH: NeuralwattModelFamily = {
@@ -192,33 +175,6 @@ const QWEN_3_8_27B: NeuralwattModelFamily = {
192
175
  };
193
176
 
194
177
  const FAMILIES: [NeuralwattModelFamily, NeuralwattVariantSpec[]][] = [
195
- [
196
- DEEPSEEK_V4_FLASH,
197
- [
198
- {
199
- id: "deepseek-v4-flash",
200
- name: "DeepSeek V4 Flash",
201
- contextWindow: 1048560,
202
- maxOutputTokens: 393216,
203
- reasoning: true,
204
- },
205
- {
206
- id: "deepseek-v4-flash-flex",
207
- name: "DeepSeek V4 Flash (flex)",
208
- contextWindow: 1048560,
209
- maxOutputTokens: 393216,
210
- reasoning: true,
211
- costMultiplier: 0.65,
212
- },
213
- {
214
- id: "deepseek-v4-flash-speed",
215
- name: "DeepSeek V4 Flash (Speed)",
216
- contextWindow: 1048560,
217
- maxOutputTokens: 393216,
218
- reasoning: true,
219
- },
220
- ],
221
- ],
222
178
  [
223
179
  DEEPSEEK_V4_1_FLASH,
224
180
  [
@@ -3,8 +3,7 @@ import type {
3
3
  ModelsStoreEntry,
4
4
  RefreshModelsContext,
5
5
  } from "@earendil-works/pi-ai";
6
- import { configuredApiBaseUrl } from "../../../src/config/loader";
7
- import type { NeuralwattApiModel } from "../../../src/types/models-api";
6
+ import type { NeuralwattApiModel } from "../types/models-api";
8
7
  import type {
9
8
  buildNeuralwattProviderModels,
10
9
  buildNeuralwattProviderModelsFromApi,
@@ -33,15 +32,16 @@ function catalogScope(apiKey: string | undefined): CatalogScope {
33
32
  : "public";
34
33
  }
35
34
 
36
- function catalogKey(scope: CatalogScope): string {
37
- return `${scope} ${CATALOG_SCOPE_VERSION} ${configuredApiBaseUrl()}`;
35
+ function catalogKey(scope: CatalogScope, baseUrl: string): string {
36
+ return `${scope} ${CATALOG_SCOPE_VERSION} ${baseUrl}`;
38
37
  }
39
38
 
40
39
  function catalogKeyMatches(
41
40
  entry: ScopedModelsStoreEntry | undefined,
42
41
  scope: CatalogScope,
42
+ baseUrl: string,
43
43
  ): boolean {
44
- return entry !== undefined && entry.catalogKey === catalogKey(scope);
44
+ return entry !== undefined && entry.catalogKey === catalogKey(scope, baseUrl);
45
45
  }
46
46
 
47
47
  export type FetchNeuralwattApiModels = (
@@ -64,8 +64,9 @@ function isFreshStoreEntry(
64
64
  function isUsableStoreEntry(
65
65
  entry: Readonly<ModelsStoreEntry> | undefined,
66
66
  scope: CatalogScope,
67
+ baseUrl: string,
67
68
  ): entry is ModelsStoreEntry {
68
- return isFreshStoreEntry(entry) && catalogKeyMatches(entry, scope);
69
+ return isFreshStoreEntry(entry) && catalogKeyMatches(entry, scope, baseUrl);
69
70
  }
70
71
 
71
72
  export function createNeuralwattRefreshModels(
@@ -73,9 +74,11 @@ export function createNeuralwattRefreshModels(
73
74
  fetchApiModels: FetchNeuralwattApiModels,
74
75
  buildFromApi: typeof buildNeuralwattProviderModelsFromApi,
75
76
  buildFromStore: typeof buildNeuralwattProviderModelsFromStore,
77
+ baseUrl: string | (() => string),
76
78
  ) {
77
79
  return async (context: RefreshModelsContext): Promise<NeuralwattModel[]> => {
78
80
  context.signal.throwIfAborted();
81
+ const resolvedBaseUrl = typeof baseUrl === "function" ? baseUrl() : baseUrl;
79
82
  const fallback = buildFromStore(staticModels);
80
83
  try {
81
84
  const apiKey =
@@ -85,11 +88,15 @@ export function createNeuralwattRefreshModels(
85
88
  const scope = catalogScope(apiKey);
86
89
  const stored = context.stored as ScopedModelsStoreEntry | undefined;
87
90
  if (!context.allowNetwork) {
88
- return stored !== undefined && catalogKeyMatches(stored, scope)
91
+ return stored !== undefined &&
92
+ catalogKeyMatches(stored, scope, resolvedBaseUrl)
89
93
  ? buildFromStore(asStoredChatModels(stored.models))
90
94
  : fallback;
91
95
  }
92
- if (!context.force && isUsableStoreEntry(stored, scope)) {
96
+ if (
97
+ !context.force &&
98
+ isUsableStoreEntry(stored, scope, resolvedBaseUrl)
99
+ ) {
93
100
  return buildFromStore(asStoredChatModels(stored.models));
94
101
  }
95
102
  const apiModels = await fetchApiModels(apiKey, context.signal);
@@ -98,7 +105,7 @@ export function createNeuralwattRefreshModels(
98
105
  const entry: ScopedModelsStoreEntry = {
99
106
  models: models as unknown as ModelsStoreEntry["models"],
100
107
  checkedAt: Date.now(),
101
- catalogKey: catalogKey(scope),
108
+ catalogKey: catalogKey(scope, resolvedBaseUrl),
102
109
  };
103
110
  await context.publish({ persist: entry }).catch(() => undefined);
104
111
  context.signal.throwIfAborted();
@@ -1,9 +1,13 @@
1
- import type { Provider } from "@earendil-works/pi-ai";
2
- import type { NeuralwattApi } from "../../src/config";
1
+ import type {
2
+ Provider,
3
+ ProviderAuth,
4
+ ProviderStreams,
5
+ } from "@earendil-works/pi-ai";
3
6
  import { createAnthropicMessagesApi } from "./api/anthropic-messages";
4
7
  import { createOpenAiCompletionsApi } from "./api/openai-completions";
5
8
  import { classify, stampClassifierModels } from "./api/system-one";
6
9
  import type { NeuralwattApiHandler } from "./api/types";
10
+ import type { NeuralwattApi } from "./config";
7
11
  import {
8
12
  NEURALWATT_API_KEY_ENV,
9
13
  NEURALWATT_BASE_URL,
@@ -24,27 +28,87 @@ import type { AnyStreamSimple } from "./stream-simple";
24
28
 
25
29
  export { NEURALWATT_API_KEY_ENV, NEURALWATT_BASE_URL, NEURALWATT_PROVIDER_ID };
26
30
 
31
+ export function createNeuralwattApiKeyAuth(): ProviderAuth {
32
+ return {
33
+ apiKey: {
34
+ name: "Neuralwatt API key",
35
+ login: async (interaction) => ({
36
+ type: "api_key",
37
+ key: await interaction.prompt({
38
+ type: "secret",
39
+ message: "Enter Neuralwatt API key",
40
+ }),
41
+ }),
42
+ check: async ({ ctx, credential }) => {
43
+ if (credential?.type === "api_key" && credential.key) {
44
+ return { type: "api_key", source: "stored credential" };
45
+ }
46
+ if (await ctx.env(NEURALWATT_API_KEY_ENV)) {
47
+ return { type: "api_key", source: NEURALWATT_API_KEY_ENV };
48
+ }
49
+ return { type: "api_key", source: "anonymous" };
50
+ },
51
+ resolve: async ({ ctx, credential, signal }) => {
52
+ signal.throwIfAborted();
53
+ if (credential?.type === "api_key" && credential.key) {
54
+ return {
55
+ auth: { apiKey: credential.key },
56
+ env: credential.env,
57
+ source: "stored credential",
58
+ };
59
+ }
60
+ const envKey = await ctx.env(NEURALWATT_API_KEY_ENV);
61
+ signal.throwIfAborted();
62
+ if (envKey) {
63
+ return { auth: { apiKey: envKey }, source: NEURALWATT_API_KEY_ENV };
64
+ }
65
+ // pi-ai rejects empty keys before dispatch; "-" is the neutral
66
+ // placeholder that gateways strip or replace server-side.
67
+ return { auth: { apiKey: "-" }, source: "anonymous" };
68
+ },
69
+ },
70
+ };
71
+ }
72
+
27
73
  export interface NeuralwattProviderOptions {
28
74
  /** Active API surface; resolved once. Changes need a `/reload`. */
29
75
  api?: NeuralwattApi;
76
+ baseUrl?: string | (() => string);
77
+ openAiUpstream?: ProviderStreams;
78
+ messagesUpstream?: ProviderStreams;
79
+ toolsOptOut?: () => boolean;
30
80
  openAiStreamSimple?: AnyStreamSimple;
31
81
  messagesStreamSimple?: AnyStreamSimple;
32
82
  }
33
83
 
34
- function createApiHandler(
84
+ export function createApiHandler(
35
85
  api: NeuralwattApi,
36
86
  options?: NeuralwattProviderOptions,
37
87
  ): NeuralwattApiHandler {
88
+ const baseUrl = resolveBaseUrl(options);
38
89
  if (api === "anthropic-messages") {
39
90
  return createAnthropicMessagesApi({
91
+ upstream: options?.messagesUpstream,
92
+ baseUrl,
40
93
  streamSimple: options?.messagesStreamSimple,
41
94
  });
42
95
  }
43
96
  return createOpenAiCompletionsApi({
97
+ upstream: options?.openAiUpstream,
98
+ baseUrl,
99
+ toolsOptOut: options?.toolsOptOut,
44
100
  streamSimple: options?.openAiStreamSimple,
45
101
  });
46
102
  }
47
103
 
104
+ function resolveBaseUrl(options?: NeuralwattProviderOptions): string {
105
+ const value =
106
+ typeof options?.baseUrl === "function"
107
+ ? options.baseUrl()
108
+ : options?.baseUrl;
109
+ return value ?? NEURALWATT_BASE_URL;
110
+ }
111
+
48
112
  export function createNeuralwattProvider(
49
113
  staticModels: NeuralwattModel[],
50
114
  fetchApiModels: FetchNeuralwattApiModels,
@@ -60,59 +124,30 @@ export function createNeuralwattProvider(
60
124
  fetchApiModels,
61
125
  buildNeuralwattProviderModelsFromApi,
62
126
  buildNeuralwattProviderModelsFromStore,
127
+ () => resolveBaseUrl(options),
63
128
  );
64
129
 
65
130
  return {
66
131
  id: NEURALWATT_PROVIDER_ID,
67
132
  name: "Neuralwatt",
68
- baseUrl: NEURALWATT_BASE_URL,
69
- headers: NEURALWATT_REQUEST_HEADERS,
70
- auth: {
71
- apiKey: {
72
- name: "Neuralwatt API key",
73
- login: async (interaction) => ({
74
- type: "api_key",
75
- key: await interaction.prompt({
76
- type: "secret",
77
- message: "Enter Neuralwatt API key",
78
- }),
79
- }),
80
- check: async ({ ctx, credential }) => {
81
- if (credential?.type === "api_key" && credential.key) {
82
- return { type: "api_key", source: "stored credential" };
83
- }
84
- if (await ctx.env(NEURALWATT_API_KEY_ENV)) {
85
- return { type: "api_key", source: NEURALWATT_API_KEY_ENV };
86
- }
87
- return { type: "api_key", source: "anonymous" };
88
- },
89
- resolve: async ({ ctx, credential, signal }) => {
90
- signal.throwIfAborted();
91
- if (credential?.type === "api_key" && credential.key) {
92
- return {
93
- auth: { apiKey: credential.key },
94
- env: credential.env,
95
- source: "stored credential",
96
- };
97
- }
98
- const envKey = await ctx.env(NEURALWATT_API_KEY_ENV);
99
- signal.throwIfAborted();
100
- if (envKey) {
101
- return { auth: { apiKey: envKey }, source: NEURALWATT_API_KEY_ENV };
102
- }
103
- // pi-ai rejects empty keys before dispatch; "-" is the neutral
104
- // placeholder that gateways strip or replace server-side.
105
- return { auth: { apiKey: "-" }, source: "anonymous" };
106
- },
107
- },
133
+ get baseUrl() {
134
+ return resolveBaseUrl(options);
108
135
  },
136
+ headers: NEURALWATT_REQUEST_HEADERS,
137
+ auth: createNeuralwattApiKeyAuth(),
109
138
  getModels: () =>
110
- handler.stampModels(partitionNeuralwattModels(canonicalModels).chat),
139
+ createApiHandler(
140
+ options?.api ?? "openai-completions",
141
+ options,
142
+ ).stampModels(partitionNeuralwattModels(canonicalModels).chat),
111
143
  getAllModels: () => {
112
144
  const { chat, classifiers } = partitionNeuralwattModels(canonicalModels);
113
145
  return [
114
- ...handler.stampModels(chat),
115
- ...stampClassifierModels(classifiers),
146
+ ...createApiHandler(
147
+ options?.api ?? "openai-completions",
148
+ options,
149
+ ).stampModels(chat),
150
+ ...stampClassifierModels(classifiers, resolveBaseUrl(options)),
116
151
  ];
117
152
  },
118
153
  classify: (model, context, options) => classify(model, context, options),
@@ -1,4 +1,4 @@
1
- import type { NeuralwattQuotas } from "../../src/types/quota-api";
1
+ import type { NeuralwattQuotas } from "./types/quota-api";
2
2
 
3
3
  const JOULES_PER_KWH = 3_600_000;
4
4
 
@@ -85,13 +85,14 @@ export async function readQuotaCommentsFromTee(
85
85
  const final = decoder.decode(new Uint8Array(0), { stream: false });
86
86
  const remaining = (buffer + final).trim();
87
87
  if (remaining) onComment(remaining);
88
- } catch {
88
+ } catch (_error) {
89
89
  // The SDK side may abort the tee; quota comments are best-effort.
90
+ void _error;
90
91
  } finally {
91
92
  try {
92
93
  reader.releaseLock();
93
- } catch {
94
- // ignore
94
+ } catch (_error) {
95
+ void _error; // Intentionally ignored - the lock may already be released.
95
96
  }
96
97
  }
97
98
  }
@@ -16,7 +16,7 @@ import type {
16
16
  SimpleStreamOptions,
17
17
  TranscriptContext,
18
18
  } from "@earendil-works/pi-ai";
19
- import { configuredApiBaseUrl } from "../../src/config/loader";
19
+ import { NEURALWATT_BASE_URL } from "./constants";
20
20
  import {
21
21
  type NeuralwattRateLimitInfo,
22
22
  parseRateLimitHeaders,
@@ -68,10 +68,10 @@ function isProviderStreamUrl(
68
68
  export function wrapNeuralwattStreamSimple(
69
69
  base: AnyStreamSimple,
70
70
  callbacks: NeuralwattStreamCallbacks,
71
+ fallbackBaseUrl: string = NEURALWATT_BASE_URL,
71
72
  ): AnyStreamSimple {
72
73
  return (model, context, options = {}) => {
73
- const providerOrigin = new URL(model.baseUrl ?? configuredApiBaseUrl())
74
- .origin;
74
+ const providerOrigin = new URL(model.baseUrl ?? fallbackBaseUrl).origin;
75
75
  const callerFetch = options.fetch;
76
76
 
77
77
  const neuralwattFetch: FetchFunction = async (input, init) => {
File without changes
File without changes