gloomberb 0.20.5 → 0.20.6

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 (127) hide show
  1. package/README.md +1 -1
  2. package/README.zh-CN.md +1 -1
  3. package/package.json +2 -1
  4. package/src/api-client/data.ts +10 -2
  5. package/src/api-client/hk-tenders.ts +59 -0
  6. package/src/api-client/index.ts +1 -0
  7. package/src/api-client/types/econ.ts +20 -2
  8. package/src/app.tsx +18 -13
  9. package/src/architecture/floating-promise-allowlist.json +313 -0
  10. package/src/cli/commands/market.ts +164 -40
  11. package/src/cli/commands/news-search.ts +22 -7
  12. package/src/cli/commands/overview.ts +12 -6
  13. package/src/cli/commands/ticker.ts +3 -1
  14. package/src/cli/early-command.ts +2 -0
  15. package/src/cli/errors.ts +10 -1
  16. package/src/cli/fx-forward.ts +76 -12
  17. package/src/cli/fx-pair.ts +1 -1
  18. package/src/cli/fx-quote-rate.ts +23 -0
  19. package/src/cli/help.ts +1 -0
  20. package/src/cli/index-roots.ts +5 -4
  21. package/src/cli/index.ts +40 -3
  22. package/src/cli/known-gaps.ts +11 -8
  23. package/src/cli/listing-arg.ts +6 -4
  24. package/src/cli/options.ts +52 -3
  25. package/src/cli/output-file.ts +5 -3
  26. package/src/cli/pane-functions/catalog.ts +15 -0
  27. package/src/cli/pane-functions/function-help.ts +4 -4
  28. package/src/cli/pane-functions/headless.ts +9 -4
  29. package/src/cli/pane-functions/index.ts +6 -4
  30. package/src/cli/pane-functions/resolver.ts +2 -2
  31. package/src/cli/result.ts +21 -2
  32. package/src/cli/spreadsheet-hint.ts +7 -3
  33. package/src/cli/treasury-yields.ts +5 -3
  34. package/src/components/chart/composite/legend.tsx +40 -2
  35. package/src/components/command-bar/workflow/tickers.ts +2 -2
  36. package/src/components/data-table/view.tsx +9 -2
  37. package/src/components/ui/data-table/opentui/index.tsx +11 -4
  38. package/src/components/ui/data-table/opentui/model.ts +8 -6
  39. package/src/components/ui/data-table/types.ts +6 -1
  40. package/src/components/ui/table-layout.ts +38 -1
  41. package/src/docs/snapshot.json +3 -3
  42. package/src/market-data/market/change-basis.ts +9 -5
  43. package/src/market-data/market/dated-previous-close.ts +57 -6
  44. package/src/market-data/quotes/contributions.ts +2 -0
  45. package/src/market-data/quotes/listing-enterprise-value.ts +50 -0
  46. package/src/plugins/builtin/alerts/metric-data.ts +15 -2
  47. package/src/plugins/builtin/backtest/headless.ts +1 -1
  48. package/src/plugins/builtin/cds/model.ts +0 -6
  49. package/src/plugins/builtin/chart-composer/formula.ts +16 -3
  50. package/src/plugins/builtin/chart-composer/headless-schema.ts +2 -0
  51. package/src/plugins/builtin/chart-composer/headless.ts +2 -1
  52. package/src/plugins/builtin/chart-composer/presets.ts +1 -0
  53. package/src/plugins/builtin/cloud/askg/pane.tsx +55 -13
  54. package/src/plugins/builtin/credit-boards/cdx-pane.tsx +20 -7
  55. package/src/plugins/builtin/credit-boards/client.ts +8 -0
  56. package/src/plugins/builtin/credit-boards/headless.ts +4 -1
  57. package/src/plugins/builtin/credit-boards/model.ts +58 -4
  58. package/src/plugins/builtin/credit-boards/series.ts +63 -6
  59. package/src/plugins/builtin/credit-boards/sovr-pane.tsx +3 -2
  60. package/src/plugins/builtin/credit-conditions/headless.ts +24 -6
  61. package/src/plugins/builtin/credit-conditions/index.tsx +1 -1
  62. package/src/plugins/builtin/credit-conditions/model.ts +12 -6
  63. package/src/plugins/builtin/credit-conditions/series.ts +2 -1
  64. package/src/plugins/builtin/econ/calendar-model.ts +41 -7
  65. package/src/plugins/builtin/econ/calendar-source.ts +7 -1
  66. package/src/plugins/builtin/econ/index.tsx +41 -8
  67. package/src/plugins/builtin/econ/types.ts +3 -0
  68. package/src/plugins/builtin/fixed-income/index.tsx +2 -0
  69. package/src/plugins/builtin/fx-matrix/index.tsx +44 -14
  70. package/src/plugins/builtin/help/keybindings-editor.tsx +6 -2
  71. package/src/plugins/builtin/portfolio-list/cli/render.ts +20 -3
  72. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +5 -1
  73. package/src/plugins/builtin/research/headless-schema.ts +4 -3
  74. package/src/plugins/builtin/research/relative-valuation-columns.ts +145 -47
  75. package/src/plugins/builtin/research/relative-valuation-currency.ts +31 -0
  76. package/src/plugins/builtin/research/relative-valuation-headless.ts +25 -8
  77. package/src/plugins/builtin/research/relative-valuation-model.ts +40 -9
  78. package/src/plugins/builtin/research/relative-valuation-pane.tsx +3 -2
  79. package/src/plugins/builtin/research/relative-valuation-peers.ts +2 -2
  80. package/src/plugins/builtin/thirteenf/api.ts +47 -4
  81. package/src/plugins/builtin/ticker-detail/data-panes/historical-prices.tsx +8 -7
  82. package/src/plugins/builtin/ticker-detail/data-panes/history-bars.ts +8 -5
  83. package/src/plugins/builtin/ticker-detail/financials/model.ts +6 -2
  84. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +1 -1
  85. package/src/plugins/builtin/ticker-detail/headless.ts +6 -4
  86. package/src/plugins/builtin/treasury-auctions/cache.ts +36 -2
  87. package/src/plugins/builtin/treasury-auctions/headless.ts +42 -4
  88. package/src/plugins/builtin/treasury-auctions/hk-headless.ts +126 -0
  89. package/src/plugins/builtin/treasury-auctions/hk-view.tsx +347 -0
  90. package/src/plugins/builtin/treasury-auctions/hk.ts +363 -0
  91. package/src/plugins/builtin/treasury-auctions/index.tsx +14 -1
  92. package/src/plugins/builtin/treasury-auctions/model.ts +16 -8
  93. package/src/plugins/builtin/treasury-auctions/pane.tsx +45 -21
  94. package/src/portfolio/collection-name.ts +22 -0
  95. package/src/renderers/dom/data-table/frozen-column.ts +3 -1
  96. package/src/renderers/dom/data-table/index.tsx +27 -9
  97. package/src/renderers/dom/data-table/row.tsx +2 -0
  98. package/src/renderers/electrobun/bun/desktop/backend.ts +27 -24
  99. package/src/renderers/electrobun/bun/desktop/detached-windows.ts +3 -3
  100. package/src/renderers/electrobun/bun/desktop/snapshot-commit.ts +77 -0
  101. package/src/renderers/electrobun/shared/protocol.ts +4 -0
  102. package/src/renderers/electrobun/view/backend-rpc.ts +3 -0
  103. package/src/renderers/electrobun/view/desktop/window/bridge.ts +3 -0
  104. package/src/sources/gloomberb-cloud/normalizers.ts +9 -5
  105. package/src/sources/provider-router/cache.ts +3 -1
  106. package/src/sync/controller.ts +17 -2
  107. package/src/sync/other-window-tabs.ts +32 -1
  108. package/src/sync/react.ts +4 -4
  109. package/src/time-series/bar-spacing.ts +33 -0
  110. package/src/time-series/base-series.ts +21 -3
  111. package/src/time-series/chart-bounds.ts +31 -0
  112. package/src/time-series/field-catalog.ts +17 -0
  113. package/src/time-series/fundamentals.ts +143 -11
  114. package/src/time-series/ice-credit.ts +32 -6
  115. package/src/time-series/resolve.ts +9 -5
  116. package/src/time-series/session-bar.ts +78 -9
  117. package/src/time-series/studies/formula.ts +53 -10
  118. package/src/time-series/studies/pair.ts +18 -7
  119. package/src/time-series/studies/units.ts +49 -2
  120. package/src/time-series/types.ts +12 -0
  121. package/src/types/desktop-window.ts +2 -0
  122. package/src/types/financials.ts +6 -0
  123. package/src/types/headless.ts +8 -0
  124. package/src/utils/cli-output.ts +6 -3
  125. package/src/utils/ebitda.ts +128 -0
  126. package/src/utils/format.ts +1 -1
  127. package/src/utils/shell-word.ts +13 -0
