@aliou/pi-neuralwatt 0.18.1 → 0.19.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +630 -0
  2. package/README.md +23 -0
  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 +7 -2
  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 +1 -1
  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 +39 -31
  15. package/extensions/provider/quota-store.ts +2 -1
  16. package/extensions/quota-warnings/index.ts +1 -1
  17. package/extensions/shared/truncate.ts +292 -0
  18. package/package.json +24 -8
  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 +1 -1
  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 @@
1
+ export { configLoader } from "./loader";
@@ -1,12 +1,12 @@
1
1
  import { buildSchemaUrl, ConfigLoader } from "@aliou/pi-utils-settings";
2
- import packageJson from "../../package.json";
3
- import { DEFAULT_CONFIG } from "./defaults";
4
- import { migrations } from "./migration";
2
+ import packageJson from "../../../package.json";
3
+ import { DEFAULT_CONFIG } from "../../../src/config/defaults";
4
+ import { resolveApi, resolveApiBaseUrl } from "../../../src/config/resolve";
5
5
  import type {
6
- NeuralwattApi,
7
6
  NeuralwattConfig,
8
7
  ResolvedNeuralwattConfig,
9
- } from "./types";
8
+ } from "../../../src/config/types";
9
+ import { migrations } from "./migration";
10
10
 
11
11
  /**
12
12
  * Fill in every field the rest of the code reads. Migrations already normalized
@@ -26,6 +26,7 @@ function normalizeResolvedConfig(
26
26
  enabled:
27
27
  config.quotaWarnings?.enabled ?? DEFAULT_CONFIG.quotaWarnings.enabled,
28
28
  },
29
+ hostedTools: config.hostedTools,
29
30
  provider: {
30
31
  api: resolveApi(config.provider?.api),
31
32
  apiBaseUrl: resolveApiBaseUrl(config.provider?.apiBaseUrl),
@@ -33,34 +34,19 @@ function normalizeResolvedConfig(
33
34
  };
34
35
  }
35
36
 
36
- export function resolveApi(value: string | undefined): NeuralwattApi {
37
- if (value === "anthropic-messages" || value === "openai-completions") {
38
- return value;
39
- }
40
- return DEFAULT_CONFIG.provider.api;
41
- }
42
-
43
- export function resolveApiBaseUrl(value: string | undefined): string {
44
- const trimmed = value?.trim().replace(/\/+$/u, "");
45
- if (!trimmed) {
46
- return DEFAULT_CONFIG.provider.apiBaseUrl;
47
- }
37
+ export function configuredApiBaseUrl(): string {
48
38
  try {
49
- const url = new URL(trimmed);
50
- if (url.protocol !== "https:" && url.protocol !== "http:") {
51
- return DEFAULT_CONFIG.provider.apiBaseUrl;
52
- }
39
+ return configLoader.getConfig().provider.apiBaseUrl;
53
40
  } catch {
54
41
  return DEFAULT_CONFIG.provider.apiBaseUrl;
55
42
  }
56
- return trimmed;
57
43
  }
58
44
 
59
- export function configuredApiBaseUrl(): string {
45
+ export function hostedToolsOptOut(): boolean {
60
46
  try {
61
- return configLoader.getConfig().provider.apiBaseUrl;
47
+ return configLoader.getConfig().hostedTools?.enabled === false;
62
48
  } catch {
63
- return DEFAULT_CONFIG.provider.apiBaseUrl;
49
+ return false;
64
50
  }
65
51
  }
66
52
 
@@ -2,7 +2,7 @@ import { constants } from "node:fs";
2
2
  import { copyFile } from "node:fs/promises";
3
3
  import { basename, dirname, join } from "node:path";
4
4
  import type { Migration } from "@aliou/pi-utils-settings";
5
- import packageJson from "../../../package.json";
5
+ import packageJson from "../../../../package.json";
6
6
 
7
7
  /** The original flat config, replaced by per-feature sections. */
