gloomberb 0.9.2 → 0.9.4

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 (233) hide show
  1. package/README.md +24 -2
  2. package/bin/gloomberb +1 -1
  3. package/package.json +1 -1
  4. package/src/app/runtime/desktop-menu.ts +5 -1
  5. package/src/app/runtime/ticker-refresh.ts +4 -1
  6. package/src/app.tsx +20 -8
  7. package/src/brokers/account-cache.ts +1 -1
  8. package/src/brokers/sync-broker-instance.test.ts +107 -0
  9. package/src/brokers/sync-broker-instance.ts +22 -10
  10. package/src/capabilities/registry.ts +1 -0
  11. package/src/capabilities/types.ts +23 -0
  12. package/src/cli/commands/api.ts +119 -0
  13. package/src/cli/commands/automation.ts +173 -0
  14. package/src/cli/commands/command-utils.ts +53 -0
  15. package/src/cli/commands/market.ts +527 -0
  16. package/src/cli/commands/overview.ts +222 -0
  17. package/src/cli/commands/search.ts +39 -0
  18. package/src/cli/commands/system.ts +553 -0
  19. package/src/cli/commands/ticker.ts +104 -12
  20. package/src/cli/context.ts +35 -2
  21. package/src/cli/desktop-pane-shot.ts +2 -1
  22. package/src/cli/entry.ts +51 -0
  23. package/src/cli/errors.ts +56 -5
  24. package/src/cli/index.ts +73 -11
  25. package/src/cli/options.test.ts +38 -0
  26. package/src/cli/options.ts +95 -0
  27. package/src/cli/pane-functions/index.ts +10 -1
  28. package/src/cli/pane-functions/screenshot.ts +13 -1
  29. package/src/cli/registry.test.ts +40 -0
  30. package/src/cli/registry.ts +46 -5
  31. package/src/cli/result.test.ts +82 -0
  32. package/src/cli/result.ts +149 -0
  33. package/src/cli/types.ts +11 -0
  34. package/src/cli.test.ts +11 -11
  35. package/src/components/chart/bar-chart-renderer.test.ts +108 -3
  36. package/src/components/chart/bar-chart-renderer.ts +226 -27
  37. package/src/components/chart/comparison-stock-chart/interactions.ts +7 -1
  38. package/src/components/chart/comparison-stock-chart/legend.tsx +4 -0
  39. package/src/components/chart/comparison-stock-chart/render-data.ts +37 -8
  40. package/src/components/chart/comparison-stock-chart/selection-runtime.ts +19 -2
  41. package/src/components/chart/comparison-stock-chart/sources.ts +8 -4
  42. package/src/components/chart/comparison-stock-chart/toolbar.tsx +13 -3
  43. package/src/components/chart/comparison-stock-chart/view.tsx +12 -2
  44. package/src/components/chart/core/pane-settings.test.ts +27 -0
  45. package/src/components/chart/core/pane-settings.ts +60 -1
  46. package/src/components/chart/core/pointer.ts +34 -6
  47. package/src/components/chart/price-axis-labels.tsx +3 -1
  48. package/src/components/chart/static/bar-chart-surface.test.tsx +97 -0
  49. package/src/components/chart/static/bar-chart-surface.tsx +151 -28
  50. package/src/components/chart/static/chart/axis-overlays.tsx +243 -0
  51. package/src/components/chart/static/chart/surface.test.tsx +92 -0
  52. package/src/components/chart/static/chart/surface.tsx +167 -24
  53. package/src/components/chart/stock-chart/index.test.ts +25 -0
  54. package/src/components/chart/stock-chart/resolved/runtime.ts +1 -1
  55. package/src/components/chart/stock-chart/settings.ts +7 -3
  56. package/src/components/chart/stock-chart/viewport/runtime.ts +5 -5
  57. package/src/components/command-bar/layout-items/current-layout.ts +5 -1
  58. package/src/components/command-bar/pane-templates/workflow-route.ts +10 -0
  59. package/src/components/command-bar/surface/pane.test.tsx +76 -0
  60. package/src/components/data-table/view.tsx +13 -2
  61. package/src/components/feed-data-table/stack-view.tsx +9 -1
  62. package/src/components/index.ts +1 -1
  63. package/src/components/input-search-bar.test.tsx +103 -0
  64. package/src/components/input-search-bar.tsx +16 -0
  65. package/src/components/layout/detached-pane-shell.tsx +6 -3
  66. package/src/components/layout/floating-pane.tsx +3 -2
  67. package/src/components/layout/pane/content.tsx +20 -8
  68. package/src/components/layout/pane/footer/registration.tsx +6 -2
  69. package/src/components/layout/pane/frame.tsx +4 -4
  70. package/src/components/layout/pane/header.tsx +40 -4
  71. package/src/components/layout/pane/index.tsx +3 -1
  72. package/src/components/layout/pane/sizing.test.ts +43 -0
  73. package/src/components/layout/pane/sizing.ts +13 -4
  74. package/src/components/layout/shell/active-drag.ts +5 -1
  75. package/src/components/layout/shell/cursor-occlusion.ts +196 -0
  76. package/src/components/layout/shell/drag/runtime.ts +28 -3
  77. package/src/components/layout/shell/fullscreen.ts +10 -0
  78. package/src/components/layout/shell/index.test.tsx +487 -4
  79. package/src/components/layout/shell/index.tsx +165 -4
  80. package/src/components/layout/shell/layout-state.test.ts +33 -0
  81. package/src/components/layout/shell/layout-state.ts +4 -9
  82. package/src/components/layout/shell/native/pointer-runtime.ts +10 -4
  83. package/src/components/layout/shell/pane/layers.tsx +34 -16
  84. package/src/components/layout/shell/pane/management-shortcuts.ts +19 -0
  85. package/src/components/layout/shell/shortcuts.ts +4 -0
  86. package/src/components/layout/shell/terminal-pointer-runtime.ts +29 -19
  87. package/src/components/layout/shell/visible-layout.ts +17 -0
  88. package/src/components/layout/shell/window-mode/index.ts +11 -3
  89. package/src/components/layout/shell/window-mode/overlays.tsx +8 -1
  90. package/src/components/layout/status-bar.test.tsx +111 -1
  91. package/src/components/layout/status-bar.tsx +37 -7
  92. package/src/components/layout/transient-layout.tsx +57 -0
  93. package/src/components/layout/window-edit/mode.test.ts +76 -5
  94. package/src/components/layout/window-edit/mode.ts +47 -2
  95. package/src/components/layout/window-edit/presentation.ts +2 -1
  96. package/src/components/onboarding/onboarding-steps.tsx +8 -28
  97. package/src/components/onboarding/onboarding-wizard.test.tsx +13 -12
  98. package/src/components/onboarding/onboarding-wizard.tsx +2 -4
  99. package/src/components/onboarding/portfolio-step/index.tsx +0 -12
  100. package/src/components/onboarding/portfolio-step/types.ts +1 -3
  101. package/src/components/onboarding/wizard-keyboard.ts +2 -5
  102. package/src/components/price-performance.tsx +9 -1
  103. package/src/components/table-view-shared.tsx +12 -4
  104. package/src/components/ui/data-table/opentui/index.tsx +25 -12
  105. package/src/components/ui/data-table/types.ts +4 -0
  106. package/src/components/ui/fields.tsx +10 -3
  107. package/src/components/ui/page-stack-view.tsx +6 -2
  108. package/src/components/ui/table-layout.test.ts +25 -0
  109. package/src/components/ui/table-layout.ts +22 -6
  110. package/src/components/ui/tabs.tsx +26 -10
  111. package/src/components/ui/ui.test.tsx +87 -0
  112. package/src/core/app-services.ts +7 -4
  113. package/src/core/state/app/layout-reducer.ts +2 -2
  114. package/src/data/config/store/index.ts +1 -2
  115. package/src/plugins/builtin/analytics/index.test.tsx +6 -2
  116. package/src/plugins/builtin/analytics/pane-model.ts +43 -8
  117. package/src/plugins/builtin/cloud-tweets/pane.tsx +2 -0
  118. package/src/plugins/builtin/cloud-tweets/search-bar.tsx +3 -0
  119. package/src/plugins/builtin/cloud-tweets/table.tsx +14 -2
  120. package/src/plugins/builtin/comparison-chart/index.test.tsx +130 -6
  121. package/src/plugins/builtin/kelly-sizer/constants.ts +3 -0
  122. package/src/plugins/builtin/kelly-sizer/fields.ts +214 -0
  123. package/src/plugins/builtin/kelly-sizer/index.test.tsx +197 -0
  124. package/src/plugins/builtin/kelly-sizer/index.tsx +47 -0
  125. package/src/plugins/builtin/kelly-sizer/model.test.ts +152 -0
  126. package/src/plugins/builtin/kelly-sizer/model.ts +580 -0
  127. package/src/plugins/builtin/kelly-sizer/pane.tsx +558 -0
  128. package/src/plugins/builtin/kelly-sizer/portfolio.ts +71 -0
  129. package/src/plugins/builtin/kelly-sizer/sections.tsx +142 -0
  130. package/src/plugins/builtin/kelly-sizer/state.ts +67 -0
  131. package/src/plugins/builtin/kelly-sizer/test-support.tsx +174 -0
  132. package/src/plugins/builtin/kelly-sizer/types.ts +156 -0
  133. package/src/plugins/builtin/kelly-sizer/view.test.tsx +77 -0
  134. package/src/plugins/builtin/kelly-sizer/view.tsx +375 -0
  135. package/src/plugins/builtin/layout-manager/index.tsx +5 -1
  136. package/src/plugins/builtin/news/wire/read-state.ts +9 -32
  137. package/src/plugins/builtin/options/view.test.tsx +141 -4
  138. package/src/plugins/builtin/options/view.tsx +76 -15
  139. package/src/plugins/builtin/portfolio-list/account-metrics.test.ts +26 -1
  140. package/src/plugins/builtin/portfolio-list/account-metrics.ts +14 -0
  141. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +23 -0
  142. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +19 -2
  143. package/src/plugins/builtin/portfolio-list/index.test.ts +23 -0
  144. package/src/plugins/builtin/portfolio-list/pane/index.tsx +3 -1
  145. package/src/plugins/builtin/portfolio-list/quick-add/index.tsx +2 -7
  146. package/src/plugins/builtin/portfolio-list/summary/index.test.ts +59 -1
  147. package/src/plugins/builtin/portfolio-list/summary/index.tsx +36 -5
  148. package/src/plugins/builtin/shared/read-state.ts +43 -0
  149. package/src/plugins/builtin/substack/article-detail.test.tsx +10 -0
  150. package/src/plugins/builtin/substack/article-detail.tsx +39 -15
  151. package/src/plugins/builtin/substack/article-stack.tsx +6 -2
  152. package/src/plugins/builtin/substack/feed-tabs.tsx +12 -9
  153. package/src/plugins/builtin/substack/pane.tsx +8 -3
  154. package/src/plugins/builtin/substack/read-state.ts +55 -0
  155. package/src/plugins/builtin/thirteenf/pane.test.tsx +26 -0
  156. package/src/plugins/builtin/thirteenf/pane.tsx +12 -1
  157. package/src/plugins/builtin/ticker-detail/data-panes/fundamental-graph/content.tsx +149 -48
  158. package/src/plugins/builtin/ticker-detail/data-panes/fundamental-graph/model.ts +25 -2
  159. package/src/plugins/builtin/ticker-detail/data-panes/fundamental-graph.tsx +5 -4
  160. package/src/plugins/builtin/ticker-detail/data-panes.test.ts +16 -0
  161. package/src/plugins/builtin/ticker-detail/index.test.tsx +143 -0
  162. package/src/plugins/catalog-ui.ts +2 -0
  163. package/src/plugins/ibkr/broker-adapter.ts +19 -0
  164. package/src/plugins/ibkr/config.test.ts +31 -2
  165. package/src/plugins/ibkr/config.ts +9 -2
  166. package/src/plugins/ibkr/flex/index.test.ts +18 -9
  167. package/src/plugins/ibkr/flex/index.ts +30 -0
  168. package/src/plugins/ibkr/flex/statement-client.ts +68 -14
  169. package/src/plugins/ibkr/gateway/account-loaders.ts +1 -1
  170. package/src/plugins/ibkr/gateway/account-summary.ts +1 -0
  171. package/src/plugins/ibkr/gateway/service/index.test.ts +8 -0
  172. package/src/plugins/pane-manager/docking.ts +9 -2
  173. package/src/plugins/pane-manager/gridlock.ts +13 -5
  174. package/src/plugins/pane-manager/layout-state.ts +25 -0
  175. package/src/plugins/pane-manager/queries.ts +8 -2
  176. package/src/plugins/pane-manager.test.ts +33 -0
  177. package/src/plugins/pane-manager.ts +6 -1
  178. package/src/plugins/prediction-markets/chart.tsx +10 -4
  179. package/src/plugins/prediction-markets/controller/index.ts +2 -0
  180. package/src/plugins/prediction-markets/controller/keyboard.ts +34 -5
  181. package/src/plugins/prediction-markets/detail/book.tsx +141 -96
  182. package/src/plugins/prediction-markets/detail/overview.tsx +3 -0
  183. package/src/plugins/prediction-markets/detail/pane.tsx +71 -64
  184. package/src/plugins/prediction-markets/detail/shared.tsx +19 -0
  185. package/src/plugins/prediction-markets/detail/trades.tsx +64 -19
  186. package/src/plugins/prediction-markets/detail.test.tsx +50 -0
  187. package/src/plugins/prediction-markets/pane.test.tsx +75 -0
  188. package/src/plugins/prediction-markets/pane.tsx +71 -23
  189. package/src/plugins/prediction-markets/test-helpers.tsx +42 -23
  190. package/src/renderers/electrobun/bun/application-menu/click.test.ts +9 -0
  191. package/src/renderers/electrobun/bun/application-menu/click.ts +1 -0
  192. package/src/renderers/electrobun/bun/application-menu/index.test.ts +9 -0
  193. package/src/renderers/electrobun/bun/application-menu/index.ts +3 -2
  194. package/src/renderers/electrobun/bun/index.ts +13 -0
  195. package/src/renderers/electrobun/bun/window/focus.test.ts +35 -0
  196. package/src/renderers/electrobun/bun/window/focus.ts +5 -0
  197. package/src/renderers/electrobun/view/app-services.ts +6 -4
  198. package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +13 -2
  199. package/src/renderers/electrobun/view/data-table/index.tsx +19 -4
  200. package/src/renderers/electrobun/view/data-table/row.tsx +30 -6
  201. package/src/renderers/electrobun/view/desktop/controls.tsx +11 -5
  202. package/src/renderers/electrobun/view/host/ascii-text.ts +50 -0
  203. package/src/renderers/electrobun/view/host/input.tsx +115 -18
  204. package/src/renderers/electrobun/view/host/tabs.tsx +7 -2
  205. package/src/renderers/electrobun/view/host/text.test.ts +22 -0
  206. package/src/renderers/electrobun/view/host/text.tsx +24 -20
  207. package/src/renderers/electrobun/view/styles.css +11 -0
  208. package/src/renderers/electrobun/view/ui-host.tsx +1 -1
  209. package/src/renderers/opentui/host.tsx +17 -1
  210. package/src/renderers/opentui/start.tsx +13 -5
  211. package/src/renderers/opentui/ui-host.tsx +57 -25
  212. package/src/sources/provider-router/batches.ts +16 -2
  213. package/src/sources/provider-router/financial-routes.ts +5 -0
  214. package/src/sources/provider-router/financials.ts +11 -23
  215. package/src/sources/provider-router/index.test.ts +189 -0
  216. package/src/sources/provider-router/primary.ts +3 -2
  217. package/src/sources/sec-edgar.test.ts +83 -0
  218. package/src/sources/sec-edgar.ts +231 -0
  219. package/src/sources/yahoo-finance.test.ts +51 -0
  220. package/src/sources/yahoo-finance.ts +49 -1
  221. package/src/state/app/context/index.test.tsx +5 -8
  222. package/src/state/app/input-capture.ts +12 -0
  223. package/src/types/broker.ts +1 -0
  224. package/src/types/config.ts +10 -0
  225. package/src/types/plugin.ts +28 -0
  226. package/src/types/trading.ts +2 -0
  227. package/src/ui/host.tsx +16 -0
  228. package/src/ui/index.tsx +2 -0
  229. package/src/utils/cli-output.ts +6 -0
  230. package/src/utils/financial-statements.ts +23 -0
  231. package/src/utils/search-focus-navigation.ts +24 -0
  232. package/src/version.ts +1 -1
  233. package/src/components/onboarding/portfolio-step/manual-name-panel.tsx +0 -62