@@ -61,6 +61,9 @@ export interface ImpliedForward {
61
61
  premiumPercent: number;
62
62
  /** The same premium a year: `premiumPercent` × 360 / days. */
63
63
  annualizedPercent: number;
64
+ /** What one unit of the base and of the quote currency grows to over the tenor at its own rate. */
65
+ baseGrowth: number;
66
+ quoteGrowth: number;
64
67
  }
65
68
 
66
69
  /**
@@ -75,7 +78,9 @@ export function impliedForward(
75
78
  base: Pick<CloudShortRate, "dayCountBasis" | "compounding"> & { value: number },
76
79
  quote: Pick<CloudShortRate, "dayCountBasis" | "compounding"> & { value: number; currency: string },
77
80
  ): ImpliedForward {
78
- const forward = spot * shortRateGrowth(quote, days) / shortRateGrowth(base, days);
81
+ const baseGrowth = shortRateGrowth(base, days);
82
+ const quoteGrowth = shortRateGrowth(quote, days);
83
+ const forward = spot * quoteGrowth / baseGrowth;
79
84
  const pointSize = forwardPointSize(quote.currency);
80
85
  const premiumPercent = (forward / spot - 1) * 100;
81
86
  return {
@@ -85,25 +90,32 @@ export function impliedForward(
85
90
  pointSize,
86
91
  premiumPercent,
87
92
  annualizedPercent: premiumPercent * 360 / days,
93
+ baseGrowth,
94
+ quoteGrowth,
88
95
  };
89
96
  }
90
97
 
91
98
  /**
92
99
  * What one unit grows to over `days` at a short rate: simple interest on its
93
- * day count, or, for a rate compounded over 252 business days (CDI),
94
- * (1 + r)^(days / 365), business days taken as 252/365 of the calendar days.
100
+ * day count; for a rate compounded over 252 business days (CDI),
101
+ * (1 + r)^(days / 365), business days taken as 252/365 of the calendar days;
102
+ * for one compounded daily on ACT/365 (ZARONIA), (1 + r / 365)^days.
95
103
  */
96
104
  function shortRateGrowth(rate: Pick<CloudShortRate, "dayCountBasis" | "compounding"> & { value: number }, days: number): number {
97
- return rate.compounding === "business-252"
98
- ? (1 + rate.value / 100) ** (days / 365)
99
- : 1 + (rate.value / 100) * days / rate.dayCountBasis;
105
+ if (rate.compounding === "business-252") return (1 + rate.value / 100) ** (days / 365);
106
+ if (rate.compounding === "daily-365") return (1 + rate.value / 100 / 365) ** days;
107
+ return 1 + (rate.value / 100) * days / rate.dayCountBasis;
100
108
  }
101
109
 
102
- /** `(1 + 3.92% × 92/360)`, or `(1 + 13.65%)^(92/365)` for a compounded rate: one leg of the parity, as `fx --forward` prints it. */
110
+ /**
111
+ * `(1 + 3.92% × 92/360)`, `(1 + 13.65%)^(92/365)` for a rate compounded over
112
+ * business days, `(1 + 7.099%/365)^92` for one compounded daily: one leg of
113
+ * the parity, as `fx --forward` prints it.
114
+ */
103
115
  export function shortRateGrowthText(rate: Pick<CloudShortRate, "dayCountBasis" | "compounding"> & { value: number }, days: number): string {
104
- return rate.compounding === "business-252"
105
- ? `(1 + ${formatRatePercent(rate.value)})^(${days}/365)`
106
- : `(1 + ${formatRatePercent(rate.value)} × ${days}/${rate.dayCountBasis})`;
116
+ if (rate.compounding === "business-252") return `(1 + ${formatRatePercent(rate.value)})^(${days}/365)`;
117
+ if (rate.compounding === "daily-365") return `(1 + ${formatRatePercent(rate.value)}/365)^${days}`;
118
+ return `(1 + ${formatRatePercent(rate.value)} × ${days}/${rate.dayCountBasis})`;
107
119
  }
108
120
 
109
121
  /** A rate the forward can use: listed for the currency, with a value. */
@@ -141,8 +153,60 @@ export function formatForwardPoints(points: number): string {
141
153
  return `${points >= 0 ? "+" : ""}${points.toFixed(1)}`;
142
154
  }