8
8
  interface FlatNeuralwattConfig {
@@ -5,6 +5,7 @@ import {
5
5
  } from "@earendil-works/pi-coding-agent";
6
6
  import { fetchQuotas } from "../../src/lib/neuralwatt-api";
7
7
  import { getNeuralwattApiKey } from "../_shared/auth";
8
+ import { configuredApiBaseUrl } from "../_shared/config/loader";
8
9
  import { QuotasComponent } from "./components/quotas-display";
9
10
 
10
11
  function missingAuthMessage(): string {
@@ -44,7 +45,11 @@ export function registerQuotasCommand(
44
45
  );
45
46
 
46
47
  async function loadQuotas(): Promise<void> {
47
- const fetchResult = await fetchQuotas(key, controller.signal);
48
+ const fetchResult = await fetchQuotas(
49
+ key,
50
+ configuredApiBaseUrl(),
51
+ controller.signal,
52
+ );
48
53
  if (controller.signal.aborted) return;
49
54
  if (fetchResult.success) {
50
55
  component.setState({
@@ -75,7 +80,7 @@ export function registerQuotasCommand(
75
80
 
76
81
  // Non-interactive fallback (RPC, print, JSON modes)
77
82
  if (result === undefined) {
78
- const fetchResult = await fetchQuotas(key);
83
+ const fetchResult = await fetchQuotas(key, configuredApiBaseUrl());
79
84
  if (!fetchResult.success) {
80
85
  ctx.ui.notify(
81
86
  JSON.stringify({ error: fetchResult.error.message }),
@@ -1,5 +1,4 @@
1
1
  import type { Theme } from "@earendil-works/pi-coding-agent";
2
- import { truncateToWidth } from "@earendil-works/pi-tui";
3
2
  import type { NeuralwattQuotas } from "../../../src/types/quota-api";
4
3
  import {
5
4
  percentCreditsRemaining,
@@ -11,6 +10,7 @@ import {
11
10
  formatTokens,
12
11
  formatUsd,
13
12
  } from "../../../src/utils/quota-format";
13
+ import { truncateToWidth } from "../../shared/truncate";
14
14
  import { renderProgressBar } from "./progress-bar";
15
15
 
16
16
  /**
@@ -1,8 +1,9 @@
1
1
  import type { Theme } from "@earendil-works/pi-coding-agent";
2
2
  import { DynamicBorder } from "@earendil-works/pi-coding-agent";
3
3
  import type { Component, TUI } from "@earendil-works/pi-tui";
4
- import { Loader, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
4
+ import { Loader, matchesKey } from "@earendil-works/pi-tui";
5
5
  import type { NeuralwattQuotas } from "../../../src/types/quota-api";
6
+ import { truncateToWidth } from "../../shared/truncate";
6
7
  import {
7
8
  renderCreditsTab,
8
9
  renderSubscriptionTab,
@@ -1,12 +1,12 @@
1
1
  import { bindProjectConfig } from "@aliou/pi-utils-settings";
2
2
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
- import { configLoader } from "../../src/config";
4
3
  import {
5
4
  NEURALWATT_CONFIG_UPDATED_EVENT,
6
5
  NEURALWATT_EXTENSIONS_REGISTER_EVENT,
7
6
  NEURALWATT_EXTENSIONS_REQUEST_EVENT,
8
7
  type NeuralwattConfigUpdatedPayload,
9
8
  } from "../../src/events";
9
+ import { configLoader } from "../_shared/config";
10
10
  import { registerQuotasCommand } from "./command";
11
11
 
12
12
  export default async function (pi: ExtensionAPI) {
@@ -1,10 +1,6 @@
1
1
  import type { Component, SettingsListTheme } from "@earendil-works/pi-tui";
2
- import {
3
- Input,
4
- Key,
5
- matchesKey,
6
- truncateToWidth,
7
- } from "@earendil-works/pi-tui";
2
+ import { Input, Key, matchesKey } from "@earendil-works/pi-tui";
3
+ import { truncateToWidth } from "../../../shared/truncate";
8
4
 
9
5
  export interface ApiBaseUrlEditorOptions {
10
6
  initial: string;
@@ -4,16 +4,16 @@ import {
4
4
  } from "@aliou/pi-utils-settings";
5
5
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
6
  import type { SettingItem } from "@earendil-works/pi-tui";
7
- import {
8
- configLoader,
9
- type NeuralwattApi,
10
- type NeuralwattConfig,
11
- type ResolvedNeuralwattConfig,
7
+ import type {
8
+ NeuralwattApi,
9
+ NeuralwattConfig,
10
+ ResolvedNeuralwattConfig,
12
11
  } from "../../../../src/config";
13
12
  import {
14
13
  NEURALWATT_CONFIG_UPDATED_EVENT,
15
14
  type NeuralwattFeatureId,
16
15
  } from "../../../../src/events";
16
+ import { configLoader } from "../../../_shared/config";
17
17
  import { ApiBaseUrlEditor } from "./api-base-url-editor";
18
18
 
19
19
  export interface RegisterNeuralwattSettingsOptions {
@@ -117,6 +117,19 @@ export function registerNeuralwattSettings(
117
117
  });
118
118
  },
119
119
  },
120
+ {
121
+ id: "hostedTools",
122
+ label: "Hosted tools",
123
+ description:
124
+ "Offer Neuralwatt hosted tools on OpenAI-surface requests; disabled sends an opt-out header with every request",
125
+ currentValue: featureValue(
126
+ tabConfig?.hostedTools,
127
+ resolved.hostedTools?.enabled ?? true,
128
+ )
129
+ ? "enabled"
130
+ : "disabled",
131
+ values: ["enabled", "disabled"],
132
+ },
120
133
  ],
121
134
  },
122
135
  {
@@ -161,6 +174,19 @@ export function registerNeuralwattSettings(
161
174
  };
162
175
  }
163
176
 
177
+ if (id === "hostedTools") {
178
+ if (newValue !== "enabled" && newValue !== "disabled") {
179
+ return null;
180
+ }
181
+ const updated = { ...config };
182
+ if (newValue === "disabled") {
183
+ updated.hostedTools = { ...config.hostedTools, enabled: false };
184
+ } else {
185
+ delete updated.hostedTools;
186
+ }
187
+ return updated;
188
+ }
189
+
164
190
  if (!getLoadedFeatures().has(id as NeuralwattFeatureId)) {
165
191
  return null;
166
192
  }
@@ -1,10 +1,12 @@
1
1
  import { bindProjectConfig } from "@aliou/pi-utils-settings";
2
- import { getApiProvider } from "@earendil-works/pi-ai/compat";
2
+ import {
3
+ anthropicMessagesApi,
4
+ openAICompletionsApi,
5
+ } from "@earendil-works/pi-ai/compat";
3
6
  import type {
4
7
  ExtensionAPI,
5
8
  ModelRegistry,
6
9
  } from "@earendil-works/pi-coding-agent";
7
- import { configLoader } from "../../src/config";
8
10
  import {
9
11
  NEURALWATT_CONFIG_UPDATED_EVENT,
10
12
  NEURALWATT_EXTENSIONS_REGISTER_EVENT,
@@ -18,23 +20,28 @@ import {
18
20
  fetchNeuralwattModels,
19
21
  fetchQuotas,
20
22
  } from "../../src/lib/neuralwatt-api";
21
- import type { NeuralwattQuotas } from "../../src/types/quota-api";
22
- import { getNeuralwattApiKey } from "../_shared/auth";
23
- import { registerNeuralwattSettings } from "./commands/settings";
24
- import { normalizeNeuralwattContextOverflowError } from "./context-overflow";
25
- import { buildNeuralwattProviderModels } from "./models";
26
- import { createNeuralwattProvider } from "./provider";
27
- import { buildQuotasFromHeaders, fetchRequestedQuotas } from "./quota-store";
23
+ import { buildNeuralwattProviderModels } from "../../src/models";
24
+ import { createNeuralwattProvider } from "../../src/provider";
28
25
  import {
29
26
  type NeuralwattRateLimitInfo,
30
27
  normalizeNeuralwattRateLimitError,
31
28
  parseRateLimitHeaders,
32
- } from "./rate-limit-error";
33
- import { updateQuotasFromSseComment } from "./sse-quotas";
29
+ } from "../../src/rate-limit-error";
30
+ import { updateQuotasFromSseComment } from "../../src/sse-quotas";
34
31
  import {
35
32
  type NeuralwattStreamCallbacks,
36
33
  wrapNeuralwattStreamSimple,
37
- } from "./stream-simple";
34
+ } from "../../src/stream-simple";
35
+ import type { NeuralwattQuotas } from "../../src/types/quota-api";
36
+ import { getNeuralwattApiKey } from "../_shared/auth";
37
+ import { configLoader } from "../_shared/config";
38
+ import {
39
+ configuredApiBaseUrl,
40
+ hostedToolsOptOut,
41
+ } from "../_shared/config/loader";
42
+ import { registerNeuralwattSettings } from "./commands/settings";
43
+ import { normalizeNeuralwattContextOverflowError } from "./context-overflow";
44
+ import { buildQuotasFromHeaders, fetchRequestedQuotas } from "./quota-store";
38
45
 
39
46
  const HEADER_EMIT_THROTTLE_MS = 5_000;
40
47
 
@@ -50,29 +57,26 @@ function registerNeuralwattProvider(
50
57
  ): void {
51
58
  const staticModels = buildNeuralwattProviderModels();
52
59
 
53
- const apiProvider = getApiProvider("openai-completions");
54
- const baseStreamSimple = apiProvider?.streamSimple;
55
- const streamSimple = baseStreamSimple
56
- ? (wrapNeuralwattStreamSimple(
57
- baseStreamSimple as never,
58
- streamCallbacks,
59
- ) as never)
60
- : undefined;
61
-
62
- const messagesApiProvider = getApiProvider("anthropic-messages");
63
- const messagesBaseStreamSimple = messagesApiProvider?.streamSimple;
64
- const messagesStreamSimple = messagesBaseStreamSimple
65
- ? (wrapNeuralwattStreamSimple(
66
- messagesBaseStreamSimple as never,
67
- streamCallbacks,
68
- ) as never)
69
- : undefined;
60
+ const openAiUpstream = openAICompletionsApi();
61
+ const messagesUpstream = anthropicMessagesApi();
62
+ const streamSimple = wrapNeuralwattStreamSimple(
63
+ openAiUpstream.streamSimple as never,
64
+ streamCallbacks,
65
+ ) as never;
66
+ const messagesStreamSimple = wrapNeuralwattStreamSimple(
67
+ messagesUpstream.streamSimple as never,
68
+ streamCallbacks,
69
+ ) as never;
70
70
 
71
71
  pi.registerProvider(
72
72
  createNeuralwattProvider(
73
73
  staticModels,
74
74
  async (apiKey, signal) => {
75
- const result = await fetchNeuralwattModels(apiKey, signal);
75
+ const result = await fetchNeuralwattModels(
76
+ apiKey,
77
+ configuredApiBaseUrl(),
78
+ signal,
79
+ );
76
80
  if (!result.success) {
77
81
  throw new Error("Neuralwatt models API request failed");
78
82
  }
@@ -80,6 +84,10 @@ function registerNeuralwattProvider(
80
84
  },
81
85
  {
82
86
  api: configLoader.getConfig().provider.api,
87
+ baseUrl: configuredApiBaseUrl,
88
+ openAiUpstream,
89
+ messagesUpstream,
90
+ toolsOptOut: hostedToolsOptOut,
83
91
  openAiStreamSimple: streamSimple,
84
92
  messagesStreamSimple,
85
93
  },
@@ -256,7 +264,7 @@ export default async function (pi: ExtensionAPI) {
256
264
  if (ctx.model?.provider !== "neuralwatt") return;
257
265
  const apiKey = await getNeuralwattApiKey(ctx.modelRegistry);
258
266
  if (!apiKey) return;
259
- const quotaResult = await fetchQuotas(apiKey);
267
+ const quotaResult = await fetchQuotas(apiKey, configuredApiBaseUrl());
260
268
  if (quotaResult.success) emitQuotas(quotaResult.data.quotas, "api");
261
269
  });
262
270
 
@@ -1,6 +1,7 @@
1
1
  import { parseQuotaHeaders } from "../../src/events";
2
2
  import { fetchQuotas } from "../../src/lib/neuralwatt-api";
3
3
  import type { NeuralwattQuotas } from "../../src/types/quota-api";
4
+ import { configuredApiBaseUrl } from "../_shared/config/loader";
4
5
 
5
6
  export function buildQuotasFromHeaders(
6
7
  headers: Record<string, string>,
@@ -45,7 +46,7 @@ export async function fetchRequestedQuotas(
45
46
  apiKey: string | undefined,
46
47
  ): Promise<NeuralwattQuotas | undefined> {
47
48
  if (!apiKey) return;
48
- const result = await fetchQuotas(apiKey);
49
+ const result = await fetchQuotas(apiKey, configuredApiBaseUrl());
49
50
  if (!result.success) return;
50
51
  return result.data.quotas;
51
52
  }
@@ -3,7 +3,6 @@ import type {
3
3
  ExtensionAPI,
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
- import { configLoader } from "../../src/config";
7
6
  import {
8
7
  NEURALWATT_CONFIG_UPDATED_EVENT,
9
8
  NEURALWATT_EXTENSIONS_REGISTER_EVENT,
@@ -12,6 +11,7 @@ import {
12
11
  type NeuralwattConfigUpdatedPayload,
13
12
  type NeuralwattQuotasUpdatedPayload,
14
13
  } from "../../src/events";
14
+ import { configLoader } from "../_shared/config";
15
15
  import { checkQuotas, clearAlertState } from "./notifier";
16
16
 
17
17
  export default async function (pi: ExtensionAPI) {
@@ -0,0 +1,292 @@
1
+ import { visibleWidth } from "@earendil-works/pi-tui";
2
+
3
+ /**
4
+ * Truncate text to `maxWidth` display cells, appending `ellipsis` when text
5
+ * overflows. Unlike `truncateToWidth` from `@earendil-works/pi-tui`, this
6
+ * never injects resets (so caller-applied styling survives truncation) and
7
+ * its CSI parser accepts every escape sequence final, so non-SGR sequences
8
+ * neither swallow visible text nor skew the measured width.
9
+ */
10
+ export function truncateToWidth(
11
+ text: string,
12
+ maxWidth: number,
13
+ ellipsis = "…",
14
+ pad = false,
15
+ ): string {
16
+ if (maxWidth <= 0) return "";
17
+ if (text.length === 0) return pad ? " ".repeat(maxWidth) : "";
18
+
19
+ const ellipsisWidth = visibleWidth(ellipsis);
20
+ if (ellipsisWidth >= maxWidth) {
21
+ const textWidth = visibleWidth(text);
22
+ if (textWidth <= maxWidth) {
23
+ return pad ? text + " ".repeat(maxWidth - textWidth) : text;
24
+ }
25
+
26
+ const clippedEllipsis = truncateFragmentToWidth(ellipsis, maxWidth);
27
+ if (clippedEllipsis.width === 0) {
28
+ return pad ? " ".repeat(maxWidth) : "";
29
+ }
30
+
31
+ return finalizeTruncatedResult(
32
+ "",
33
+ 0,
34
+ clippedEllipsis.text,
35
+ clippedEllipsis.width,
36
+ maxWidth,
37
+ pad,
38
+ );
39
+ }
40
+
41
+ if (isPrintableAscii(text)) {
42
+ if (text.length <= maxWidth) {
43
+ return pad ? text + " ".repeat(maxWidth - text.length) : text;
44
+ }
45
+
46
+ const targetWidth = maxWidth - ellipsisWidth;
47
+ return finalizeTruncatedResult(
48
+ text.slice(0, targetWidth),
49
+ targetWidth,
50
+ ellipsis,
51
+ ellipsisWidth,
52
+ maxWidth,
53
+ pad,
54
+ );
55
+ }
56
+
57
+ const targetWidth = maxWidth - ellipsisWidth;
58
+ let result = "";
59
+ let visibleSoFar = 0;
60
+ let keptWidth = 0;
61
+ let keepContiguousPrefix = true;
62
+ let overflowed = false;
63
+ let exhaustedInput = false;
64
+ const hasAnsi = text.includes("\u001b");
65
+ const hasTabs = text.includes("\t");
66
+
67
+ if (!hasAnsi && !hasTabs) {
68
+ for (const { segment } of segmenter.segment(text)) {
69
+ const width = visibleWidth(segment);
70
+ if (keepContiguousPrefix && keptWidth + width <= targetWidth) {
71
+ result += segment;
72
+ keptWidth += width;
73
+ } else {
74
+ keepContiguousPrefix = false;
75
+ }
76
+
77
+ visibleSoFar += width;
78
+ if (visibleSoFar > maxWidth) {
79
+ overflowed = true;
80
+ break;
81
+ }
82
+ }
83
+ exhaustedInput = !overflowed;
84
+ } else {
85
+ let index = 0;
86
+ let pendingAnsi = "";
87
+ while (index < text.length) {
88
+ const ansi = readAnsiSequence(text, index);
89
+ if (ansi) {
90
+ pendingAnsi += ansi;
91
+ index += ansi.length;
92
+ continue;
93
+ }
94
+
95
+ if (text[index] === "\t") {
96
+ if (keepContiguousPrefix && keptWidth + 3 <= targetWidth) {
97
+ if (pendingAnsi) {
98
+ result += pendingAnsi;
99
+ pendingAnsi = "";
100
+ }
101
+ result += "\t";
102
+ keptWidth += 3;
103
+ } else {
104
+ keepContiguousPrefix = false;
105
+ pendingAnsi = "";
106
+ }
107
+
108
+ visibleSoFar += 3;
109
+ if (visibleSoFar > maxWidth) {
110
+ overflowed = true;
111
+ break;
112
+ }
113
+ index++;
114
+ continue;
115
+ }
116
+
117
+ let end = index;
118
+ while (end < text.length && text[end] !== "\t") {
119
+ const nextAnsi = readAnsiSequence(text, end);
120
+ if (nextAnsi) break;
121
+ end++;
122
+ }
123
+
124
+ for (const { segment } of segmenter.segment(text.slice(index, end))) {
125
+ const width = visibleWidth(segment);
126
+ if (keepContiguousPrefix && keptWidth + width <= targetWidth) {
127
+ if (pendingAnsi) {
128
+ result += pendingAnsi;
129
+ pendingAnsi = "";
130
+ }
131
+ result += segment;
132
+ keptWidth += width;
133
+ } else {
134
+ keepContiguousPrefix = false;
135
+ pendingAnsi = "";
136
+ }
137
+
138
+ visibleSoFar += width;
139
+ if (visibleSoFar > maxWidth) {
140
+ overflowed = true;
141
+ break;
142
+ }
143
+ }
144
+
145
+ if (overflowed) break;
146
+ index = end;
147
+ }
148
+ exhaustedInput = index >= text.length;
149
+ }
150
+
151
+ if (!overflowed && exhaustedInput) {
152
+ return pad ? text + " ".repeat(Math.max(0, maxWidth - visibleSoFar)) : text;
153
+ }
154
+
155
+ return finalizeTruncatedResult(
156
+ result,
157
+ keptWidth,
158
+ ellipsis,
159
+ ellipsisWidth,
160
+ maxWidth,
161
+ pad,
162
+ );
163
+ }
164
+
165
+ const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
166
+
167
+ function isPrintableAscii(text: string): boolean {
168
+ for (let index = 0; index < text.length; index++) {
169
+ const code = text.charCodeAt(index);
170
+ if (code < 0x20 || code > 0x7e) return false;
171
+ }
172
+ return true;
173
+ }
174
+
175
+ function truncateFragmentToWidth(
176
+ text: string,
177
+ maxWidth: number,
178
+ ): { text: string; width: number } {
179
+ if (maxWidth <= 0 || text.length === 0) {
180
+ return { text: "", width: 0 };
181
+ }
182
+
183
+ if (isPrintableAscii(text)) {
184
+ const clipped = text.slice(0, maxWidth);
185
+ return { text: clipped, width: clipped.length };
186
+ }
187
+
188
+ const hasAnsi = text.includes("\u001b");
189
+ const hasTabs = text.includes("\t");
190
+ if (!hasAnsi && !hasTabs) {
191
+ let result = "";
192
+ let width = 0;
193
+
194
+ for (const { segment } of segmenter.segment(text)) {
195
+ const segmentWidth = visibleWidth(segment);
196
+ if (width + segmentWidth > maxWidth) break;
197
+ result += segment;
198
+ width += segmentWidth;
199
+ }
200
+
201
+ return { text: result, width };
202
+ }
203
+
204
+ let result = "";
205
+ let width = 0;
206
+ let index = 0;
207
+ let pendingAnsi = "";
208
+
209
+ while (index < text.length) {
210
+ const ansi = readAnsiSequence(text, index);
211
+ if (ansi) {
212
+ pendingAnsi += ansi;
213
+ index += ansi.length;
214
+ continue;
215
+ }
216
+
217
+ if (text[index] === "\t") {
218
+ if (width + 3 > maxWidth) break;
219
+ if (pendingAnsi) {
220
+ result += pendingAnsi;
221
+ pendingAnsi = "";
222
+ }
223
+ result += "\t";
224
+ width += 3;
225
+ index++;
226
+ continue;
227
+ }
228
+
229
+ let end = index;
230
+ while (end < text.length && text[end] !== "\t") {
231
+ const nextAnsi = readAnsiSequence(text, end);
232
+ if (nextAnsi) break;
233
+ end++;
234
+ }
235
+
236
+ for (const { segment } of segmenter.segment(text.slice(index, end))) {
237
+ const segmentWidth = visibleWidth(segment);
238
+ if (width + segmentWidth > maxWidth) {
239
+ return { text: result, width };
240
+ }
241
+ if (pendingAnsi) {
242
+ result += pendingAnsi;
243
+ pendingAnsi = "";
244
+ }
245
+ result += segment;
246
+ width += segmentWidth;
247
+ }
248
+
249
+ index = end;
250
+ }
251
+
252
+ return { text: result, width };
253
+ }
254
+
255
+ function finalizeTruncatedResult(
256
+ prefix: string,
257
+ prefixWidth: number,
258
+ ellipsis: string,
259
+ ellipsisWidth: number,
260
+ maxWidth: number,
261
+ pad: boolean,
262
+ ): string {
263
+ const width = prefixWidth + ellipsisWidth;
264
+ const result = ellipsis.length > 0 ? `${prefix}${ellipsis}` : prefix;
265
+ return pad ? result + " ".repeat(Math.max(0, maxWidth - width)) : result;
266
+ }
267
+
268
+ function readAnsiSequence(text: string, index: number): string | null {
269
+ const ESCAPE = "\u001b";
270
+ if (text[index] !== ESCAPE) return null;
271
+
272
+ const next = text[index + 1];
273
+ if (next === "[") {
274
+ const code = text.slice(index);
275
+ const pattern = new RegExp(`^${ESCAPE}\\[[0-?]*[ -/]*[@-~]`, "u");
276
+ const match = code.match(pattern);
277
+ return match?.[0] ?? text[index];
278
+ }
279
+
280
+ if (next === "]" || next === "_") {
281
+ const rest = text.slice(index);
282
+ const bel = rest.indexOf("\u0007");
283
+ const st = rest.indexOf("\u001b\\");
284
+ const end = [bel, st]
285
+ .filter((value) => value >= 0)
286
+ .sort((a, b) => a - b)[0];
287
+ if (end === undefined) return text[index];
288
+ return rest.slice(0, end + (end === st ? 2 : 1));
289
+ }
290
+
291
+ return text.slice(index, Math.min(index + 2, text.length));
292
+ }