@@ -1,7 +1,7 @@
1
1
  import { dirname, resolve } from "path";
2
2
  import { mkdir } from "fs/promises";
3
3
  import type { PaneRuntimeState } from "../../core/state/app/state";
4
- import type { TickerFinancials } from "../../types/financials";
4
+ import type { OptionsChain, TickerFinancials } from "../../types/financials";
5
5
  import type { TickerRecord } from "../../types/ticker";
6
6
  import { slugifyName } from "../../utils/slugify";
7
7
  import { renderDesktopPaneScreenshot, type DesktopPaneShotPayload } from "../desktop-pane-shot";
@@ -18,6 +18,7 @@ import {
18
18
 
19
19
  const DESKTOP_CELL_WIDTH_PX = 8;
20
20
  const DESKTOP_CELL_HEIGHT_PX = 18;
21
+ const OPTIONS_PANE_ID = "options";
21
22
 
22
23
  export function defaultScreenshotPath(resolved: ResolvedPaneFunction, rawArg: string): string {
23
24
  const suffix = slugifyName([resolved.token, rawArg].filter(Boolean).join("-"), "pane");
@@ -70,11 +71,21 @@ async function buildDesktopShotPayload(
70
71
 
71
72
  const tickers: TickerRecord[] = [];
72
73
  const financials: Array<[string, TickerFinancials]> = [];
74
+ const optionsChains: Array<[string, OptionsChain]> = [];
75
+ const includeOptionsChains = resolved.pane.id === OPTIONS_PANE_ID || resolved.template?.paneId === OPTIONS_PANE_ID;
73
76
  for (const symbol of collectShotSymbols(resolved, rawArg)) {
74
77
  const entry = await fetchTickerFinancials(context, symbol);
75
78
  const data = await withShotPriceHistory(context, symbol, entry.tickerFile, entry.financials);
76
79
  tickers.push(entry.tickerFile ?? createFallbackTicker(symbol, data, context));
77
80
  financials.push([symbol, data]);
81
+ if (includeOptionsChains && context.dataProvider.getOptionsChain) {
82
+ const exchange = entry.tickerFile?.metadata.exchange
83
+ ?? data.quote?.listingExchangeName
84
+ ?? data.quote?.exchangeName
85
+ ?? "";
86
+ const chain = await context.dataProvider.getOptionsChain(symbol, exchange);
87
+ optionsChains.push([symbol, chain]);
88
+ }
78
89
  }
79
90
 
80
91
  return {
@@ -86,6 +97,7 @@ async function buildDesktopShotPayload(
86
97
  heightPx,
87
98
  tickers,
88
99
  financials,
100
+ optionsChains,
89
101
  paneState,
90
102
  };
91
103
  }
@@ -18,6 +18,7 @@ const originalHome = process.env.HOME;
18
18
 
19
19
  afterEach(async () => {
20
20
  process.env.HOME = originalHome;
21
+ process.exitCode = 0;
21
22
  await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
22
23
  });
23
24
 
@@ -182,6 +183,45 @@ describe("CLI dispatch", () => {
182
183
  expect(stdout).toContain("ok:hello world");
183
184
  });
184
185
 
186
+ test("renders plugin command failures through structured output", async () => {
187
+ process.env.HOME = await createTempHome("gloomberb-cli-registry-failure-home-");
188
+ const originalExitCode = process.exitCode;
189
+ process.exitCode = undefined;
190
+ try {
191
+ const { result, stderr } = await captureConsole(() => dispatchCli(
192
+ ["fail-example", "--json"],
193
+ {
194
+ externalPlugins: [{
195
+ plugin: {
196
+ id: "failing-cli",
197
+ name: "Failing CLI",
198
+ version: "1.0.0",
199
+ cliCommands: [{
200
+ name: "fail-example",
201
+ description: "Fail on purpose",
202
+ execute: (_args, ctx) => ctx.fail("Synthetic failure.", "Synthetic details."),
203
+ }],
204
+ },
205
+ path: "/tmp/failing-cli",
206
+ }],
207
+ },
208
+ ));
209
+
210
+ expect(result).toEqual({ kind: "handled" });
211
+ expect(process.exitCode).toBe(1);
212
+ expect(JSON.parse(stderr)).toEqual({
213
+ ok: false,
214
+ error: {
215
+ code: "cli_error",
216
+ message: "Synthetic failure.",
217
+ details: "Synthetic details.",
218
+ },
219
+ });
220
+ } finally {
221
+ process.exitCode = originalExitCode ?? 0;
222
+ }
223
+ });
224
+
185
225
  test("routes prediction market commands and aliases through launch-ui requests", async () => {
186
226
  process.env.HOME = await createTempHome("gloomberb-cli-prediction-home-");
187
227
 
@@ -1,9 +1,17 @@
1
1
  import type { AppConfig } from "../types/config";
2
- import type { CliCommandContext, CliCommandDef, CliDispatchResult, GloomPlugin } from "../types/plugin";
2
+ import type {
3
+ CliCommandContext,
4
+ CliCommandDef,
5
+ CliDispatchResult,
6
+ GloomPlugin,
7
+ PluginCliCommandDescriptor,
8
+ } from "../types/plugin";
3
9
  import type { LoadedExternalPlugin } from "../plugins/loader";
4
10
  import { getPluginCatalog } from "../plugins/catalog";
5
- import { initConfigData, initMarketData } from "./context";
11
+ import { initCliServices, initConfigData, initMarketData } from "./context";
6
12
  import { closeAndFail, fail } from "./errors";
13
+ import { DEFAULT_CLI_OPTIONS, type CliGlobalOptions } from "./options";
14
+ import { printCliResult } from "./result";
7
15
  import {
8
16
  cliStyles,
9
17
  colorBySign,
@@ -26,6 +34,8 @@ export interface CliCommandRegistry {
26
34
  lookup: ReadonlyMap<string, RegisteredCliCommand>;
27
35
  config: AppConfig | null;
28
36
  plugins: GloomPlugin[];
37
+ externalPlugins: LoadedExternalPlugin[];
38
+ descriptors: Array<{ pluginId: string; descriptor: PluginCliCommandDescriptor }>;
29
39
  }
30
40
 
31
41
  interface BuildCliCommandRegistryOptions {
@@ -61,6 +71,19 @@ function getCommandUsageLabel(command: CliCommandDef): string {
61
71
  return command.help?.usage?.[0] ?? command.name;
62
72
  }
63
73
 
74
+ function descriptorToCommand(descriptor: PluginCliCommandDescriptor): CliCommandDef | null {
75
+ if (!descriptor.execute) return null;
76
+ return {
77
+ name: descriptor.name,
78
+ aliases: descriptor.aliases,
79
+ description: descriptor.summary,
80
+ help: descriptor.examples?.length
81
+ ? { usage: descriptor.examples }
82
+ : undefined,
83
+ execute: descriptor.execute,
84
+ };
85
+ }
86
+
64
87
  function renderHelpSections(registry: CliCommandRegistry): string[] {
65
88
  const lines: string[] = [];
66
89
 
@@ -149,6 +172,7 @@ export function buildCliCommandRegistry({
149
172
  }
150
173
 
151
174
  const loadablePlugins: GloomPlugin[] = [];
175
+ const descriptors: Array<{ pluginId: string; descriptor: PluginCliCommandDescriptor }> = [];
152
176
  for (const entry of catalog) {
153
177
  if (entry.error) {
154
178
  registryLog.warn(`Skipping external plugin "${entry.plugin.id}" for CLI registration.`, {
@@ -161,6 +185,11 @@ export function buildCliCommandRegistry({
161
185
  for (const command of entry.plugin.cliCommands ?? []) {
162
186
  registerCommand(command, entry.plugin.id, "plugin");
163
187
  }
188
+ for (const descriptor of entry.plugin.cli?.commands ?? []) {
189
+ descriptors.push({ pluginId: entry.plugin.id, descriptor });
190
+ const command = descriptorToCommand(descriptor);
191
+ if (command) registerCommand(command, entry.plugin.id, "plugin");
192
+ }
164
193
  }
165
194
 
166
195
  const commands = allCommands.filter((entry) => (
@@ -180,14 +209,25 @@ export function buildCliCommandRegistry({
180
209
  lookup,
181
210
  config,
182
211
  plugins: loadablePlugins,
212
+ externalPlugins,
213
+ descriptors,
183
214
  };
184
215
  }
185
216
 
186
- export function createCliCommandContext(ownerId: string, plugins: GloomPlugin[]): CliCommandContext {
217
+ export function createCliCommandContext(
218
+ ownerId: string,
219
+ registryOrPlugins: Pick<CliCommandRegistry, "plugins" | "externalPlugins"> | GloomPlugin[],
220
+ cliOptions: CliGlobalOptions = DEFAULT_CLI_OPTIONS,
221
+ ): CliCommandContext {
222
+ const registry = Array.isArray(registryOrPlugins)
223
+ ? { plugins: registryOrPlugins, externalPlugins: [] }
224
+ : registryOrPlugins;
187
225
  return {
188
226
  initConfigData,
189
- initMarketData: () => initMarketData({ plugins }),
190
- plugins,
227
+ initMarketData: () => initMarketData({ plugins: registry.plugins }),
228
+ initServices: () => initCliServices({ externalPlugins: registry.externalPlugins }),
229
+ cliOptions,
230
+ plugins: registry.plugins,
191
231
  fail,
192
232
  closeAndFail,
193
233
  output: {
@@ -197,6 +237,7 @@ export function createCliCommandContext(ownerId: string, plugins: GloomPlugin[])
197
237
  renderStat,
198
238
  renderTable,
199
239
  },
240
+ printResult: (result, options) => printCliResult(result, cliOptions, options),
200
241
  log: debugLog.createLogger(ownerId === "core" ? "cli" : ownerId),
201
242
  };
202
243
  }
@@ -0,0 +1,82 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { serializeCliError, serializeCliResult } from "./result";
3
+ import type { CliGlobalOptions } from "./options";
4
+
5
+ const baseOptions: CliGlobalOptions = {
6
+ format: "text",
7
+ quiet: false,
8
+ color: null,
9
+ refresh: false,
10
+ dryRun: false,
11
+ yes: false,
12
+ };
13
+
14
+ describe("serializeCliResult", () => {
15
+ test("renders limited JSON result envelopes", () => {
16
+ const output = serializeCliResult(
17
+ { data: [{ symbol: "AAPL" }, { symbol: "MSFT" }] },
18
+ { ...baseOptions, format: "json", limit: 1 },
19
+ );
20
+ expect(JSON.parse(output)).toEqual({
21
+ ok: true,
22
+ data: [{ symbol: "AAPL" }],
23
+ });
24
+ });
25
+
26
+ test("includes display column metadata in JSON envelopes", () => {
27
+ const output = serializeCliResult(
28
+ { data: [{ quote: { symbol: "AAPL", price: 123 } }] },
29
+ { ...baseOptions, format: "json" },
30
+ {
31
+ rows: (data) => data.map((row) => row.quote),
32
+ columns: [
33
+ { key: "symbol", header: "Symbol" },
34
+ { key: "price", header: "Last", align: "right" },
35
+ ],
36
+ },
37
+ );
38
+ expect(JSON.parse(output)).toEqual({
39
+ ok: true,
40
+ data: [{ quote: { symbol: "AAPL", price: 123 } }],
41
+ columns: [
42
+ { key: "symbol", header: "Symbol" },
43
+ { key: "price", header: "Last", align: "right" },
44
+ ],
45
+ });
46
+ });
47
+
48
+ test("renders CSV with provided column order", () => {
49
+ const output = serializeCliResult(
50
+ { data: [{ symbol: "AAPL", name: "Apple, Inc." }] },
51
+ { ...baseOptions, format: "csv" },
52
+ {
53
+ columns: [
54
+ { key: "symbol", header: "Symbol" },
55
+ { key: "name", header: "Name" },
56
+ ],
57
+ },
58
+ );
59
+ expect(output).toBe('Symbol,Name\nAAPL,"Apple, Inc."');
60
+ });
61
+
62
+ test("renders NDJSON rows", () => {
63
+ const output = serializeCliResult(
64
+ { data: [{ symbol: "AAPL" }, { symbol: "MSFT" }] },
65
+ { ...baseOptions, format: "ndjson" },
66
+ );
67
+ expect(output).toBe('{"symbol":"AAPL"}\n{"symbol":"MSFT"}');
68
+ });
69
+ });
70
+
71
+ describe("serializeCliError", () => {
72
+ test("renders stable structured errors for JSON", () => {
73
+ const output = serializeCliError(
74
+ { code: "auth_required", message: "Sign in first.", retryable: true },
75
+ { ...baseOptions, format: "json" },
76
+ );
77
+ expect(JSON.parse(output)).toEqual({
78
+ ok: false,
79
+ error: { code: "auth_required", message: "Sign in first.", retryable: true },
80
+ });
81
+ });
82
+ });
@@ -0,0 +1,149 @@
1
+ import type { CliGlobalOptions } from "./options";
2
+ import { renderTable, type CliTableColumn } from "../utils/cli-output";
3
+
4
+ export interface CliResult<T = unknown> {
5
+ data: T;
6
+ metadata?: Record<string, unknown>;
7
+ warnings?: string[];
8
+ }
9
+
10
+ export interface CliErrorObject {
11
+ code: string;
12
+ message: string;
13
+ details?: unknown;
14
+ retryable?: boolean;
15
+ }
16
+
17
+ export interface CliResultColumn<Row = Record<string, unknown>> extends CliTableColumn {
18
+ key: string;
19
+ value?: (row: Row) => unknown;
20
+ }
21
+
22
+ export interface CliResultRenderOptions<T = unknown, Row = Record<string, unknown>> {
23
+ text?: (data: T) => string;
24
+ columns?: CliResultColumn<Row>[];
25
+ rows?: (data: T) => Row[];
26
+ }
27
+
28
+ interface CliResultJsonEnvelope<T> extends CliResult<T> {
29
+ ok: true;
30
+ columns?: Array<Pick<CliResultColumn, "key" | "header" | "align" | "width">>;
31
+ }
32
+
33
+ function applyLimit<T>(data: T, limit?: number): T {
34
+ if (!Array.isArray(data) || limit == null) return data;
35
+ return data.slice(0, limit) as T;
36
+ }
37
+
38
+ function asRows<T, Row>(data: T, limit?: number, rows?: (data: T) => Row[]): Row[] {
39
+ const resolvedRows = rows ? rows(data) : (Array.isArray(data) ? data : [data]) as Row[];
40
+ return limit == null ? resolvedRows : resolvedRows.slice(0, limit);
41
+ }
42
+
43
+ function normalizeCell(value: unknown): string {
44
+ if (value == null) return "";
45
+ if (value instanceof Date) return value.toISOString();
46
+ if (typeof value === "object") return JSON.stringify(value);
47
+ return String(value);
48
+ }
49
+
50
+ function inferColumns(rows: Record<string, unknown>[]): CliResultColumn<Record<string, unknown>>[] {
51
+ const keys = new Set<string>();
52
+ for (const row of rows) {
53
+ if (row && typeof row === "object" && !Array.isArray(row)) {
54
+ for (const key of Object.keys(row)) keys.add(key);
55
+ }
56
+ }
57
+ return [...keys].map((key) => ({ key, header: key }));
58
+ }
59
+
60
+ function csvEscape(value: string): string {
61
+ if (!/[",\n\r]/.test(value)) return value;
62
+ return `"${value.replace(/"/g, '""')}"`;
63
+ }
64
+
65
+ function serializeColumns<Row>(columns?: CliResultColumn<Row>[]) {
66
+ return columns?.map((column) => ({
67
+ key: column.key,
68
+ header: column.header,
69
+ ...(column.align ? { align: column.align } : {}),
70
+ ...(column.width ? { width: column.width } : {}),
71
+ }));
72
+ }
73
+
74
+ function renderCsv<Row extends Record<string, unknown>>(
75
+ rows: Row[],
76
+ columns?: CliResultColumn<Row>[],
77
+ ): string {
78
+ const resolvedColumns = columns && columns.length > 0
79
+ ? columns
80
+ : inferColumns(rows as Record<string, unknown>[]) as CliResultColumn<Row>[];
81
+ const header = resolvedColumns.map((column) => csvEscape(column.header)).join(",");
82
+ const body = rows.map((row) => resolvedColumns
83
+ .map((column) => csvEscape(normalizeCell(column.value ? column.value(row) : row[column.key])))
84
+ .join(","));
85
+ return [header, ...body].join("\n");
86
+ }
87
+
88
+ function renderTextTable<Row extends Record<string, unknown>>(
89
+ rows: Row[],
90
+ columns?: CliResultColumn<Row>[],
91
+ ): string {
92
+ const resolvedColumns = columns && columns.length > 0
93
+ ? columns
94
+ : inferColumns(rows as Record<string, unknown>[]) as CliResultColumn<Row>[];
95
+ return renderTable(
96
+ resolvedColumns.map((column) => ({
97
+ header: column.header,
98
+ align: column.align,
99
+ width: column.width,
100
+ })),
101
+ rows.map((row) => resolvedColumns.map((column) => normalizeCell(column.value ? column.value(row) : row[column.key]))),
102
+ );
103
+ }
104
+
105
+ export function serializeCliResult<T, Row extends Record<string, unknown> = Record<string, unknown>>(
106
+ result: CliResult<T>,
107
+ options: CliGlobalOptions,
108
+ renderOptions: CliResultRenderOptions<T, Row> = {},
109
+ ): string {
110
+ if (options.format === "json") {
111
+ const columns = serializeColumns(renderOptions.columns);
112
+ const envelope: CliResultJsonEnvelope<T> = {
113
+ ok: true,
114
+ ...result,
115
+ data: applyLimit(result.data, options.limit),
116
+ ...(columns?.length ? { columns } : {}),
117
+ };
118
+ return JSON.stringify(envelope, null, 2);
119
+ }
120
+
121
+ const rows = asRows(result.data, options.limit, renderOptions.rows);
122
+ if (options.format === "ndjson") {
123
+ return rows.map((row) => JSON.stringify(row)).join("\n");
124
+ }
125
+ if (options.format === "csv") {
126
+ return renderCsv(rows as Row[], renderOptions.columns);
127
+ }
128
+ if (renderOptions.text) {
129
+ return renderOptions.text(result.data);
130
+ }
131
+ return renderTextTable(rows as Row[], renderOptions.columns);
132
+ }
133
+
134
+ export function printCliResult<T, Row extends Record<string, unknown> = Record<string, unknown>>(
135
+ result: CliResult<T>,
136
+ options: CliGlobalOptions,
137
+ renderOptions: CliResultRenderOptions<T, Row> = {},
138
+ ): void {
139
+ if (options.quiet && options.format === "text") return;
140
+ const output = serializeCliResult(result, options, renderOptions);
141
+ if (output) console.log(output);
142
+ }
143
+
144
+ export function serializeCliError(error: CliErrorObject, options: CliGlobalOptions): string {
145
+ if (options.format === "json" || options.format === "ndjson") {
146
+ return JSON.stringify({ ok: false, error }, null, options.format === "json" ? 2 : 0);
147
+ }
148
+ return error.details == null ? error.message : `${error.message}\n${String(error.details)}`;
149
+ }
package/src/cli/types.ts CHANGED
@@ -2,6 +2,7 @@ import type { AppConfig } from "../types/config";
2
2
  import { AppPersistence } from "../data/app-persistence";
3
3
  import { TickerRepository } from "../data/ticker-repository";
4
4
  import { AssetDataRouter } from "../sources/provider-router";
5
+ import type { AppServices } from "../core/app-services";
5
6
 
6
7
  export type ConfigContext = {
7
8
  config: AppConfig;
@@ -13,3 +14,13 @@ export type ConfigContext = {
13
14
  export type MarketContext = ConfigContext & {
14
15
  dataProvider: AssetDataRouter;
15
16
  };
17
+
18
+ export type CliServicesContext = {
19
+ config: AppConfig;
20
+ dataDir: string;
21
+ services: AppServices;
22
+ dataProvider: AssetDataRouter;
23
+ persistence: AppPersistence;
24
+ store: TickerRepository;
25
+ destroy(): void;
26
+ };
package/src/cli.test.ts CHANGED
@@ -22,6 +22,7 @@ const originalHome = process.env.HOME;
22
22
 
23
23
  afterEach(async () => {
24
24
  process.env.HOME = originalHome;
25
+ process.exitCode = 0;
25
26
  await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
26
27
  });
27
28
 
@@ -96,12 +97,12 @@ async function captureConsole<T>(fn: () => Promise<T> | T): Promise<{ result: T;
96
97
  }
97
98
  }
98
99
 
99
- async function captureConsoleFailure(fn: () => Promise<unknown> | unknown): Promise<{ stdout: string; stderr: string; error: unknown }> {
100
+ async function captureConsoleFailure(fn: () => Promise<unknown> | unknown): Promise<{ stdout: string; stderr: string; exitCode: string | number | undefined }> {
100
101
  const logs: string[] = [];
101
102
  const errors: string[] = [];
102
103
  const originalLog = console.log;
103
104
  const originalError = console.error;
104
- const originalExit = process.exit;
105
+ const originalExitCode = process.exitCode;
105
106
 
106
107
  console.log = (...args: unknown[]) => {
107
108
  logs.push(args.map(String).join(" "));
@@ -109,23 +110,22 @@ async function captureConsoleFailure(fn: () => Promise<unknown> | unknown): Prom
109
110
  console.error = (...args: unknown[]) => {
110
111
  errors.push(args.map(String).join(" "));
111
112
  };
112
- process.exit = ((code?: number) => {
113
- throw new Error(`process.exit:${code ?? 0}`);
114
- }) as typeof process.exit;
113
+ process.exitCode = undefined;
115
114
 
116
115
  try {
117
116
  await fn();
118
- throw new Error("Expected command to fail.");
119
- } catch (error) {
117
+ if (process.exitCode == null || process.exitCode === 0) {
118
+ throw new Error("Expected command to fail.");
119
+ }
120
120
  return {
121
121
  stdout: logs.join("\n"),
122
122
  stderr: errors.join("\n"),
123
- error,
123
+ exitCode: process.exitCode,
124
124
  };
125
125
  } finally {
126
126
  console.log = originalLog;
127
127
  console.error = originalError;
128
- process.exit = originalExit;
128
+ process.exitCode = originalExitCode ?? 0;
129
129
  }
130
130
  }
131
131
 
@@ -226,7 +226,7 @@ describe("CLI portfolio commands", () => {
226
226
  });
227
227
 
228
228
  const result = await captureConsoleFailure(() => runCli(["portfolio", "create", "Research"]));
229
- expect(String(result.error)).toContain("process.exit:1");
229
+ expect(result.exitCode).toBe(1);
230
230
  expect(result.stderr).toContain('Portfolio "Research" already exists.');
231
231
  });
232
232
 
@@ -370,7 +370,7 @@ describe("CLI portfolio commands", () => {
370
370
  });
371
371
 
372
372
  const result = await captureConsoleFailure(() => runCli(["portfolio", "add", "IBKR Account", "NVDA"]));
373
- expect(String(result.error)).toContain("process.exit:1");
373
+ expect(result.exitCode).toBe(1);
374
374
  expect(result.stderr).toContain('Portfolio "IBKR Account" is broker-managed and cannot be modified manually.');
375
375
  });
376
376
  });
@@ -1,5 +1,13 @@
1
1
  import { describe, expect, test } from "bun:test";
2
- import { buildBarChartScene, renderBarChart, renderNativeBarChart } from "./bar-chart-renderer";
2
+ import {
3
+ buildBarChartScene,
4
+ renderBarChart,
5
+ renderBarChartAxis,
6
+ renderBarChartYAxis,
7
+ renderNativeBarChart,
8
+ resolveNativeBarPixelBounds,
9
+ resolveBarChartHover,
10
+ } from "./bar-chart-renderer";
3
11
 
4
12
  const series = [
5
13
  {
@@ -27,27 +35,124 @@ describe("bar chart renderer", () => {
27
35
  const scene = buildBarChartScene(series, {
28
36
  width: 24,
29
37
  height: 8,
30
- colors: { bgColor: "#000000", gridColor: "#333333", axisColor: "#666666" },
38
+ colors: { bgColor: "#000000", gridColor: "#333333", axisColor: "#666666", negativeColor: "#ff5555" },
31
39
  });
32
40
 
33
41
  expect(scene).not.toBeNull();
34
42
  expect(scene!.categories).toEqual(["2024", "2025"]);
35
43
  expect(scene!.bars).toHaveLength(4);
36
44
  expect(scene!.zeroRow).toBeGreaterThanOrEqual(0);
45
+ expect(scene!.bars.find((bar) => bar.value < 0)?.color).toBe("#ff5555");
37
46
  });
38
47
 
39
48
  test("renders text fallback and native bitmap output", () => {
40
49
  const scene = buildBarChartScene(series, {
41
50
  width: 24,
42
51
  height: 8,
43
- colors: { bgColor: "#000000", gridColor: "#333333", axisColor: "#666666" },
52
+ colors: {
53
+ bgColor: "#000000",
54
+ gridColor: "#333333",
55
+ axisColor: "#666666",
56
+ negativeColor: "#ff5555",
57
+ hoverColor: "#ffffff",
58
+ },
44
59
  })!;
45
60
 
46
61
  expect(renderBarChart(scene).join("\n")).toContain("█");
47
62
 
48
63
  const bitmap = renderNativeBarChart(scene, 96, 48);
64
+ const negativePixel = Array.from({ length: bitmap.pixels.length / 4 }).some((_, pixelIndex) => {
65
+ const index = pixelIndex * 4;
66
+ return bitmap.pixels[index]! > 200 && bitmap.pixels[index + 1]! < 100 && bitmap.pixels[index + 2]! < 100;
67
+ });
49
68
  expect(bitmap.width).toBe(96);
50
69
  expect(bitmap.height).toBe(48);
51
70
  expect(bitmap.pixels.some((value) => value > 0)).toBe(true);
71
+ expect(negativePixel).toBe(true);
72
+
73
+ const hover = resolveBarChartHover(scene, scene.bars[0]!.x);
74
+ expect(renderBarChart(scene, hover).join("\n")).toContain("▓");
75
+ const hoverBitmap = renderNativeBarChart(scene, 96, 48, hover);
76
+ const hoverPixel = Array.from({ length: hoverBitmap.pixels.length / 4 }).some((_, pixelIndex) => {
77
+ const index = pixelIndex * 4;
78
+ return hoverBitmap.pixels[index]! > 240 && hoverBitmap.pixels[index + 1]! > 240 && hoverBitmap.pixels[index + 2]! > 240;
79
+ });
80
+ expect(hoverBitmap.pixels).not.toEqual(bitmap.pixels);
81
+ expect(hoverPixel).toBe(true);
82
+ });
83
+
84
+ test("renders y-axis labels and resolves hover targets", () => {
85
+ const scene = buildBarChartScene(series, {
86
+ width: 24,
87
+ height: 8,
88
+ colors: { bgColor: "#000000", gridColor: "#333333", axisColor: "#666666" },
89
+ })!;
90
+
91
+ const yAxis = renderBarChartYAxis(scene, 8, (value) => String(Math.round(value)));
92
+ const labelCount = yAxis.filter((line) => line.trim().length > 0).length;
93
+ expect(labelCount).toBeGreaterThanOrEqual(5);
94
+ expect(yAxis.join("\n")).toContain("22");
95
+ expect(yAxis.join("\n")).toContain("0");
96
+
97
+ const hover = resolveBarChartHover(scene, scene.bars[1]!.x);
98
+ expect(hover).toMatchObject({
99
+ seriesId: "NVDA",
100
+ seriesLabel: "NVDA",
101
+ category: "2024",
102
+ value: 20,
103
+ x: scene.bars[1]!.x,
104
+ width: scene.bars[1]!.width,
105
+ row: scene.bars[1]!.row,
106
+ });
107
+ });
108
+
109
+ test("renders dense single-series bars with consistent separators and readable x-axis labels", () => {
110
+ const denseSeries = [{
111
+ id: "value",
112
+ label: "Value",
113
+ color: "#00ff66",
114
+ points: Array.from({ length: 14 }, (_unused, index) => ({
115
+ category: `${2015 + index} Q1`,
116
+ value: index + 1,
117
+ })),
118
+ }];
119
+ const scene = buildBarChartScene(denseSeries, {
120
+ width: 47,
121
+ height: 8,
122
+ colors: { bgColor: "#000000", gridColor: "#333333", axisColor: "#666666", negativeColor: "#ff5555" },
123
+ })!;
124
+
125
+ const lastBar = scene.bars.at(-1)!;
126
+ expect(lastBar.x + lastBar.width).toBe(scene.width);
127
+ expect(renderBarChart(scene)[scene.zeroRow]).not.toContain("─");
128
+
129
+ const bitmapWidth = 470;
130
+ const pixelBounds = scene.bars.map((bar) => resolveNativeBarPixelBounds(scene, bar, bitmapWidth));
131
+ const pixelWidths = pixelBounds.map((bounds) => bounds.rightExclusive - bounds.left);
132
+ expect(Math.max(...pixelWidths) - Math.min(...pixelWidths)).toBeLessThanOrEqual(1);
133
+ expect(pixelBounds[0]!.left).toBe(0);
134
+ expect(pixelBounds.at(-1)!.rightExclusive).toBe(bitmapWidth);
135
+ const pixelGaps: number[] = [];
136
+ for (let index = 1; index < pixelBounds.length; index++) {
137
+ pixelGaps.push(pixelBounds[index]!.left - pixelBounds[index - 1]!.rightExclusive);
138
+ }
139
+ expect(new Set(pixelGaps)).toEqual(new Set([1]));
140
+
141
+ const bitmap = renderNativeBarChart(scene, bitmapWidth, 80);
142
+ const zeroY = Math.round((scene.zeroRow / Math.max(scene.height - 1, 1)) * (bitmap.height - 1));
143
+ let separatorColumns = 0;
144
+ for (let x = 0; x < bitmap.width; x++) {
145
+ const index = (zeroY * bitmap.width + x) * 4;
146
+ if (bitmap.pixels[index + 1]! <= 120) separatorColumns++;
147
+ }
148
+ expect(separatorColumns).toBe(scene.categories.length - 1);
149
+
150
+ const axis = renderBarChartAxis(scene, 1);
151
+ expect(axis).toHaveLength(1);
152
+ expect(axis.every((line) => line.length === scene.width)).toBe(true);
153
+ expect(axis.join("\n")).toContain("2015");
154
+ expect(axis.join("\n")).not.toContain("Q1");
155
+ expect(axis.join("\n")).not.toContain("20 20");
156
+ expect(axis[0]!.endsWith(" ")).toBe(true);
52
157
  });
53
158
  });