143
155
 
144
- /** `TIIE 28d 6.776% (Banco de México, 2026-10-20; ACT/360)`, `CDI 13.65% (Banco Central do Brasil, 2026-11-05; BUS/252 compounded)`. */
156
+ /**
157
+ * `TIIE 28d 6.776% (Banco de México, 2026-10-20; ACT/360)`, `CDI 13.65% (Banco Central do Brasil, 2026-11-05; BUS/252 compounded)`,
158
+ * `ZARONIA 7.099% (South African Reserve Bank, 2026-11-05; ACT/365 compounded daily)`.
159
+ */
145
160
  export function describeShortRate(rate: CloudShortRate & { value: number }): string {
146
- const basis = rate.compounding === "business-252" ? "BUS/252 compounded" : `ACT/${rate.dayCountBasis}`;
161
+ const basis = rate.compounding === "business-252" ? "BUS/252 compounded"
162
+ : rate.compounding === "daily-365" ? "ACT/365 compounded daily" : `ACT/${rate.dayCountBasis}`;
147
163
  return `${rate.name} ${formatRatePercent(rate.value)} (${rate.publisher}, ${rate.asOf ?? "undated"}; ${basis})`;
148
164
  }
165
+
166
+ /**
167
+ * The carry of a forward on an amount of the pair's base currency, above
168
+ * zero: the forward points on it over the tenor, in the quote currency. The
169
+ * side that holds the currency whose rate earns more over the tenor (the
170
+ * larger growth factor) earns it: with the forward above spot, the seller of
171
+ * the base currency forward (short the pair); below spot, the buyer (long).
172
+ * A forward at spot has no carry.
173
+ */
174
+ export interface ForwardCarry {
175
+ /** The amount, in the pair's base currency. */
176
+ amount: number;
177
+ /** Amount × |forward - spot|, in the quote currency: what one side pays the other. */
178
+ value: number;
179
+ /** The side that earns it; null when the forward is at spot. */
180
+ earnedBy: "long" | "short" | null;
181
+ /** The currency whose rate earns more over the tenor, from the two growth factors; null when they are equal. */
182
+ higher: "base" | "quote" | null;
183
+ }
184
+
185
+ export function forwardCarry(
186
+ amount: number,
187
+ implied: Pick<ImpliedForward, "spot" | "forward" | "baseGrowth" | "quoteGrowth">,
188
+ ): ForwardCarry {
189
+ const difference = implied.forward - implied.spot;
190
+ return {
191
+ amount,
192
+ value: Math.abs(amount * difference),
193
+ earnedBy: difference > 0 ? "short" : difference < 0 ? "long" : null,
194
+ higher: implied.quoteGrowth > implied.baseGrowth ? "quote" : implied.quoteGrowth < implied.baseGrowth ? "base" : null,
195
+ };
196
+ }
197
+
198
+ /**
199
+ * Who earns the carry and who pays it, by side of the pair: `Short USD/MXN
200
+ * (selling USD forward) earns it and long USD/MXN (buying USD forward) pays
201
+ * it: MXN's rate earns more over the 30 days.` A forward at spot has none.
202
+ */
203
+ export function describeCarrySides(carry: ForwardCarry, base: string, quote: string, days: number): string {
204
+ if (carry.earnedBy == null || carry.higher == null) {
205
+ return `No carry: at these rates ${base} and ${quote} earn the same over the ${days} days, so the forward is at spot.`;
206
+ }
207
+ const short = `short ${base}/${quote} (selling ${base} forward)`;
208
+ const long = `long ${base}/${quote} (buying ${base} forward)`;
209
+ const [earns, pays] = carry.earnedBy === "short" ? [short, long] : [long, short];
210
+ const higher = carry.higher === "quote" ? quote : base;
211
+ return `${earns.charAt(0).toUpperCase()}${earns.slice(1)} earns it and ${pays} pays it: ${higher}'s rate earns more over the ${days} days.`;
212
+ }
@@ -161,7 +161,7 @@ export function parseFxArgs(words: readonly string[], baseCurrency: string): FxA
161
161
  * An amount in its currency's minor units, grouped (1,234.50 EUR; 1,235 JPY).
162
162
  * One too small for them keeps six significant figures instead of reading 0.
163
163
  */
164
- function formatFxAmount(amount: number, currency: string): string {
164
+ export function formatFxAmount(amount: number, currency: string): string {
165
165
  const digits = currencyMinorDigits(currency);
166
166
  const rounded = Number(amount.toFixed(digits));
167
167
  if (rounded === 0 && amount !== 0) return `${formatFxRate(amount)} ${currency}`;
@@ -160,6 +160,29 @@ async function metalFromFuture(
160
160
  };
161
161
  }
162
162
 
163
+ /**
164
+ * The rate's move on the day, as `quote` gives its pair's: the rate against
165
+ * the same reading at the previous daily closes (the pair's own close, or
166
+ * each dollar pair's for a cross), in percent. Null for a rate priced from a
167
+ * future, or when a close is missing.
168
+ */
169
+ export function fxQuoteRateMove(rate: FxQuoteRate): { percent: number; previousRate: number } | null {
170
+ if (rate.derivedFrom) return null;
171
+ const closes = rate.quotes.map(({ quote }) => quote.previousClose);
172
+ if (!closes.every(isUsableRate)) return null;
173
+ let previousRate: number;
174
+ if (rate.viaUsd) {
175
+ // Each dollar pair as USD per unit, as the cross is read: EURUSD=X as sent, USDJPY=X inverted.
176
+ const [from, into] = rate.quotes.map(({ symbol }, index) => symbol.startsWith("USD") ? 1 / closes[index]! : closes[index]!) as [number, number];
177
+ previousRate = from / into;
178
+ } else {
179
+ // The pair's own quote, inverted when the rate is (JPY/EUR read from EURJPY=X).
180
+ previousRate = rate.rate === rate.quotes[0]!.figure ? closes[0]! : 1 / closes[0]!;
181
+ }
182
+ const percent = (rate.rate / previousRate - 1) * 100;
183
+ return Number.isFinite(percent) ? { percent, previousRate } : null;
184
+ }
185
+
163
186
  /** How long past its feed's delay a weekday FX rate stays current, counted while the FX market trades. */
164
187
  const FX_STALE_AFTER_DELAY_MS = 15 * 60_000;
165
188
 
package/src/cli/help.ts CHANGED
@@ -47,6 +47,7 @@ const GLOBAL_OPTIONS: Array<[string, string]> = [
47
47
  ["--json", "Print the full result as JSON"],
48
48
  ["--csv", "Print rows as CSV under the columns the text shows; fn reports and fundamentals put each table under # section: and end with # source lines"],
49
49
  ["--ndjson", "Print one JSON object per table row"],
50
+ ["--output <path>, --out <path>", "Write a --csv, --json or --ndjson export to this file in UTF-8, and print where it went (a redirect is UTF-16 in Windows PowerShell 5.1)"],
50
51
  ["--limit <n>", "Show at most n rows, the first n as printed"],
51
52
  ["--tail <n>", "Show the newest n rows of a dated series (history, fred, econ) in their printed order, or the last n of another list"],
52
53
  ["--refresh", "Fetch fresh data instead of reading the cache"],
@@ -1,4 +1,5 @@
1
1
  import { indexRootFor, type IndexRoot } from "../tickers/index-roots";
2
+ import { commandWord } from "../utils/shell-word";
2
3
 
3
4
  /** A broker's code for an index: VIX.X and $VIX.X as thinkorswim writes it, $VIX as Schwab does. */
4
5
  export interface BrokerIndexCode extends IndexRoot {
@@ -26,12 +27,12 @@ export function brokerIndexReadAs(code: BrokerIndexCode): string {
26
27
  return `Read ${code.typed} as ${code.symbol} (${code.name}).`;
27
28
  }
28
29
 
29
- /** "^VIX Cboe Volatility Index (try: gloom quote ^VIX)", under a bare root that found nothing. */
30
+ /** `^VIX Cboe Volatility Index (try: gloom quote "^VIX")`, under a bare root that found nothing. */
30
31
  export function indexRootTryLine(root: IndexRoot, command = "quote"): string {
31
- return `${root.symbol} ${root.name} (try: gloom ${command} ${root.symbol})`;
32
+ return `${root.symbol} ${root.name} (try: gloom ${command} ${commandWord(root.symbol)})`;
32
33
  }
33
34
 
34
- /** "also ^MOVE ICE BofA MOVE Index (gloom quote ^MOVE)", under a bare root that quoted another instrument. */
35
+ /** `also ^MOVE ICE BofA MOVE Index (gloom quote "^MOVE")`, under a bare root that quoted another instrument. */
35
36
  export function indexRootAlsoLine(root: IndexRoot, command = "quote"): string {
36
- return `also ${root.symbol} ${root.name} (gloom ${command} ${root.symbol})`;
37
+ return `also ${root.symbol} ${root.name} (gloom ${command} ${commandWord(root.symbol)})`;
37
38
  }
package/src/cli/index.ts CHANGED
@@ -2,7 +2,9 @@ import { VERSION } from "../version";
2
2
  import type { CliCommandContext, CliCommandDef, CliDispatchResult, CliLaunchRequest } from "../types/plugin";
3
3
  import type { LoadedExternalPlugin } from "../plugins/loader";
4
4
  import { loadCliConfigIfAvailable } from "./context";
5
- import { parseCliGlobalArgs } from "./options";
5
+ import { checkCliOutputFormat, commandOwnsOutput, parseCliGlobalArgs, type CliGlobalOptions } from "./options";
6
+ import { checkOutputPath, resolveOutputPath, writeOutputFile } from "./output-file";
7
+ import { printCliResult, takeCliFileExport } from "./result";
6
8
  import {
7
9
  buildCliCommandRegistry,
8
10
  createCliCommandContext,
@@ -189,7 +191,7 @@ export function createCoreCliCommands(
189
191
  "fn HP AAPL",
190
192
  "fn ANR SAN:EPA",
191
193
  "fn CBR --json",
192
- "fn WEI --csv --section europe > europe.csv",
194
+ "fn WEI --csv --section europe --output europe.csv",
193
195
  "fn RV NEE,FSLR --csv --output rv.csv",
194
196
  "fn 13F AAPL --view=ticker-holdings",
195
197
  "fn OVME --spot 100 --strike 100 --days 30 --volatility 25",
@@ -413,7 +415,8 @@ export { buildSearchReport, searchCandidatesForCli };
413
415
  export async function dispatchCli(args: string[], options: DispatchCliOptions = {}): Promise<CliDispatchResult> {
414
416
  let parsed;
415
417
  try {
416
- parsed = parseCliGlobalArgs(args);
418
+ // --output without a format is refused once the command is known: a plugin's own --output is not the export's.
419
+ parsed = parseCliGlobalArgs(args, { deferOutputCheck: true });
417
420
  } catch (error) {
418
421
  printCliError(asUsageError(error), inferCliErrorOptions(args));
419
422
  process.exitCode = 1;
@@ -438,6 +441,15 @@ export async function dispatchCli(args: string[], options: DispatchCliOptions =
438
441
  if (!resolved) {
439
442
  return { kind: "unhandled" };
440
443
  }
444
+ try {
445
+ // A plugin command with its own --output keeps it: the global flag yields, as it does to `fn` and `shot`.
446
+ if (parsed.options.output !== undefined && commandOwnsOutput(resolved.command)) parsed = parseCliGlobalArgs(args, { ownsOutput: true });
447
+ checkCliOutputFormat(parsed);
448
+ } catch (error) {
449
+ printCliError(asUsageError(error), parsed.options);
450
+ process.exitCode = 1;
451
+ return { kind: "handled" };
452
+ }
441
453
 
442
454
  // The overview includes installed commands; one built-in command's help only
443
455
  // needs that command. An unknown help topic may belong to an installed plugin.
@@ -459,13 +471,19 @@ export async function dispatchCli(args: string[], options: DispatchCliOptions =
459
471
  : foldCommandArgs(resolved.command, parsed.args.slice(1), parsed.literalStart - 1);
460
472
  try {
461
473
  if (!helpOnly && resolved.builtin) checkCliCommandOptions(resolved.command, commandArgs, parsed.literalStart - 1);
474
+ // The file --output names, checked before the command runs so a path that cannot be written fails at once.
475
+ const outputPath = parsed.options.output !== undefined && !helpOnly ? resolveOutputPath(parsed.options.output) : null;
476
+ const replacing = outputPath ? await checkOutputPath(outputPath) : false;
477
+ takeCliFileExport();
462
478
  // What it answers from a saved copy, its refresh having failed, its closing line says.
463
479
  const result = await collectSavedCopies(() => Promise.resolve(target.command.execute(
464
480
  commandArgs,
465
481
  createCliCommandContext(target.ownerId, registry, parsed.options, commandArgs),
466
482
  )));
483
+ if (outputPath) await saveFileExport(outputPath, parsed.options, resolved.command.name, replacing);
467
484
  return normalizeCliDispatchResult(result);
468
485
  } catch (error) {
486
+ takeCliFileExport();
469
487
  // A coin typed without its quote currency (USDT) is named by its one symbol (USDT-USD) in the hint.
470
488
  if (parsed.options.format !== "json") await primeBoardCoins([error instanceof Error ? error.message : String(error)]);
471
489
  printCliError(error, parsed.options, { command: resolved.command.name, args: commandArgs,
@@ -475,6 +493,25 @@ export async function dispatchCli(args: string[], options: DispatchCliOptions =
475
493
  }
476
494
  }
477
495
 
496
+ /**
497
+ * Writes the export a command printed to the file `--output` named, in
498
+ * UTF-8 without a byte order mark, and says where it went: `Saved <path>`,
499
+ * `Replaced <path>` over a file that was there, or in JSON its envelope. A
500
+ * command that printed no export (its result failed, or it has no table to
501
+ * export) writes no file and says so.
502
+ */
503
+ async function saveFileExport(path: string, options: CliGlobalOptions, command: string, replacing: boolean): Promise<void> {
504
+ const written = takeCliFileExport();
505
+ if (written === null) {
506
+ if (process.exitCode) return;
507
+ throw new Error(`${command} printed no ${options.format.toUpperCase()} export; nothing was written to ${path}.`);
508
+ }
509
+ await writeOutputFile(path, `${written}\n`);
510
+ printCliResult({ data: { output: path, format: options.format, replaced: replacing } },
511
+ { ...options, output: undefined, format: options.format === "json" ? "json" : "text" },
512
+ { text: () => `${replacing ? "Replaced" : "Saved"} ${path}` });
513
+ }
514
+
478
515
  /** Explains why dispatch found no command in `args`, suggesting the closest one. */
479
516
  export async function failUnknownCliCommand(args: string[], options: DispatchCliOptions = {}): Promise<never> {
480
517
  let token = args[0] ?? "";
@@ -2,6 +2,7 @@ import { listingSuffixExchange } from "../sources/listing-symbols";
2
2
  import { kindFromListingSyntax } from "../tickers/instrument-kind";
3
3
  import { macroReleaseTopic } from "../plugins/builtin/shared/macro-releases";
4
4
  import { parsePublicTickerKey } from "../utils/exchanges";
5
+ import { commandWord } from "../utils/shell-word";
5
6
  import { listingAbroadVenue } from "../utils/sec";
6
7
  import { nimCommand } from "./bank-section";
7
8
  import { treasuryYieldLine, treasuryYieldTenor } from "./treasury-yields";
@@ -174,8 +175,8 @@ const BANK_FIGURES_TOPIC = {
174
175
  * command or a function. One example, writing a file.
175
176
  */
176
177
  function exportLine(symbol = "LMT"): string {
177
- return `Export: add --csv or --json to any command to print its result as CSV or JSON, e.g. gloom history ${symbol} --csv > ${
178
- symbol.toLowerCase().replace(/[^a-z0-9]+/g, "-")}.csv`;
178
+ return `Export: add --csv or --json to any command to print its result as CSV or JSON, and --output <file> to write it to a file in UTF-8, e.g. gloom history ${
179
+ commandWord(symbol)} --csv --output ${symbol.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")}.csv`;
179
180
  }
180
181
 
181
182
  const EXPORT_POINTER = {
@@ -352,13 +353,15 @@ const COMMAND_POINTERS: ReadonlyArray<{
352
353
  },
353
354
  {
354
355
  // A currency forward, not a forward rate on a yield curve, forward guidance, a forward P/E or the forward
355
- // inflation series: a query that says more than "forward" has to name FX.
356
- names: ["forward", "forwards", "fwd", "fwds"],
357
- words: ["rate", "rates", "implied", "hedge", "hedging", "cost", "costs", "premium", "interest", "1w", "2w", "30d", "1m", "3m",
356
+ // inflation series: a query that says more than "forward" has to name FX. A hedge or a carry alone is the
357
+ // forward's too (a hedge fund or a carry cost is not).
358
+ names: ["forward", "forwards", "fwd", "fwds", "hedge", "hedging", "carry"],
359
+ words: ["rate", "rates", "implied", "cost", "costs", "premium", "interest", "1w", "2w", "30d", "1m", "3m",
358
360
  "6m", "1y"],
359
- qualifiers: ["fx", "currency", "currencies", "point", "points", "pips", "cip", "covered", "parity", "outright",
360
- "usd", "mxn", "eur", "gbp", "usdmxn", "eurusd", "gbpusd", "eurmxn", "peso", "dollar", "euro", "sterling"],
361
- line: "FX forwards implied by both currencies' short rates (covered interest parity), with forward points and the hedge cost: gloom fx USD/MXN --forward 30d",
361
+ qualifiers: ["fx", "currency", "currencies", "point", "points", "pips", "cip", "covered", "parity", "outright", "trade",
362
+ "usd", "mxn", "eur", "gbp", "zar", "try", "usdmxn", "eurusd", "gbpusd", "eurmxn", "usdzar", "usdtry", "peso", "dollar", "euro",
363
+ "sterling", "rand", "lira"],
364
+ line: "FX forwards implied by both currencies' short rates (covered interest parity), with forward points, the hedge cost and, for an amount, the carry and who earns it: gloom fx 5000000 USD/MXN --forward 30d",
362
365
  },
363
366
  {
364
367
  names: ["defi", "tvl", "tvls", "total value locked", "on-chain", "onchain", "aave", "lido", "eigenlayer", "morpho"],
@@ -70,6 +70,7 @@ import { listingSuffixCandidate, listingSuffixVenue, tickerHasListingSuffix } fr
70
70
  import { isCurrencyPairListing } from "../utils/fx-market-hours";
71
71
  import { coinElsewhereNote, notTheCoinNote } from "./commands/crypto-hints";
72
72
  import { fredSeriesArgument, fredSeriesNotListing } from "../series/fred-argument";
73
+ import { commandWord } from "../utils/shell-word";
73
74
 
74
75
  /** The `--exchange` option of every command that takes a ticker. */
75
76
  export const EXCHANGE_OPTION = {
@@ -654,9 +655,9 @@ interface OtherListingsMessage {
654
655
  * --range 5Y` keeps the options. Null where the request names listings alone.
655
656
  */
656
657
  function retryCommand(request: Pick<ListingDataRequest, "command" | "retry">, key: string): string | null {
657
- if (request.retry !== undefined) return request.retry?.(key) ?? null;
658
+ if (request.retry !== undefined) return request.retry?.(commandWord(key)) ?? null;
658
659
  const [command, ...options] = request.command.split(" ");
659
- return ["gloom", command, key, ...options].join(" ");
660
+ return ["gloom", command, commandWord(key), ...options].join(" ");
660
661
  }
661
662
 
662
663
  /**
@@ -1745,8 +1746,9 @@ export function listingFields(saved: Pick<SavedListingName, "key" | "symbol" | "
1745
1746
 
1746
1747
  /** The listing a saved ticker row is, as a collection command names it after adding or removing it. */
1747
1748
  export function savedListingName(ticker: TickerRecord): SavedListingName {
1748
- const { symbol } = parsePublicTickerKey(ticker.metadata.ticker);
1749
- const exchange = canonicalExchange(ticker.metadata.exchange);
1749
+ const { symbol, exchange: stored } = parsePublicTickerKey(ticker.metadata.ticker);
1750
+ // A row stored under its venue (ASML:XAMS) with none beside it is that venue's listing.
1751
+ const exchange = canonicalExchange(ticker.metadata.exchange) || stored || "";
1750
1752
  const key = exchange ? `${symbol}:${exchange}` : symbol;
1751
1753
  // A row saved without a company carries its symbol as the name.
1752
1754
  const typed = ticker.metadata.name?.trim();
@@ -19,6 +19,14 @@ export interface CliGlobalOptions {
19
19
  refresh: boolean;
20
20
  dryRun: boolean;
21
21
  yes: boolean;
22
+ /**
23
+ * `--output <path>` (or `--out`): the file a `--csv`, `--json` or
24
+ * `--ndjson` export is written to, in UTF-8, in place of stdout. A shell's
25
+ * redirect is not always UTF-8: Windows PowerShell 5.1 writes `>` as
26
+ * UTF-16. `fn`, `shot` and a plugin command that declares its own
27
+ * `--output` read the flag themselves.
28
+ */
29
+ output?: string;
22
30
  }
23
31
 
24
32
  export interface ParsedCliArgs {
@@ -55,6 +63,8 @@ function parseRowCount(flag: "--limit" | "--tail", value: string | undefined): n
55
63
 
56
64
  /** Commands whose own `--width` is a size in pixels, so it is not the table width. */
57
65
  const PIXEL_WIDTH_COMMANDS = new Set(["shot", "screenshot"]);
66
+ /** Commands whose own `--output` names their file: a function's report, a capture's PNG. */
67
+ const OWN_OUTPUT_COMMANDS = new Set(["fn", "function", "shot", "screenshot"]);
58
68
  const MIN_TABLE_WIDTH = 20;
59
69
 
60
70
  function parseColumnCount(value: string | undefined): number {
@@ -65,23 +75,44 @@ function parseColumnCount(value: string | undefined): number {
65
75
  return parsed;
66
76
  }
67
77
 
78
+ function parseOutputFile(value: string | undefined): string {
79
+ if (!value?.trim() || value.startsWith("--")) throw new Error("--output needs a file to write, such as --csv --output report.csv.");
80
+ return value;
81
+ }
82
+
68
83
  /** The first word that is not an option or the value of one: the command the arguments are for. */
69
84
  function commandWord(rawArgs: readonly string[]): string | undefined {
70
85
  for (let index = 0; index < rawArgs.length; index += 1) {
71
86
  const arg = rawArgs[index]!;
72
87
  if (arg === "--") return rawArgs[index + 1];
73
- if (arg === "--limit" || arg === "--tail" || arg === "--width") index += 1;
88
+ if (arg === "--limit" || arg === "--tail" || arg === "--width" || arg === "--output" || arg === "--out") index += 1;
74
89
  else if (!arg.startsWith("-")) return arg;
75
90
  }
76
91
  return undefined;
77
92
  }
78
93
 
79
- export function parseCliGlobalArgs(rawArgs: string[]): ParsedCliArgs {
94
+ /**
95
+ * Whether a command reads `--output` itself: `fn` and `shot`, and a plugin
96
+ * command whose options declare one. The global flag yields to it.
97
+ */
98
+ export function commandOwnsOutput(command: { name: string; help?: { options?: readonly { flags: string }[] } }): boolean {
99
+ return OWN_OUTPUT_COMMANDS.has(command.name.toLowerCase())
100
+ || (command.help?.options ?? []).some((option) => /(^|[\s,])--(output|out)\b/.test(option.flags));
101
+ }
102
+
103
+ /**
104
+ * The global flags out of `rawArgs`. `ownsOutput` says the command reads
105
+ * `--output` itself (commandOwnsOutput), which a built-in's name tells
106
+ * before its plugin is loaded; `deferOutputCheck` leaves refusing `--output`
107
+ * without an export format to `checkCliOutputFormat`, once that is known.
108
+ */
109
+ export function parseCliGlobalArgs(rawArgs: string[], settings: { ownsOutput?: boolean; deferOutputCheck?: boolean } = {}): ParsedCliArgs {
80
110
  const options: CliGlobalOptions = { ...DEFAULT_CLI_OPTIONS };
81
111
  const args: string[] = [];
82
112
  let help = false;
83
113
  let literalStart: number | null = null;
84
114
  const ownsWidth = PIXEL_WIDTH_COMMANDS.has(commandWord(rawArgs)?.toLowerCase() ?? "");
115
+ const ownsOutput = settings.ownsOutput ?? OWN_OUTPUT_COMMANDS.has(commandWord(rawArgs)?.toLowerCase() ?? "");
85
116
 
86
117
  for (let index = 0; index < rawArgs.length; index += 1) {
87
118
  const arg = rawArgs[index]!;
@@ -143,6 +174,15 @@ export function parseCliGlobalArgs(rawArgs: string[]): ParsedCliArgs {
143
174
  options.width = parseColumnCount(arg.slice("--width=".length));
144
175
  continue;
145
176
  }
177
+ if (!ownsOutput && (arg === "--output" || arg === "--out")) {
178
+ index += 1;
179
+ options.output = parseOutputFile(rawArgs[index]);
180
+ continue;
181
+ }
182
+ if (!ownsOutput && (arg.startsWith("--output=") || arg.startsWith("--out="))) {
183
+ options.output = parseOutputFile(arg.slice(arg.indexOf("=") + 1));
184
+ continue;
185
+ }
146
186
  if (arg === "--limit" || arg === "--tail") {
147
187
  index += 1;
148
188
  options[arg === "--limit" ? "limit" : "tail"] = parseRowCount(arg, rawArgs[index]);
@@ -162,5 +202,14 @@ export function parseCliGlobalArgs(rawArgs: string[]): ParsedCliArgs {
162
202
  throw new Error("Use --limit or --tail, not both: --limit keeps the first rows, --tail the newest.");
163
203
  }
164
204
 
165
- return { args, options, help, literalStart: literalStart ?? args.length };
205
+ const parsed = { args, options, help, literalStart: literalStart ?? args.length };
206
+ if (!settings.deferOutputCheck) checkCliOutputFormat(parsed);
207
+ return parsed;
208
+ }
209
+
210
+ /** `--output` writes an export: refused without --csv, --json or --ndjson. */
211
+ export function checkCliOutputFormat(parsed: Pick<ParsedCliArgs, "options" | "help">): void {
212
+ if (parsed.options.output !== undefined && parsed.options.format === "text" && !parsed.help) {
213
+ throw new Error("--output writes an export: add --csv, --json or --ndjson, such as --csv --output report.csv.");
214
+ }
166
215
  }
@@ -52,17 +52,19 @@ function isNotAFile(path: string): Error {
52
52
  /**
53
53
  * Fails when `path` names a folder, a link or anything else that is not a
54
54
  * plain file (a device, a pipe): checked before a report loads, so it stops
55
- * at once, and again as the file is opened.
55
+ * at once, and again as the file is opened. True when a file is there to be
56
+ * replaced.
56
57
  */
57
- export async function checkOutputPath(path: string, platform: NodeJS.Platform = process.platform): Promise<void> {
58
+ export async function checkOutputPath(path: string, platform: NodeJS.Platform = process.platform): Promise<boolean> {
58
59
  const existing = await lstat(path).catch(() => {
59
60
  // Intentional ignore: a path that does not exist yet is the usual case, and writing reports any real failure.
60
61
  return null;
61
62
  });
62
- if (!existing) return;
63
+ if (!existing) return false;
63
64
  if (existing.isDirectory()) throw isFolder(path, platform === "win32" ? win32 : posix);
64
65
  if (existing.isSymbolicLink()) throw isLink(path);
65
66
  if (!existing.isFile()) throw isNotAFile(path);
67
+ return true;
66
68
  }
67
69
 
68
70
  /**
@@ -665,10 +665,25 @@ function optionDescription(option: PaneFunctionOptionDef): string {
665
665
  const parts = [option.description.replace(/\.$/, "")];
666
666
  // An enum that also reads other values (a bar size of any length) lists its values as examples.
667
667
  if (choices.join("|").length > MAX_INLINE_CHOICES) parts.push(`${option.list ? "Each one of" : option.normalize ? "Such as" : "One of"} ${choices.join(", ")}`);
668
+ const bounds = optionBounds(option);
669
+ if (bounds) parts.push(bounds);
668
670
  if (option.defaultValue !== undefined && option.defaultValue !== "") parts.push(`Default ${String(option.defaultValue)}`);
669
671
  return `${parts.join(". ")}.`;
670
672
  }
671
673
 
674
+ /**
675
+ * The range a number option takes (`From 30 to 1,100`), so its limits are read
676
+ * before a value is refused, unless its description already names them.
677
+ */
678
+ function optionBounds(option: PaneFunctionOptionDef): string | null {
679
+ if (option.type !== "integer") return null;
680
+ const named = (value: number) => [String(value), value.toLocaleString("en-US")].some((text) => new RegExp(`(^|[^\\d,.])${text.replace(/[.,]/g, "\\$&")}(?!\\d|[,.]\\d)`).test(option.description));
681
+ const min = option.minimum != null && !named(option.minimum) ? option.minimum.toLocaleString("en-US") : null;
682
+ const max = option.maximum != null && !named(option.maximum) ? option.maximum.toLocaleString("en-US") : null;
683
+ if (min && max) return `From ${min} to ${max}`;
684
+ return min ? `At least ${min}` : max ? `At most ${max}` : null;
685
+ }
686
+
672
687
  /** A limitation as a sentence, so one does not run into the next: with a full stop unless it ends in one. */
673
688
  export function limitationSentence(text: string): string {
674
689
  const trimmed = text.trim();
@@ -993,15 +993,15 @@ export const FUNCTION_HELP: Readonly<Record<string, FunctionHelp>> = {
993
993
  bloomberg: ["WIRP", "FFIP"],
994
994
  },
995
995
  CRD: {
996
- summary: "ICE BofA option-adjusted spreads: US investment grade and high yield by rating, and euro high yield, with the day's change.",
997
- usage: ["CRD", "CRD --region euro"],
996
+ summary: "ICE BofA option-adjusted spreads: US investment grade and high yield by rating, euro high yield, and emerging markets and Asia corporates, with the day's change.",
997
+ usage: ["CRD", "CRD --region euro", "CRD --region asia,em"],
998
998
  keys: [OPEN],
999
999
  data: same("Daily close, published the next day"),
1000
1000
  bloomberg: ["CRD"],
1001
1001
  },
1002
1002
  AUCT: {
1003
- summary: "Bill, note, bond and TIPS auction results: high rate (a bill's investment rate, with its discount rate), the stop-out's spread against the published average (the median from Nov 1998), bid-to-cover, indirect, direct and dealer takedown and size, with the auctions announced next. The after view ranks each auction's B/C, indirect and dealer share against its tenor's last 24 and gives the Treasury yield's move 1, 5 and 20 sessions later. Searchable by benchmark (10Y) or CUSIP; history reaches back to 1979 (--history-days all).",
1004
- usage: ["AUCT", "AUCT 10Y", "AUCT 91282CRF0", "AUCT 7Y --history-days 3650 --view after --sort btc-pctl"],
1003
+ summary: "Bill, note, bond and TIPS auction results: high rate (a bill's investment rate, with its discount rate), the stop-out's spread against the published average (the median from Nov 1998), bid-to-cover, indirect, direct and dealer takedown and size, with the auctions announced next. The after view ranks each auction's B/C, indirect and dealer share against its tenor's last 24 and gives the Treasury yield's move 1, 5 and 20 sessions later. Searchable by benchmark (10Y) or CUSIP; history reaches back to 1979 (--history-days all). --market hk lists Hong Kong's EF Bills, EF Notes and Government Bond tenders from HKMA's Open API (Source: HKMA; published monthly): issue date, tenor, average accepted yield, B/C and size.",
1004
+ usage: ["AUCT", "AUCT 10Y", "AUCT 91282CRF0", "AUCT 7Y --history-days 3650 --view after --sort btc-pctl", "AUCT --market hk", "AUCT HKGB 10Y"],
1005
1005
  keys: [SEARCH, key("f", "ilter"), OPEN],
1006
1006
  data: same("Daily, after each auction"),
1007
1007
  bloomberg: ["AUCT"],
@@ -598,11 +598,12 @@ function renderSeries(result: HeadlessSeriesResult): string[] {
598
598
  const latest = [...series.points].reverse().find((point) => (
599
599
  point.value != null || point.close != null
600
600
  ));
601
+ // N/M stands for the period the series would end on, not an older value before it.
601
602
  return {
602
603
  series: series.label,
603
604
  name: series.name?.trim() || null,
604
- latest: latest ? seriesLatestDate(series, latest.date) : "-",
605
- value: seriesValue(series, latest?.value ?? latest?.close ?? null),
605
+ latest: series.notMeaningful ? series.notMeaningful.asOf : latest ? seriesLatestDate(series, latest.date) : "-",
606
+ value: series.notMeaningful ? "N/M" : seriesValue(series, latest?.value ?? latest?.close ?? null),
606
607
  unit: series.unit?.trim() ? currencyRateUnitText(series.unit.trim()) : null,
607
608
  points: observationCount(series),
608
609
  };
@@ -617,6 +618,9 @@ function renderSeries(result: HeadlessSeriesResult): string[] {
617
618
  { key: "points", header: "Points", align: "right" },
618
619
  ];
619
620
  const lines = [renderRows(rows, columns, undefined)];
621
+ const notMeaningful = result.series.flatMap((series) => series.notMeaningful
622
+ ? [`${series.label}: N/M, ${series.notMeaningful.reason.charAt(0).toLowerCase()}${series.notMeaningful.reason.slice(1)}.`] : []);
623
+ if (notMeaningful.length) lines.push("", ...notMeaningful.map((line) => wrapToTerminal(line)));
620
624
  if (result.stats) {
621
625
  lines.push("", renderSection("Statistics"), renderEntries(statisticsEntries(result.stats)));
622
626
  }
@@ -963,7 +967,8 @@ function resultRowCount(definition: HeadlessPaneDefinition, result: HeadlessPane
963
967
  count + ("rows" in section && section.rows ? section.rows.length : section.entries.length)
964
968
  ), 0);
965
969
  case "series":
966
- return (result as HeadlessSeriesResult).series.reduce((count, series) => count + observationCount(series), 0);
970
+ // An N/M is a reading: the report has something to say for the series.
971
+ return (result as HeadlessSeriesResult).series.reduce((count, series) => count + Math.max(observationCount(series), series.notMeaningful ? 1 : 0), 0);
967
972
  case "snapshot":
968
973
  return (result as HeadlessSnapshotResult).items.length;
969
974
  default: {
@@ -1049,7 +1054,7 @@ export async function buildHeadlessFunctionReport(
1049
1054
  target: resolved.token,
1050
1055
  capabilityId: resolved.capability.id,
1051
1056
  symbols,
1052
- options: resolved.options,
1057
+ options: { ...resolved.options, ...loaded.result.appliedOptions },
1053
1058
  rowCount,
1054
1059
  empty: rowCount === 0,
1055
1060
  complete,
@@ -36,7 +36,7 @@ import {
36
36
  ListingArgError, listingFateLoader, listingReadNotes, loadForListing, loadListingQuoteAnswer, quotedListingChoiceNotes, refuseMovedListing,
37
37
  } from "../listing-arg";
38
38
  import { notATickerStop } from "../company-name-hint";
39
- import { CLI_ERROR_CODE, failUnreachable, failWithError, isCliFailure, unreachableError } from "../errors";
39
+ import { CLI_ERROR_CODE, failUnreachable, failWithError, isCliFailure, isSourceUnavailableAnswer, unreachableError } from "../errors";
40
40
  import { DATA_SERVICE_UNREACHABLE_MESSAGE, isNetworkFailure } from "../../utils/network-failure";
41
41
  import { isTickerLinkPeer } from "../../layout/ticker-navigation";
42
42
  import { knownGapMessage, commandPointer, commandPointerLeads, topicPointer } from "../known-gaps";
@@ -287,7 +287,7 @@ export async function runPaneFunction(args: string[], ctx: CliCommandContext) {
287
287
  }
288
288
  // The file --output names, checked before the report loads so a path that cannot be written fails at once.
289
289
  const outputPath = parsed.outputPath === null ? null : resolveOutputPath(parsed.outputPath);
290
- if (outputPath) await checkOutputPath(outputPath);
290
+ const replacing = outputPath ? await checkOutputPath(outputPath) : false;
291
291
  if (parsed.requireBotSafe && (
292
292
  !resolved.capability.botSafe || resolved.capability.reportReadiness !== "ready"
293
293
  )) {
@@ -382,10 +382,10 @@ export async function runPaneFunction(args: string[], ctx: CliCommandContext) {
382
382
  await writeOutputFile(outputPath, `${csv}\n`);
383
383
  if (!ctx.cliOptions.quiet) for (const line of footer) console.error(line);
384
384
  // What was written and where; warnings go to stderr as they would beside printed rows, and JSON keeps its envelope.
385
- const saved = { output: outputPath, format: ctx.cliOptions.format, rows: report.data.rowCount };
385
+ const saved = { output: outputPath, format: ctx.cliOptions.format, rows: report.data.rowCount, replaced: replacing };
386
386
  printCliResult({ data: saved, ...(warnings.length > 0 ? { warnings } : {}) },
387
387
  { ...ctx.cliOptions, format: ctx.cliOptions.format === "json" ? "json" : "text" },
388
- { text: () => `Saved ${outputPath}` });
388
+ { text: () => `${replacing ? "Replaced" : "Saved"} ${outputPath}` });
389
389
  return;
390
390
  }
391
391
  ctx.printResult(result, render);
@@ -650,6 +650,8 @@ async function runPaneCliCommand(ctx: CliCommandContext, run: () => Promise<void
650
650
  // A failure with fields for --json (`ticker_moved`, its change and retry), or a code of its own (`no_data`,
651
651
  // `service_unreachable` and whether to retry), keeps them.
652
652
  if (isCliFailure(error) && (error.fields || error.code !== CLI_ERROR_CODE)) throw error;
653
+ // A source the data service reads was unavailable: retryable `source_unavailable`, in its own words.
654
+ if (isSourceUnavailableAnswer(error)) throw error;
653
655
  // A listing it cannot use says what to type instead; a name that opens nothing, what is close to it.
654
656
  if (error instanceof ListingArgError || error instanceof UnknownPaneFunctionError) ctx.fail(error.message, error.details || undefined);
655
657
  const message = error instanceof Error ? error.message : String(error);