@bloomai/cli 0.1.6 → 0.1.8

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.
package/dist/index.js CHANGED
@@ -1,29 +1,263 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import { readFileSync as readFileSync2 } from "fs";
4
+ import { readFileSync as readFileSync5 } from "fs";
5
5
  import path from "path";
6
6
  import { fileURLToPath } from "url";
7
- import { Command } from "commander";
7
+ import { Command as Command3 } from "commander";
8
8
 
9
- // src/auth.ts
10
- import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
9
+ // src/errors.ts
10
+ var BloomError = class extends Error {
11
+ constructor(msg) {
12
+ super(msg);
13
+ this.name = "BloomError";
14
+ }
15
+ };
16
+ var AuthError = class extends BloomError {
17
+ constructor(msg) {
18
+ super(msg);
19
+ this.name = "AuthError";
20
+ }
21
+ };
22
+ var RateLimitError = class extends BloomError {
23
+ constructor(msg) {
24
+ super(msg);
25
+ this.name = "RateLimitError";
26
+ }
27
+ };
28
+ var TickerNotFoundError = class extends BloomError {
29
+ ticker;
30
+ constructor(ticker, msg) {
31
+ super(msg ?? `Ticker not found: ${ticker}`);
32
+ this.name = "TickerNotFoundError";
33
+ this.ticker = ticker;
34
+ }
35
+ };
36
+ var ApiError = class extends BloomError {
37
+ status;
38
+ constructor(status2, msg) {
39
+ super(msg);
40
+ this.name = "ApiError";
41
+ this.status = status2;
42
+ }
43
+ };
44
+ function errorMessage(body) {
45
+ const text = body.trim();
46
+ try {
47
+ const parsed = JSON.parse(text);
48
+ const msg = typeof parsed === "string" ? parsed : parsed?.error ?? parsed?.detail ?? parsed?.message;
49
+ if (typeof msg === "string") return msg;
50
+ } catch {
51
+ }
52
+ return text.startsWith("<") ? "" : text;
53
+ }
54
+ var TICKER_NOT_FOUND = /invalid symbol|symbol doesn't exist|investment not found/i;
55
+ function httpError(status2, body, ticker) {
56
+ const msg = errorMessage(body);
57
+ if (status2 === 401) {
58
+ return new AuthError("API key was rejected (HTTP 401). It may be invalid or revoked.");
59
+ }
60
+ if (status2 === 403) {
61
+ return new AuthError(msg || "Authentication failed");
62
+ }
63
+ if (status2 === 429) {
64
+ return new RateLimitError(msg || "Rate limited");
65
+ }
66
+ if (ticker && TICKER_NOT_FOUND.test(msg)) {
67
+ return new TickerNotFoundError(ticker, msg);
68
+ }
69
+ return new ApiError(status2, msg ? `${msg} (HTTP ${status2})` : `API error ${status2}`);
70
+ }
71
+ function mcpError(code, message) {
72
+ const msg = message ? String(message) : "";
73
+ const lower = msg.toLowerCase();
74
+ if (code === -32e3 || lower.includes("unauthorized") || lower.includes("auth")) {
75
+ return new AuthError(msg || "Authentication failed");
76
+ }
77
+ if (code === -32001 || lower.includes("rate limit")) {
78
+ return new RateLimitError(msg || "Rate limited");
79
+ }
80
+ if (lower.includes("not found") && lower.includes("ticker")) {
81
+ const match = msg.match(/ticker[:\s]+([A-Z]+)/i);
82
+ return new TickerNotFoundError(match?.[1] ?? "UNKNOWN", msg);
83
+ }
84
+ return new ApiError(code, msg || `MCP error ${code}`);
85
+ }
86
+
87
+ // src/debug.ts
88
+ var _debug = false;
89
+ function setDebug(v) {
90
+ _debug = v;
91
+ }
92
+ function debugLog(...args) {
93
+ if (_debug) {
94
+ console.error("[debug]", ...args);
95
+ }
96
+ }
97
+
98
+ // src/cache.ts
99
+ import { readFileSync, writeFileSync, mkdirSync, readdirSync, unlinkSync, statSync } from "fs";
100
+ import { createHash } from "crypto";
11
101
  import { join } from "path";
12
102
  import { homedir } from "os";
13
- var CONFIG_DIR = join(homedir(), ".config", "bloom-cli");
14
- var CONFIG_FILE = join(CONFIG_DIR, "config.json");
103
+ var TTL = {
104
+ quote: 300,
105
+ // 5 min
106
+ news: 14400,
107
+ // 4 hours
108
+ info: 86400,
109
+ // 24 hours
110
+ financials: 604800,
111
+ // 7 days
112
+ earnings: 86400,
113
+ // 24 hours
114
+ technicals: 3600,
115
+ // 1 hour
116
+ sentiment: 1800,
117
+ // 30 min
118
+ default: 3600
119
+ // 1 hour fallback
120
+ };
121
+ var _noCache = false;
122
+ var _cacheDir;
123
+ function setNoCache(v) {
124
+ _noCache = v;
125
+ }
126
+ function setCacheDir(dir) {
127
+ _cacheDir = dir;
128
+ }
129
+ function getCacheDir() {
130
+ return _cacheDir ?? process.env.BLOOM_CACHE_DIR ?? join(homedir(), ".cache", "bloom-cli");
131
+ }
132
+ function ensureCacheDir() {
133
+ const dir = getCacheDir();
134
+ mkdirSync(dir, { recursive: true });
135
+ return dir;
136
+ }
137
+ function cacheKey(toolName, args) {
138
+ const sortedArgs = JSON.stringify(args, Object.keys(args).sort());
139
+ const hash = createHash("md5").update(`${toolName}:${sortedArgs}`).digest("hex");
140
+ return hash;
141
+ }
142
+ function getCached(toolName, args) {
143
+ if (_noCache) return void 0;
144
+ const key = cacheKey(toolName, args);
145
+ const filePath = join(getCacheDir(), `${key}.json`);
146
+ let raw;
147
+ try {
148
+ raw = readFileSync(filePath, "utf-8");
149
+ } catch {
150
+ return void 0;
151
+ }
152
+ try {
153
+ const entry = JSON.parse(raw);
154
+ if (Date.now() > entry.expiresAt) {
155
+ try {
156
+ unlinkSync(filePath);
157
+ } catch {
158
+ }
159
+ debugLog(`cache MISS (expired) ${toolName}`);
160
+ return void 0;
161
+ }
162
+ debugLog(`cache HIT ${toolName} (expires in ${Math.round((entry.expiresAt - Date.now()) / 1e3)}s)`);
163
+ return entry.data;
164
+ } catch {
165
+ try {
166
+ unlinkSync(filePath);
167
+ } catch {
168
+ }
169
+ return void 0;
170
+ }
171
+ }
172
+ function setCached(toolName, args, data, category) {
173
+ if (_noCache) return;
174
+ const ttlSeconds = TTL[category] ?? TTL.default;
175
+ const key = cacheKey(toolName, args);
176
+ const entry = {
177
+ data,
178
+ expiresAt: Date.now() + ttlSeconds * 1e3,
179
+ toolName,
180
+ category,
181
+ createdAt: Date.now()
182
+ };
183
+ try {
184
+ const dir = ensureCacheDir();
185
+ const filePath = join(dir, `${key}.json`);
186
+ writeFileSync(filePath, JSON.stringify(entry), { mode: 384 });
187
+ debugLog(`cache SET ${toolName} (ttl=${ttlSeconds}s, category=${category})`);
188
+ } catch (err) {
189
+ debugLog(`cache WRITE ERROR: ${err}`);
190
+ }
191
+ }
192
+ function clearCache() {
193
+ const dir = getCacheDir();
194
+ let cleared = 0;
195
+ try {
196
+ const files = readdirSync(dir);
197
+ for (const f of files) {
198
+ if (f.endsWith(".json")) {
199
+ try {
200
+ unlinkSync(join(dir, f));
201
+ cleared++;
202
+ } catch {
203
+ }
204
+ }
205
+ }
206
+ } catch {
207
+ }
208
+ return { cleared };
209
+ }
210
+ function cacheStats() {
211
+ const dir = getCacheDir();
212
+ const result = {
213
+ items: 0,
214
+ totalBytes: 0,
215
+ expired: 0,
216
+ byCategory: {},
217
+ cacheDir: dir
218
+ };
219
+ try {
220
+ const files = readdirSync(dir);
221
+ for (const f of files) {
222
+ if (!f.endsWith(".json")) continue;
223
+ const filePath = join(dir, f);
224
+ try {
225
+ const st = statSync(filePath);
226
+ result.totalBytes += st.size;
227
+ const raw = readFileSync(filePath, "utf-8");
228
+ const entry = JSON.parse(raw);
229
+ result.items++;
230
+ if (Date.now() > entry.expiresAt) {
231
+ result.expired++;
232
+ }
233
+ const cat = entry.category || "unknown";
234
+ result.byCategory[cat] = (result.byCategory[cat] ?? 0) + 1;
235
+ } catch {
236
+ }
237
+ }
238
+ } catch {
239
+ }
240
+ return result;
241
+ }
242
+
243
+ // src/auth.ts
244
+ import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2, existsSync as existsSync2 } from "fs";
245
+ import { join as join2 } from "path";
246
+ import { homedir as homedir2 } from "os";
247
+ var CONFIG_DIR = join2(homedir2(), ".config", "bloom-cli");
248
+ var CONFIG_FILE = join2(CONFIG_DIR, "config.json");
15
249
  function readConfig() {
16
- if (!existsSync(CONFIG_FILE)) return {};
250
+ if (!existsSync2(CONFIG_FILE)) return {};
17
251
  try {
18
- return JSON.parse(readFileSync(CONFIG_FILE, "utf-8"));
252
+ return JSON.parse(readFileSync2(CONFIG_FILE, "utf-8"));
19
253
  } catch {
20
254
  return {};
21
255
  }
22
256
  }
23
- function writeConfig(config) {
257
+ function writeConfig(config2) {
24
258
  try {
25
- mkdirSync(CONFIG_DIR, { recursive: true });
26
- writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2) + "\n", {
259
+ mkdirSync2(CONFIG_DIR, { recursive: true });
260
+ writeFileSync2(CONFIG_FILE, JSON.stringify(config2, null, 2) + "\n", {
27
261
  mode: 384
28
262
  });
29
263
  } catch (err) {
@@ -41,36 +275,49 @@ function getApiKey() {
41
275
  function requireApiKey() {
42
276
  const key = getApiKey();
43
277
  if (!key) {
44
- console.error(
45
- "Error: No API key found. Set BLOOM_API_KEY or run: bloom auth login"
46
- );
47
- process.exit(1);
278
+ throw new AuthError("No API key found. Set BLOOM_API_KEY or run: bloom auth login");
48
279
  }
49
280
  return key;
50
281
  }
51
- function login(apiKey) {
52
- const config = readConfig();
53
- config.api_key = apiKey;
54
- writeConfig(config);
282
+ async function login(apiKey) {
283
+ const check = await verifyApiKey(apiKey);
284
+ if (check === "invalid") {
285
+ console.error(`Error: API key ${maskKey(apiKey)} was rejected by the server. Nothing was saved.`);
286
+ process.exit(1);
287
+ }
288
+ const config2 = readConfig();
289
+ config2.api_key = apiKey;
290
+ writeConfig(config2);
55
291
  console.log("API key saved to " + CONFIG_FILE);
292
+ if (check === "unverified") {
293
+ console.error("Warning: could not reach the server to verify the key.");
294
+ }
56
295
  }
57
296
  function logout() {
58
- if (existsSync(CONFIG_FILE)) {
59
- const config = readConfig();
60
- delete config.api_key;
61
- writeConfig(config);
297
+ if (existsSync2(CONFIG_FILE)) {
298
+ const config2 = readConfig();
299
+ delete config2.api_key;
300
+ writeConfig(config2);
62
301
  }
63
302
  console.log("Logged out. API key cleared.");
64
303
  }
65
- function status() {
304
+ async function status() {
66
305
  const envKey = process.env.BLOOM_API_KEY;
67
306
  const storedKey = readConfig().api_key;
68
- if (envKey) {
69
- console.log(`Authenticated via BLOOM_API_KEY (${maskKey(envKey)})`);
70
- } else if (storedKey) {
71
- console.log(`Authenticated via ${CONFIG_FILE} (${maskKey(storedKey)})`);
72
- } else {
307
+ const key = envKey || storedKey;
308
+ if (!key) {
73
309
  console.log("Not authenticated. Set BLOOM_API_KEY or run: bloom auth login");
310
+ process.exit(1);
311
+ }
312
+ const source = envKey ? "BLOOM_API_KEY" : CONFIG_FILE;
313
+ const check = await verifyApiKey(key);
314
+ if (check === "valid") {
315
+ console.log(`Authenticated via ${source} (${maskKey(key)})`);
316
+ } else if (check === "invalid") {
317
+ console.log(`Invalid key via ${source} (${maskKey(key)}): rejected by the server`);
318
+ process.exit(1);
319
+ } else {
320
+ console.log(`Key set via ${source} (${maskKey(key)}), not verified: server unreachable`);
74
321
  }
75
322
  }
76
323
  function maskKey(key) {
@@ -78,44 +325,32 @@ function maskKey(key) {
78
325
  return key.slice(0, 4) + "..." + key.slice(-4);
79
326
  }
80
327
 
81
- // src/commands/auth.ts
82
- import { createInterface } from "readline";
83
- function registerAuthCommand(program2) {
84
- const auth = program2.command("auth").description("Manage API authentication");
85
- auth.command("login").description("Store API key").argument("[key]", "API key (or pass via stdin)").action(async (key) => {
86
- if (!key) {
87
- const rl = createInterface({
88
- input: process.stdin,
89
- output: process.stderr
90
- });
91
- key = await new Promise((resolve) => {
92
- rl.question("API key: ", (answer) => {
93
- rl.close();
94
- resolve(answer.trim());
95
- });
96
- });
97
- }
98
- if (!key) {
99
- console.error("Error: No API key provided");
100
- process.exit(1);
101
- }
102
- login(key);
103
- });
104
- auth.command("status").description("Show current auth state").action(() => {
105
- status();
106
- });
107
- auth.command("logout").description("Clear stored credentials").action(() => {
108
- logout();
109
- });
110
- }
111
-
112
328
  // src/api.ts
113
- var API_BASE = "https://api.getbloom.app";
114
- var MCP_URL = `${API_BASE}/mcp/`;
329
+ var _apiBase = "https://api.getbloom.app";
330
+ function setApiBase(base) {
331
+ _apiBase = base;
332
+ }
115
333
  var requestId = 0;
334
+ async function verifyApiKey(apiKey) {
335
+ const url = `${_apiBase}/mcp/test-auth/`;
336
+ debugLog(`\u2192 GET ${url}`);
337
+ try {
338
+ const res = await fetch(url, {
339
+ headers: { Authorization: `Bearer ${apiKey}` },
340
+ signal: AbortSignal.timeout(1e4)
341
+ });
342
+ debugLog(`\u2190 ${res.status}`);
343
+ if (res.ok) return "valid";
344
+ if (res.status === 401 || res.status === 403) return "invalid";
345
+ } catch (err) {
346
+ debugLog(` key check failed: ${err instanceof Error ? err.message : String(err)}`);
347
+ }
348
+ return "unverified";
349
+ }
116
350
  async function callTool(toolName, args) {
117
351
  const apiKey = requireApiKey();
118
352
  requestId++;
353
+ const mcpUrl = `${_apiBase}/mcp/`;
119
354
  const body = {
120
355
  jsonrpc: "2.0",
121
356
  method: "tools/call",
@@ -125,7 +360,10 @@ async function callTool(toolName, args) {
125
360
  },
126
361
  id: requestId
127
362
  };
128
- const res = await fetch(MCP_URL, {
363
+ debugLog(`\u2192 POST ${mcpUrl}`);
364
+ debugLog(` tool: ${toolName}`, JSON.stringify(args));
365
+ const start = performance.now();
366
+ const res = await fetch(mcpUrl, {
129
367
  method: "POST",
130
368
  headers: {
131
369
  Authorization: `Bearer ${apiKey}`,
@@ -133,13 +371,15 @@ async function callTool(toolName, args) {
133
371
  },
134
372
  body: JSON.stringify(body)
135
373
  });
374
+ const elapsed = Math.round(performance.now() - start);
375
+ debugLog(`\u2190 ${res.status} (${elapsed}ms)`);
136
376
  if (!res.ok) {
137
377
  const text2 = await res.text().catch(() => "");
138
- throw new Error(`API error ${res.status}: ${text2 || res.statusText}`);
378
+ throw httpError(res.status, text2 || res.statusText);
139
379
  }
140
380
  const data = await res.json();
141
381
  if (data.error) {
142
- throw new Error(`MCP error ${data.error.code}: ${data.error.message}`);
382
+ throw mcpError(data.error.code, data.error.message);
143
383
  }
144
384
  if (!data.result?.content?.length) {
145
385
  throw new Error("Empty response from API");
@@ -153,12 +393,14 @@ async function callTool(toolName, args) {
153
393
  }
154
394
  async function callRest(path2, params) {
155
395
  const apiKey = requireApiKey();
156
- const url = new URL(path2, API_BASE);
396
+ const url = new URL(path2, _apiBase);
157
397
  if (params) {
158
398
  for (const [k, v] of Object.entries(params)) {
159
399
  url.searchParams.set(k, v);
160
400
  }
161
401
  }
402
+ debugLog(`\u2192 GET ${url.toString()}`);
403
+ const start = performance.now();
162
404
  const res = await fetch(url.toString(), {
163
405
  method: "GET",
164
406
  headers: {
@@ -166,17 +408,74 @@ async function callRest(path2, params) {
166
408
  "Content-Type": "application/json"
167
409
  }
168
410
  });
411
+ const elapsed = Math.round(performance.now() - start);
412
+ debugLog(`\u2190 ${res.status} (${elapsed}ms)`);
169
413
  if (!res.ok) {
170
414
  const text = await res.text().catch(() => "");
171
- throw new Error(`API error ${res.status}: ${text || res.statusText}`);
415
+ const ticker = path2.match(/^\/?investments\/([^/]+)\//)?.[1];
416
+ throw httpError(res.status, text || res.statusText, ticker && decodeURIComponent(ticker));
172
417
  }
173
418
  return res.json();
174
419
  }
420
+ async function callToolCached(toolName, args, category = "default") {
421
+ const cacheToolName = `${_apiBase}:${category}:${toolName}`;
422
+ const cached = getCached(cacheToolName, args);
423
+ if (cached !== void 0) {
424
+ return cached;
425
+ }
426
+ debugLog(`cache MISS ${toolName}`);
427
+ const result = await callTool(toolName, args);
428
+ setCached(cacheToolName, args, result, category);
429
+ return result;
430
+ }
431
+ async function callRestCached(path2, params, category = "default") {
432
+ const cacheToolName = `${_apiBase}:${category}:REST:${path2}`;
433
+ const cacheArgs = params ?? {};
434
+ const cached = getCached(cacheToolName, cacheArgs);
435
+ if (cached !== void 0) {
436
+ return cached;
437
+ }
438
+ debugLog(`cache MISS ${cacheToolName}`);
439
+ const result = await callRest(path2, params);
440
+ if (result?.results?.length !== 0) {
441
+ setCached(cacheToolName, cacheArgs, result, category);
442
+ }
443
+ return result;
444
+ }
445
+
446
+ // src/config.ts
447
+ import { readFileSync as readFileSync3, writeFileSync as writeFileSync3, mkdirSync as mkdirSync3, existsSync as existsSync3 } from "fs";
448
+ import { join as join3 } from "path";
449
+ import { homedir as homedir3 } from "os";
450
+ var CONFIG_DIR2 = join3(homedir3(), ".config", "bloom-cli");
451
+ var CONFIG_FILE2 = join3(CONFIG_DIR2, "config.json");
452
+ function readConfigFile() {
453
+ if (!existsSync3(CONFIG_FILE2)) return {};
454
+ try {
455
+ return JSON.parse(readFileSync3(CONFIG_FILE2, "utf-8"));
456
+ } catch {
457
+ return {};
458
+ }
459
+ }
460
+ function loadConfig(overrides) {
461
+ const file = readConfigFile();
462
+ return {
463
+ apiKey: process.env.BLOOM_API_KEY ?? file.api_key ?? overrides?.apiKey,
464
+ apiBase: process.env.BLOOM_API_BASE ?? file.api_base ?? overrides?.apiBase ?? "https://api.getbloom.app",
465
+ cacheDir: process.env.BLOOM_CACHE_DIR ?? file.cache_dir ?? overrides?.cacheDir ?? join3(homedir3(), ".cache", "bloom-cli"),
466
+ noCache: overrides?.noCache ?? false,
467
+ debug: overrides?.debug ?? false
468
+ };
469
+ }
470
+
471
+ // src/global-opts.ts
472
+ import { Option } from "commander";
175
473
 
176
474
  // src/format.ts
177
475
  import Table from "cli-table3";
178
- import { writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "fs";
476
+ import { writeFileSync as writeFileSync4, mkdirSync as mkdirSync4 } from "fs";
179
477
  import { dirname } from "path";
478
+ var FORMATS = ["json", "csv", "table", "markdown"];
180
479
  function resolveFormat(opts) {
181
480
  if (opts.format) return opts.format;
182
481
  if (opts.output || !process.stdout.isTTY) return "json";
@@ -187,15 +486,19 @@ function outputResult(data, opts, tableFormatter) {
187
486
  emit(JSON.stringify(data, null, 2), opts);
188
487
  return;
189
488
  }
190
- const fmt2 = resolveFormat(opts);
191
- if (fmt2 === "json") {
489
+ const fmt3 = resolveFormat(opts);
490
+ if (fmt3 === "json") {
192
491
  emit(JSON.stringify(data, null, 2), opts);
193
492
  return;
194
493
  }
195
- if (fmt2 === "csv") {
494
+ if (fmt3 === "csv") {
196
495
  emit(toCSV(data), opts);
197
496
  return;
198
497
  }
498
+ if (fmt3 === "markdown") {
499
+ emit(toMarkdown(data), opts);
500
+ return;
501
+ }
199
502
  if (tableFormatter) {
200
503
  emit(tableFormatter(data, opts), opts);
201
504
  } else {
@@ -204,8 +507,8 @@ function outputResult(data, opts, tableFormatter) {
204
507
  }
205
508
  function emit(content, opts) {
206
509
  if (opts.output) {
207
- mkdirSync2(dirname(opts.output), { recursive: true });
208
- writeFileSync2(opts.output, content + "\n");
510
+ mkdirSync4(dirname(opts.output), { recursive: true });
511
+ writeFileSync4(opts.output, content + "\n");
209
512
  if (!opts.quiet) {
210
513
  console.error(`Written to ${opts.output}`);
211
514
  }
@@ -228,6 +531,23 @@ function toCSV(data) {
228
531
  }
229
532
  return lines.join("\n");
230
533
  }
534
+ function toMarkdown(data, _title) {
535
+ const rows = toRows(data);
536
+ if (rows.length === 0) return "(no data)";
537
+ const headers = Array.from(new Set(rows.flatMap((row) => Object.keys(row))));
538
+ const lines = [];
539
+ lines.push("| " + headers.join(" | ") + " |");
540
+ lines.push("| " + headers.map(() => "---").join(" | ") + " |");
541
+ for (const row of rows) {
542
+ const vals = headers.map((h) => {
543
+ const v = row[h];
544
+ const s = String(v ?? "");
545
+ return s.replace(/\|/g, "\\|").replace(/\n/g, " ");
546
+ });
547
+ lines.push("| " + vals.join(" | ") + " |");
548
+ }
549
+ return lines.join("\n");
550
+ }
231
551
  function toRows(data) {
232
552
  const flatten = (v) => flattenObj(v);
233
553
  if (Array.isArray(data)) return data.map(flatten);
@@ -270,8 +590,11 @@ function flattenObj(obj, prefix = "") {
270
590
  return result;
271
591
  }
272
592
  function autoTable(data, opts) {
273
- const rows = toRows(data);
593
+ let rows = toRows(data);
274
594
  if (rows.length === 0) return "(no data)";
595
+ if (rows.length === 1 && Object.keys(rows[0]).length > 6) {
596
+ rows = Object.entries(rows[0]).map(([key, value]) => ({ key, value }));
597
+ }
275
598
  const headers = Object.keys(rows[0]);
276
599
  const table = new Table({
277
600
  head: opts?.quiet ? [] : headers,
@@ -297,16 +620,286 @@ function makeTable(headers, rows, opts) {
297
620
  function truncate(s, max) {
298
621
  return s.length > max ? s.slice(0, max - 1) + "\u2026" : s;
299
622
  }
300
- function parseIntSafe(value, fallback) {
301
- const n = parseInt(value, 10);
302
- return Number.isNaN(n) ? fallback : n;
623
+ function parseIntArg(value, name, min = 1, max = Number.MAX_SAFE_INTEGER) {
624
+ const n = /^-?\d+$/.test(value.trim()) ? Number(value) : NaN;
625
+ if (Number.isNaN(n) || n < min || n > max) {
626
+ const range = max === Number.MAX_SAFE_INTEGER ? `>= ${min}` : `${min}-${max}`;
627
+ throw new BloomError(`${name} must be a whole number ${range}, got "${value}"`);
628
+ }
629
+ return n;
303
630
  }
304
631
 
305
632
  // src/global-opts.ts
306
633
  function addGlobalOptions(cmd) {
307
- return cmd.option("-o, --output <file>", "Write output to file").option("-f, --format <fmt>", "Output format: json, csv, table").option("-q, --quiet", "Suppress headers, data only").option("--raw", "Raw JSON from API");
634
+ return cmd.option("-o, --output <file>", "Write output to file").addOption(
635
+ new Option("-f, --format <fmt>", "Output format").choices(FORMATS)
636
+ ).option("-q, --quiet", "Suppress headers, data only").option("--raw", "Raw JSON from API").option("--no-cache", "Bypass disk cache").option("--debug", "Show debug info on stderr");
308
637
  }
309
638
 
639
+ // src/commands/auth.ts
640
+ import { createInterface } from "readline";
641
+ function registerAuthCommand(program2) {
642
+ const auth = program2.command("auth").description("Manage API authentication");
643
+ auth.command("login").description("Store API key").argument("[key]", "API key (or pass via stdin)").action(async (key) => {
644
+ if (!key) {
645
+ key = (await readKey()).trim();
646
+ }
647
+ if (!key) {
648
+ console.error("Error: No API key provided");
649
+ process.exit(1);
650
+ }
651
+ await login(key);
652
+ });
653
+ auth.command("status").description("Show current auth state").action(status);
654
+ auth.command("logout").description("Clear stored credentials").action(() => {
655
+ logout();
656
+ });
657
+ }
658
+ async function readKey() {
659
+ const rl = createInterface({ input: process.stdin, output: process.stderr, prompt: "API key: " });
660
+ if (process.stdin.isTTY) rl.prompt();
661
+ for await (const line of rl) {
662
+ rl.close();
663
+ return line;
664
+ }
665
+ return "";
666
+ }
667
+
668
+ // src/client.ts
669
+ var _instance;
670
+ var BloomClient = class _BloomClient {
671
+ constructor() {
672
+ }
673
+ // --- Singleton ---
674
+ static instance() {
675
+ if (!_instance) {
676
+ _instance = new _BloomClient();
677
+ }
678
+ return _instance;
679
+ }
680
+ static resetInstance() {
681
+ _instance = void 0;
682
+ }
683
+ // --- Info ---
684
+ // cacheCategory lets the `quote` alias use the 5-minute quote TTL instead of
685
+ // the 24-hour info TTL, so an advertised "current" price is never a day old.
686
+ async getInfo(symbols, fields, cacheCategory = "info") {
687
+ const args = { symbols };
688
+ if (fields) args.fields = fields;
689
+ return callToolCached("get_symbols_metadata", args, cacheCategory);
690
+ }
691
+ // --- News ---
692
+ async getNews(symbols, limit = 15) {
693
+ return callToolCached("get_news_for_symbols", { symbols, limit }, "news");
694
+ }
695
+ // --- Price ---
696
+ async getPrice(symbol, timeframes, includeOhlc = false) {
697
+ return callToolCached("get_price_charts", {
698
+ symbol,
699
+ timeframes,
700
+ include_ohlc: includeOhlc
701
+ }, "quote");
702
+ }
703
+ // --- Financials ---
704
+ async getFinancials(symbol, chartType = "revenue") {
705
+ return callToolCached("get_financial_charts", { symbol, chart_type: chartType }, "financials");
706
+ }
707
+ // --- Earnings ---
708
+ async getEarnings(symbols) {
709
+ return callToolCached("analyze_earnings", { symbols }, "earnings");
710
+ }
711
+ // --- Earnings Calendar ---
712
+ async getEarningsCalendar(params) {
713
+ return callRestCached("/markets/earnings-calendar/", params, "earnings");
714
+ }
715
+ // --- Market briefing ---
716
+ async getMarketBriefing() {
717
+ return callTool("get_market_briefing", {});
718
+ }
719
+ // --- Sentiment ---
720
+ async getSentiment(sections) {
721
+ const args = {};
722
+ if (sections) args.sections = sections;
723
+ return callToolCached("get_market_sentiment", args, "sentiment");
724
+ }
725
+ // --- Market ---
726
+ async getMarket(mapType, period, limit, universe) {
727
+ return callToolCached("get_market_map", {
728
+ map_type: mapType,
729
+ period,
730
+ limit,
731
+ universe
732
+ }, "default");
733
+ }
734
+ // --- Collections ---
735
+ async getCollections(section, limit) {
736
+ return callToolCached("get_collections", { section, limit }, "default");
737
+ }
738
+ // --- Screen ---
739
+ async screen(args) {
740
+ return callToolCached("filter_stocks", args, "default");
741
+ }
742
+ // --- Technicals ---
743
+ async getTechnicals(symbols, sections) {
744
+ const args = { symbols };
745
+ if (sections) args.sections = sections;
746
+ return callToolCached("analyze_technicals", args, "technicals");
747
+ }
748
+ // --- Options ---
749
+ async getOptions(symbol, lookbackDays, weeklySampling, includeGreeks) {
750
+ return callToolCached("analyze_options_history", {
751
+ symbol,
752
+ lookback_days: lookbackDays,
753
+ weekly_sampling: weeklySampling,
754
+ include_greeks_analysis: includeGreeks
755
+ }, "technicals");
756
+ }
757
+ // --- Portfolio ---
758
+ async analyzePortfolio(holdings, strategy) {
759
+ const args = { holdings };
760
+ if (strategy) args.strategy = strategy;
761
+ return callToolCached("analyze_portfolio", args, "default");
762
+ }
763
+ // --- Trades ---
764
+ async evaluateTrades(trades) {
765
+ return callToolCached("analyze_trades", { trades }, "default");
766
+ }
767
+ // --- Catalysts ---
768
+ async getCatalysts(symbols) {
769
+ return callToolCached("generate_catalysts", { symbols }, "default");
770
+ }
771
+ // --- Position Size ---
772
+ async positionSize(args) {
773
+ return callToolCached("calculate_position_size", args, "default");
774
+ }
775
+ // --- Transcript ---
776
+ async searchTranscript(args) {
777
+ return callToolCached("search_transcript", args, "default");
778
+ }
779
+ // --- AI Trades ---
780
+ async getAiTrades(args) {
781
+ return callToolCached("get_ai_trade_ideas", args, "default");
782
+ }
783
+ // --- AI Portfolio ---
784
+ async getAiPortfolio(args) {
785
+ return callToolCached("get_ai_trade_ideas", args, "default");
786
+ }
787
+ // --- Moving Averages ---
788
+ // Folded into get_technicals as the "moving_averages" part. Unwrap the slice
789
+ // back into the {symbol, current_price, indicators} shape callers expect.
790
+ async getMovingAverages(symbol, indicators) {
791
+ const raw = await callToolCached(
792
+ "get_technicals",
793
+ { symbol, parts: ["moving_averages"], ma_indicators: indicators },
794
+ "technicals"
795
+ );
796
+ const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
797
+ const ma = parsed?.moving_averages;
798
+ if (ma && typeof ma === "object") {
799
+ return { symbol: parsed.symbol, ...ma };
800
+ }
801
+ return parsed;
802
+ }
803
+ // --- Backtest ---
804
+ async backtest(params) {
805
+ return callRestCached("backtest/", params, "default");
806
+ }
807
+ // --- Correlation ---
808
+ async correlation(params) {
809
+ return callRestCached("correlation/", params, "default");
810
+ }
811
+ // --- Risk ---
812
+ async getRisk(symbol) {
813
+ return callRestCached(`investments/${encodeURIComponent(symbol)}/risk_factors/`, void 0, "default");
814
+ }
815
+ // --- Drawdown ---
816
+ async getDrawdown(params) {
817
+ return callRestCached("portfolios/drawdown/", params, "default");
818
+ }
819
+ // --- Macro ---
820
+ async getMacro(args) {
821
+ return callToolCached("get_macro_indicators", args, "default");
822
+ }
823
+ // --- Sectors ---
824
+ async getSectors() {
825
+ return callToolCached("get_sector_performance", {}, "default");
826
+ }
827
+ // --- DCF ---
828
+ async getDcf(symbol) {
829
+ return callToolCached("get_dcf_valuation", { symbol }, "default");
830
+ }
831
+ // --- Holders ---
832
+ async getHolders(symbol) {
833
+ return callToolCached("get_holders", { symbol }, "default");
834
+ }
835
+ // --- Short Interest ---
836
+ async getShortInterest(symbol, limit) {
837
+ return callToolCached("get_short_interest", { symbol, limit }, "default");
838
+ }
839
+ // --- Insider ---
840
+ async getInsider(symbol, limit) {
841
+ return callToolCached("get_insider_trading", { symbol, limit }, "default");
842
+ }
843
+ // --- Dividends ---
844
+ async getDividends(args) {
845
+ return callToolCached("get_dividends", args, "default");
846
+ }
847
+ // --- Splits ---
848
+ async getSplits(args) {
849
+ return callToolCached("get_splits", args, "default");
850
+ }
851
+ // --- IPO ---
852
+ async getIpo(args) {
853
+ return callToolCached("get_ipo_calendar", args, "default");
854
+ }
855
+ // --- Compare ---
856
+ async compare(symbols) {
857
+ return callToolCached("get_symbols_metadata", { symbols }, "info");
858
+ }
859
+ // --- Ratings ---
860
+ async getRatings(symbol, limit) {
861
+ return callToolCached("get_analyst_ratings", { symbol, limit }, "default");
862
+ }
863
+ // --- Stats ---
864
+ async getStats(symbol) {
865
+ return callRestCached(`investments/${encodeURIComponent(symbol)}/stats/`, void 0, "quote");
866
+ }
867
+ // --- Peers ---
868
+ async getPeers(symbol) {
869
+ return callRestCached(`investments/${encodeURIComponent(symbol)}/peers/`, void 0, "quote");
870
+ }
871
+ // --- Bottom Line ---
872
+ async getBottomLine(symbol) {
873
+ return callRestCached(`investments/${encodeURIComponent(symbol)}/bottom_line_v2/`, void 0, "info");
874
+ }
875
+ // --- Insights ---
876
+ async getInsights(symbol, symbols) {
877
+ if (symbol) {
878
+ return callRestCached(`investments/${encodeURIComponent(symbol)}/insights/`, void 0, "default");
879
+ }
880
+ const params = {};
881
+ if (symbols) params.symbols = symbols.join(",");
882
+ return callRestCached("investments/all_insights/", params, "default");
883
+ }
884
+ // --- Arena Activity ---
885
+ async getArenaActivity(model, limit) {
886
+ const params = {};
887
+ if (model) params.model = model;
888
+ if (limit) params.limit = String(limit);
889
+ return callRestCached("api/arena/activity/", params, "default");
890
+ }
891
+ // --- Portfolio News ---
892
+ async getPortfolioNews(symbols) {
893
+ const params = {};
894
+ if (symbols) params.symbols = symbols.join(",");
895
+ return callRestCached("smart-summaries/portfolio-news/", params, "news");
896
+ }
897
+ // --- Collection Returns ---
898
+ async getCollectionReturns(collectionIds, timerange) {
899
+ return callRestCached("collections/returns/", { collection_ids: collectionIds, timerange }, "default");
900
+ }
901
+ };
902
+
310
903
  // src/commands/info.ts
311
904
  var VALID_FIELDS = [
312
905
  "basic_metadata",
@@ -318,15 +911,12 @@ var VALID_FIELDS = [
318
911
  ];
319
912
  function registerInfoCommand(program2) {
320
913
  addGlobalOptions(
321
- program2.command("info").description("Company fundamentals, ratings, peers, holdings").argument("<symbols...>", "Ticker symbols (e.g. AAPL MSFT)").option("--fields <fields>", "Comma-separated: " + VALID_FIELDS.join(","))
914
+ program2.command("info").alias("quote").description("Company fundamentals, ratings, peers, holdings").argument("<symbols...>", "Ticker symbols (e.g. AAPL MSFT)").option("--fields <fields>", "Comma-separated: " + VALID_FIELDS.join(","))
322
915
  ).action(async (symbols, opts) => {
323
- const args = {
324
- symbols: symbols.map((s) => s.toUpperCase())
325
- };
326
- if (opts.fields) {
327
- args.fields = opts.fields.split(",").map((f) => f.trim());
328
- }
329
- const data = await callTool("get_symbols_metadata", args);
916
+ const syms = symbols.map((s) => s.toUpperCase());
917
+ const fields = opts.fields?.split(",").map((f) => f.trim());
918
+ const cacheCategory = program2.args[0] === "quote" ? "quote" : "info";
919
+ const data = await BloomClient.instance().getInfo(syms, fields, cacheCategory);
330
920
  outputResult(data, opts, (d) => formatInfo(d));
331
921
  });
332
922
  }
@@ -382,10 +972,10 @@ Examples:
382
972
  $ bloom news AAPL MSFT GOOGL News for multiple stocks
383
973
  $ bloom news TSLA --limit 5 Last 5 Tesla articles
384
974
  `).action(async (symbols, opts) => {
385
- const data = await callTool("get_news_for_symbols", {
386
- symbols: symbols.map((s) => s.toUpperCase()),
387
- limit: parseIntSafe(opts.limit, 15)
388
- });
975
+ const data = await BloomClient.instance().getNews(
976
+ symbols.map((s) => s.toUpperCase()),
977
+ parseIntArg(opts.limit, "--limit")
978
+ );
389
979
  outputResult(data, opts, (d, o) => formatNews(d, o));
390
980
  });
391
981
  }
@@ -424,11 +1014,11 @@ Examples:
424
1014
  $ bloom price MSFT --ohlc Include open/high/low/close
425
1015
  $ bloom price AAPL -f csv -o prices.csv Export to CSV file
426
1016
  `).action(async (symbol, opts) => {
427
- const data = await callTool("get_price_charts", {
428
- symbol: symbol.toUpperCase(),
429
- timeframes: opts.timeframes.split(",").map((t) => t.trim()),
430
- include_ohlc: !!opts.ohlc
431
- });
1017
+ const data = await BloomClient.instance().getPrice(
1018
+ symbol.toUpperCase(),
1019
+ opts.timeframes.split(",").map((t) => t.trim()),
1020
+ !!opts.ohlc
1021
+ );
432
1022
  outputResult(data, opts, (d, o) => formatPrices(d, o));
433
1023
  });
434
1024
  }
@@ -478,7 +1068,8 @@ function formatPrices(data, opts) {
478
1068
  }
479
1069
 
480
1070
  // src/commands/financials.ts
481
- var CHART_TYPES = [
1071
+ import { Option as Option2 } from "commander";
1072
+ var VALID_TYPES = [
482
1073
  "revenue",
483
1074
  "revenue_growth",
484
1075
  "operating_margin",
@@ -491,22 +1082,35 @@ var CHART_TYPES = [
491
1082
  ];
492
1083
  function registerFinancialsCommand(program2) {
493
1084
  addGlobalOptions(
494
- program2.command("financials").description("Quarterly/annual financial data with YoY growth").argument("<symbol>", "Ticker symbol").option("--type <type>", "Chart type: " + CHART_TYPES.join(", "), "revenue")
1085
+ program2.command("financials").description("Financial charts: revenue, margins, earnings, FCF").argument("<symbol>", "Ticker symbol").addOption(
1086
+ new Option2("--type <type>", "Chart type").choices(VALID_TYPES).default("revenue")
1087
+ )
495
1088
  ).addHelpText("after", `
496
1089
  Examples:
497
- $ bloom financials AAPL Revenue (default)
498
- $ bloom financials TSLA --type operating_margin Operating margin trend
499
- $ bloom financials MSFT --type free_cash_flow Free cash flow history
500
- $ bloom financials NVDA --type net_earnings_growth Earnings growth rate
1090
+ $ bloom financials AAPL Revenue (default)
1091
+ $ bloom financials TSLA --type operating_margin Operating margins
1092
+ $ bloom financials MSFT --type free_cash_flow Free cash flow
1093
+ $ bloom financials NVDA --type revenue_growth Revenue growth rate
501
1094
  `).action(async (symbol, opts) => {
502
- const data = await callTool("get_financial_charts", {
503
- symbol: symbol.toUpperCase(),
504
- chart_type: opts.type
505
- });
1095
+ const sym = symbol.toUpperCase();
1096
+ const data = await BloomClient.instance().getFinancials(sym, opts.type);
506
1097
  outputResult(data, opts);
507
1098
  });
508
1099
  }
509
1100
 
1101
+ // src/commands/briefing.ts
1102
+ function registerBriefingCommand(program2) {
1103
+ addGlobalOptions(
1104
+ program2.command("briefing").description("Today's Morning Market Briefing, written once each trading day")
1105
+ ).action(async (opts) => {
1106
+ const data = await BloomClient.instance().getMarketBriefing();
1107
+ outputResult(data, opts, (d) => {
1108
+ const obj = d;
1109
+ return obj.briefing ?? "No briefing yet today (written each trading day around 10am ET).";
1110
+ });
1111
+ });
1112
+ }
1113
+
510
1114
  // src/commands/sentiment.ts
511
1115
  var SECTIONS = [
512
1116
  "aaii_sentiment",
@@ -522,11 +1126,8 @@ Examples:
522
1126
  $ bloom sentiment All sentiment indicators
523
1127
  $ bloom sentiment --sections aaii_sentiment,cnn_fear_greed Just AAII and Fear & Greed
524
1128
  `).action(async (opts) => {
525
- const args = {};
526
- if (opts.sections) {
527
- args.sections = opts.sections.split(",").map((s) => s.trim());
528
- }
529
- const data = await callTool("get_market_sentiment", args);
1129
+ const sections = opts.sections?.split(",").map((s) => s.trim());
1130
+ const data = await BloomClient.instance().getSentiment(sections);
530
1131
  outputResult(data, opts, (d) => formatSentiment(d));
531
1132
  });
532
1133
  }
@@ -565,12 +1166,12 @@ Examples:
565
1166
  $ bloom market --type top_movers --period 1w Weekly top movers
566
1167
  $ bloom market --universe sp500 --limit 10 Top 10 S&P 500 movers
567
1168
  `).action(async (opts) => {
568
- const data = await callTool("get_market_map", {
569
- map_type: opts.type,
570
- period: opts.period,
571
- limit: parseIntSafe(opts.limit, 24),
572
- universe: opts.universe
573
- });
1169
+ const data = await BloomClient.instance().getMarket(
1170
+ opts.type,
1171
+ opts.period,
1172
+ parseIntArg(opts.limit, "--limit"),
1173
+ opts.universe
1174
+ );
574
1175
  outputResult(data, opts);
575
1176
  });
576
1177
  }
@@ -586,10 +1187,10 @@ Examples:
586
1187
  $ bloom collections --section FAMOUS_INVESTORS Famous investor portfolios
587
1188
  $ bloom collections --section TRENDS --limit 3 Top 3 trending collections
588
1189
  `).action(async (opts) => {
589
- const data = await callTool("get_collections", {
590
- section: opts.section,
591
- limit: parseIntSafe(opts.limit, 6)
592
- });
1190
+ const data = await BloomClient.instance().getCollections(
1191
+ opts.section,
1192
+ parseIntArg(opts.limit, "--limit")
1193
+ );
593
1194
  outputResult(data, opts);
594
1195
  });
595
1196
  }
@@ -603,7 +1204,7 @@ function registerScreenCommand(program2) {
603
1204
  const args = {
604
1205
  filter_expressions: filters,
605
1206
  and_query: !opts.or,
606
- limit: parseIntSafe(opts.limit, 50)
1207
+ limit: parseIntArg(opts.limit, "--limit")
607
1208
  };
608
1209
  if (opts.symbols) {
609
1210
  args.symbols = opts.symbols.split(",").map((s) => s.trim().toUpperCase());
@@ -611,7 +1212,7 @@ function registerScreenCommand(program2) {
611
1212
  if (opts.fields) {
612
1213
  args.fields = opts.fields.split(",").map((f) => f.trim());
613
1214
  }
614
- const data = await callTool("filter_stocks", args);
1215
+ const data = await BloomClient.instance().screen(args);
615
1216
  outputResult(data, opts, (d, o) => formatScreen(d, o));
616
1217
  }
617
1218
  );
@@ -648,42 +1249,52 @@ function formatScreen(data, opts) {
648
1249
  return makeTable(headers, rows, opts);
649
1250
  }
650
1251
 
1252
+ // src/limits.ts
1253
+ var MAX_ANALYSIS_SYMBOLS = 10;
1254
+
651
1255
  // src/commands/earnings.ts
652
1256
  function registerEarningsCommand(program2) {
653
1257
  addGlobalOptions(
654
- program2.command("earnings").description("Earnings history, estimates, surprises").argument("<symbols...>", "Ticker symbols (up to 5)")
1258
+ program2.command("earnings").description("Earnings history, estimates, surprises").argument("<symbols...>", "Ticker symbols (up to 10)")
655
1259
  ).addHelpText("after", `
656
1260
  Examples:
657
1261
  $ bloom earnings AAPL Apple earnings history and surprises
658
1262
  $ bloom earnings AAPL MSFT GOOGL Compare earnings for multiple stocks
659
1263
  `).action(async (symbols, opts) => {
660
- const data = await callTool("analyze_earnings", {
661
- symbols: symbols.map((s) => s.toUpperCase()).slice(0, 5)
662
- });
1264
+ const syms = symbols.map((s) => s.toUpperCase()).slice(0, MAX_ANALYSIS_SYMBOLS);
1265
+ const data = await BloomClient.instance().getEarnings(syms);
663
1266
  outputResult(data, opts);
664
1267
  });
665
1268
  }
666
1269
 
667
1270
  // src/commands/earnings-calendar.ts
1271
+ function formatEps(value, currency) {
1272
+ if (value == null) return "\u2014";
1273
+ return !currency || currency === "USD" ? `$${value}` : `${value} ${currency}`;
1274
+ }
668
1275
  function registerEarningsCalendarCommand(program2) {
669
1276
  addGlobalOptions(
670
1277
  program2.command("earnings-calendar").description(
671
1278
  "Upcoming earnings dates (all companies, or filter by symbols)"
672
- ).argument("[symbols...]", "Ticker symbols (omit to show all)").option("--days <n>", "Look-ahead window in days (1-90)", "28")
1279
+ ).argument("[symbols...]", "Ticker symbols (omit to show all)").option("--days <n>", "Look-ahead window in days (1-90)", "28").option(
1280
+ "--popular",
1281
+ "Also include top companies by market cap, not just the given symbols"
1282
+ )
673
1283
  ).addHelpText("after", `
674
1284
  Examples:
675
1285
  $ bloom earnings-calendar AAPL MSFT GOOGL Upcoming earnings for these stocks
676
1286
  $ bloom earnings-calendar TSLA --days 7 Earnings within the next week
677
1287
  $ bloom earnings-calendar NVDA --days 90 Earnings within 90 days
1288
+ $ bloom earnings-calendar AAPL --popular AAPL plus the popular calendar
678
1289
  `).action(
679
1290
  async (symbols, opts) => {
680
- const days = parseIntSafe(opts.days, 28);
1291
+ const days = parseIntArg(opts.days, "--days", 1, 90);
681
1292
  const params = { days: String(days) };
682
1293
  if (symbols.length > 0) {
683
1294
  params.symbols = symbols.map((s) => s.toUpperCase()).join(",");
1295
+ if (!opts.popular) params.include_popular = "false";
684
1296
  }
685
- const data = await callRest(
686
- "/markets/earnings-calendar/",
1297
+ const data = await BloomClient.instance().getEarningsCalendar(
687
1298
  params
688
1299
  );
689
1300
  const items = data.results ?? [];
@@ -696,8 +1307,8 @@ Examples:
696
1307
  r.earnings_date ?? "\u2014",
697
1308
  r.symbol,
698
1309
  r.name,
699
- r.eps_estimate != null ? `$${r.eps_estimate}` : "\u2014",
700
- r.eps_actual != null ? `$${r.eps_actual}` : "\u2014"
1310
+ formatEps(r.eps_estimate, r.currency),
1311
+ formatEps(r.eps_actual, r.currency)
701
1312
  ]),
702
1313
  o
703
1314
  );
@@ -710,7 +1321,7 @@ Examples:
710
1321
  var SECTIONS2 = ["technical_indicators", "options_analysis", "insider_activity"];
711
1322
  function registerTechnicalsCommand(program2) {
712
1323
  addGlobalOptions(
713
- program2.command("technicals").description("RSI, MAs, patterns, options flow, insider trades").argument("<symbols...>", "Ticker symbols (up to 5)").option("--sections <s>", "Comma-separated: " + SECTIONS2.join(","))
1324
+ program2.command("technicals").description("RSI, MAs, patterns, options flow, insider trades").argument("<symbols...>", "Ticker symbols (up to 10)").option("--sections <s>", "Comma-separated: " + SECTIONS2.join(","))
714
1325
  ).addHelpText("after", `
715
1326
  Examples:
716
1327
  $ bloom technicals AAPL All technical data
@@ -718,13 +1329,9 @@ Examples:
718
1329
  $ bloom technicals NVDA --sections options_analysis Options flow only
719
1330
  $ bloom technicals AAPL --sections insider_activity Insider trades only
720
1331
  `).action(async (symbols, opts) => {
721
- const args = {
722
- symbols: symbols.map((s) => s.toUpperCase()).slice(0, 5)
723
- };
724
- if (opts.sections) {
725
- args.sections = opts.sections.split(",").map((s) => s.trim());
726
- }
727
- const data = await callTool("analyze_technicals", args);
1332
+ const syms = symbols.map((s) => s.toUpperCase()).slice(0, MAX_ANALYSIS_SYMBOLS);
1333
+ const sections = opts.sections?.split(",").map((s) => s.trim());
1334
+ const data = await BloomClient.instance().getTechnicals(syms, sections);
728
1335
  outputResult(data, opts);
729
1336
  });
730
1337
  }
@@ -741,12 +1348,12 @@ Examples:
741
1348
  $ bloom options-history AAPL --greeks Include advanced Greeks analysis
742
1349
  `).action(
743
1350
  async (symbol, opts) => {
744
- const data = await callTool("analyze_options_history", {
745
- symbol: symbol.toUpperCase(),
746
- lookback_days: parseIntSafe(opts.days, 30),
747
- weekly_sampling: opts.weekly ?? !opts.daily,
748
- include_greeks_analysis: !!opts.greeks
749
- });
1351
+ const data = await BloomClient.instance().getOptions(
1352
+ symbol.toUpperCase(),
1353
+ parseIntArg(opts.days, "--days", 7, 90),
1354
+ opts.weekly ?? !opts.daily,
1355
+ !!opts.greeks
1356
+ );
750
1357
  outputResult(data, opts);
751
1358
  }
752
1359
  );
@@ -761,12 +1368,14 @@ function registerPortfolioCommand(program2) {
761
1368
  try {
762
1369
  holdings = JSON.parse(holdingsStr);
763
1370
  } catch {
764
- console.error(`Error: Invalid JSON for holdings. Use format: '{"AAPL":0.3,"MSFT":0.7}'`);
765
- process.exit(1);
766
1371
  }
767
- const args = { holdings };
768
- if (opts.strategy) args.strategy = opts.strategy;
769
- const data = await callTool("analyze_portfolio", args);
1372
+ const valid = holdings !== null && typeof holdings === "object" && !Array.isArray(holdings) && Object.keys(holdings).length > 0 && Object.values(holdings).every((w) => typeof w === "number" && Number.isFinite(w));
1373
+ if (!valid) {
1374
+ throw new BloomError(
1375
+ `holdings must be a JSON object of symbol to numeric weight, e.g. '{"AAPL":0.3,"MSFT":0.7}'`
1376
+ );
1377
+ }
1378
+ const data = await BloomClient.instance().analyzePortfolio(holdings, opts.strategy);
770
1379
  outputResult(data, opts);
771
1380
  });
772
1381
  }
@@ -781,7 +1390,7 @@ Examples:
781
1390
  $ bloom trades "Sell MSFT 20% to take profits" "Buy GOOGL 15% on AI momentum"
782
1391
  `).action(async (tradeStrs, opts) => {
783
1392
  const trades = tradeStrs.map(parseTrade);
784
- const data = await callTool("analyze_trades", { trades });
1393
+ const data = await BloomClient.instance().evaluateTrades(trades);
785
1394
  outputResult(data, opts);
786
1395
  });
787
1396
  }
@@ -811,15 +1420,15 @@ Format: "Buy AAPL 30% because thesis" or JSON object`
811
1420
  // src/commands/catalysts.ts
812
1421
  function registerCatalystsCommand(program2) {
813
1422
  addGlobalOptions(
814
- program2.command("catalysts").description("Forward-looking value catalysts").argument("<symbols...>", "Ticker symbols (up to 5)")
1423
+ program2.command("catalysts").description("Forward-looking value catalysts").argument("<symbols...>", "Ticker symbols (up to 10)")
815
1424
  ).addHelpText("after", `
816
1425
  Examples:
817
1426
  $ bloom catalysts AAPL Upcoming catalysts for Apple
818
1427
  $ bloom catalysts TSLA NVDA AMZN Catalysts for multiple stocks
819
1428
  `).action(async (symbols, opts) => {
820
- const data = await callTool("generate_catalysts", {
821
- symbols: symbols.map((s) => s.toUpperCase()).slice(0, 5)
822
- });
1429
+ const data = await BloomClient.instance().getCatalysts(
1430
+ symbols.map((s) => s.toUpperCase()).slice(0, MAX_ANALYSIS_SYMBOLS)
1431
+ );
823
1432
  outputResult(data, opts);
824
1433
  });
825
1434
  }
@@ -848,11 +1457,11 @@ function registerPositionCommand(program2) {
848
1457
  const args = {
849
1458
  bull_return: bullReturn,
850
1459
  bear_return: bearReturn,
851
- conviction: parseIntSafe(opts.conviction, 5),
1460
+ conviction: parseIntArg(opts.conviction, "--conviction", 1, 10),
852
1461
  portfolio_value: portfolioValue
853
1462
  };
854
1463
  if (opts.symbol) args.symbol = opts.symbol.toUpperCase();
855
- const data = await callTool("calculate_position_size", args);
1464
+ const data = await BloomClient.instance().positionSize(args);
856
1465
  outputResult(data, opts);
857
1466
  }
858
1467
  );
@@ -861,16 +1470,16 @@ function registerPositionCommand(program2) {
861
1470
  // src/commands/transcript.ts
862
1471
  function registerTranscriptCommand(program2) {
863
1472
  addGlobalOptions(
864
- program2.command("transcript").description("Search earnings call transcripts").argument("<symbol>", "Ticker symbol").argument("<keywords...>", "Keywords to search (OR logic)").option("--quarter <q>", 'Fiscal quarter, e.g. "Q1 2024"').option("--max <n>", "Max results", "10")
1473
+ program2.command("transcript").alias("transcripts").description("Search earnings call transcripts").argument("<symbol>", "Ticker symbol").argument("<keywords...>", "Keywords to search (OR logic)").option("--quarter <q>", 'Fiscal quarter, e.g. "Q1 2024"').option("--max <n>", "Max results", "10")
865
1474
  ).action(
866
1475
  async (symbol, keywords, opts) => {
867
1476
  const args = {
868
1477
  symbol: symbol.toUpperCase(),
869
1478
  keywords,
870
- max_results: parseIntSafe(opts.max, 10)
1479
+ max_results: parseIntArg(opts.max, "--max")
871
1480
  };
872
1481
  if (opts.quarter) args.fiscal_quarter = opts.quarter;
873
- const data = await callTool("search_transcript", args);
1482
+ const data = await BloomClient.instance().searchTranscript(args);
874
1483
  outputResult(data, opts, (d, o) => formatTranscript(d, o));
875
1484
  }
876
1485
  );
@@ -913,11 +1522,11 @@ function registerAiTradesCommand(program2) {
913
1522
  program2.command("ai-trades").description("Recent trade decisions from AI models competing with real money (InvestingArena)").option("--model <m>", "Filter by AI model: claude|openai|gemini").option("--symbol <s>", "Filter by stock ticker symbol (e.g., AAPL)").option("--limit <n>", "Max recent trades per model (default: 10, max: 50)", "10")
914
1523
  ).action(async (opts) => {
915
1524
  const args = {
916
- limit: parseIntSafe(opts.limit, 10)
1525
+ limit: parseIntArg(opts.limit, "--limit", 1, 50)
917
1526
  };
918
1527
  if (opts.model) args.ai_model = opts.model;
919
1528
  if (opts.symbol) args.symbol = opts.symbol.toUpperCase();
920
- const data = await callTool("get_ai_trade_ideas", args);
1529
+ const data = await BloomClient.instance().getAiTrades(args);
921
1530
  if (opts.raw) {
922
1531
  outputResult(data, opts);
923
1532
  return;
@@ -945,7 +1554,7 @@ function formatTrades(data, opts) {
945
1554
  String(t.shares ?? "-"),
946
1555
  t.fill_price != null ? `$${Number(t.fill_price).toFixed(2)}` : "-",
947
1556
  gain,
948
- truncate2(String(t.rationale ?? "-"), 60)
1557
+ truncate(String(t.rationale ?? "-"), 60)
949
1558
  ];
950
1559
  });
951
1560
  return makeTable(
@@ -954,9 +1563,6 @@ function formatTrades(data, opts) {
954
1563
  opts
955
1564
  );
956
1565
  }
957
- function truncate2(s, max) {
958
- return s.length > max ? s.slice(0, max - 1) + "\u2026" : s;
959
- }
960
1566
 
961
1567
  // src/commands/ai-portfolio.ts
962
1568
  function registerAiPortfolioCommand(program2) {
@@ -970,7 +1576,7 @@ Examples:
970
1576
  `).action(async (opts) => {
971
1577
  const args = {};
972
1578
  if (opts.model) args.ai_model = opts.model;
973
- const data = await callTool("get_ai_trade_ideas", args);
1579
+ const data = await BloomClient.instance().getAiPortfolio(args);
974
1580
  if (opts.raw) {
975
1581
  outputResult(data, opts);
976
1582
  return;
@@ -1077,6 +1683,7 @@ function registerMaCommand(program2) {
1077
1683
  program2.command("ma").description("Moving averages (SMA/EMA) for a symbol").argument("<symbol>", "Ticker symbol (e.g., AAPL)").option("--sma <periods>", "Comma-separated SMA periods (e.g., 50,100,200)").option("--ema <periods>", "Comma-separated EMA periods (e.g., 20,50)").option("--limit <n>", "Number of data points to display (default: 20)", "20")
1078
1684
  ).action(
1079
1685
  async (symbol, opts) => {
1686
+ const limit = parseIntArg(opts.limit, "--limit");
1080
1687
  const indicators = [];
1081
1688
  if (opts.sma) {
1082
1689
  for (const p of opts.sma.split(",")) {
@@ -1093,12 +1700,10 @@ function registerMaCommand(program2) {
1093
1700
  if (indicators.length === 0) {
1094
1701
  indicators.push("sma_100", "ema_100");
1095
1702
  }
1096
- const args = {
1097
- symbol: symbol.toUpperCase(),
1703
+ const data = await BloomClient.instance().getMovingAverages(
1704
+ symbol.toUpperCase(),
1098
1705
  indicators
1099
- };
1100
- const data = await callTool("get_moving_averages", args);
1101
- const limit = parseInt(opts.limit, 10) || 20;
1706
+ );
1102
1707
  let parsed = null;
1103
1708
  try {
1104
1709
  parsed = typeof data === "string" ? JSON.parse(data) : data;
@@ -1142,7 +1747,7 @@ function registerBacktestCommand(program2) {
1142
1747
  addGlobalOptions(
1143
1748
  program2.command("backtest").description("Backtest a portfolio against a benchmark").requiredOption("--symbols <s>", "Comma-separated symbols (e.g., AAPL,MSFT)").requiredOption("--allocations <a>", "Comma-separated weights (e.g., 0.5,0.5)").option("--benchmark <b>", "Benchmark symbol (default: SPY)", "SPY").option("--strategy <s>", "Strategy: buy_and_hold", "buy_and_hold")
1144
1749
  ).action(async (opts) => {
1145
- const data = await callRest("backtest/", {
1750
+ const data = await BloomClient.instance().backtest({
1146
1751
  symbols: opts.symbols,
1147
1752
  allocations: opts.allocations,
1148
1753
  benchmark: opts.benchmark,
@@ -1169,7 +1774,9 @@ function formatBacktest(data) {
1169
1774
  ]);
1170
1775
  }
1171
1776
  if (rows.length === 0) return JSON.stringify(data, null, 2);
1172
- return makeTable(["Interval", "Return", "Benchmark", "Alpha", "Sharpe", "Max DD"], rows);
1777
+ const table = makeTable(["Interval", "Return", "Benchmark", "Alpha", "Sharpe", "Max DD"], rows);
1778
+ const warnings = Array.isArray(obj.warnings) ? obj.warnings : [];
1779
+ return [table, ...warnings.map((w) => `Warning: ${w}`)].join("\n");
1173
1780
  }
1174
1781
  function fmt(v) {
1175
1782
  if (v == null || v === "") return "-";
@@ -1199,7 +1806,7 @@ Examples:
1199
1806
  };
1200
1807
  if (opts.start) params.start_date = opts.start;
1201
1808
  if (opts.end) params.end_date = opts.end;
1202
- const data = await callRest("correlation/", params);
1809
+ const data = await BloomClient.instance().correlation(params);
1203
1810
  outputResult(data, opts, formatCorrelation);
1204
1811
  });
1205
1812
  }
@@ -1216,29 +1823,56 @@ function formatCorrelation(data) {
1216
1823
  }
1217
1824
 
1218
1825
  // src/commands/risk.ts
1826
+ var STALE_DAYS = 456;
1219
1827
  function registerRiskCommand(program2) {
1220
1828
  addGlobalOptions(
1221
- program2.command("risk").description("Risk factors for a stock").argument("<symbol>", "Ticker symbol")
1829
+ program2.command("risk").description("Risk factors from the company's latest ingested SEC 10-K (check filingDate)").argument("<symbol>", "Ticker symbol")
1222
1830
  ).addHelpText("after", `
1831
+ Each row carries filingDate/periodEnd for its 10-K (null on older rows; use
1832
+ created). A warning goes to stderr when the source is over ~15 months old.
1833
+
1223
1834
  Examples:
1224
1835
  $ bloom risk AAPL Risk factors for Apple
1225
1836
  $ bloom risk TSLA Risk factors for Tesla
1226
1837
  `).action(async (symbol, opts) => {
1227
- const data = await callRest(`investments/${symbol.toUpperCase()}/risk_factors/`);
1838
+ const data = await BloomClient.instance().getRisk(symbol.toUpperCase());
1839
+ const warning = staleWarning(riskRows(data));
1840
+ if (warning && !opts.quiet) console.error(warning);
1228
1841
  outputResult(data, opts, formatRisk);
1229
1842
  });
1230
1843
  }
1231
- function formatRisk(data) {
1232
- if (!Array.isArray(data)) return JSON.stringify(data, null, 2);
1233
- if (data.length === 0) return "(no risk factors found)";
1234
- const rows = data.map((r) => [
1235
- String(r.category ?? r.risk_type ?? "-"),
1236
- truncate3(String(r.description ?? r.text ?? "-"), 80)
1237
- ]);
1238
- return makeTable(["Category", "Description"], rows);
1844
+ function riskRows(data) {
1845
+ return data?.results ?? [];
1239
1846
  }
1240
- function truncate3(s, max) {
1241
- return s.length > max ? s.slice(0, max - 1) + "\u2026" : s;
1847
+ function sourceInfo(rows) {
1848
+ let best = null;
1849
+ for (const r of rows) {
1850
+ const raw = r.filingDate ?? r.created;
1851
+ if (!raw) continue;
1852
+ const date = String(raw).slice(0, 10);
1853
+ if (!best || date > best.date) best = { date, how: r.filingDate ? "filed" : "ingested" };
1854
+ }
1855
+ return best;
1856
+ }
1857
+ function staleWarning(rows) {
1858
+ const src = sourceInfo(rows);
1859
+ if (!src) return null;
1860
+ const ageDays = (Date.now() - Date.parse(src.date)) / 864e5;
1861
+ if (ageDays <= STALE_DAYS) return null;
1862
+ return `Warning: these risk factors come from a 10-K ${src.how} ${src.date} (${Math.floor(ageDays / 30)} months ago) and may be out of date.`;
1863
+ }
1864
+ function formatRisk(data) {
1865
+ const rows = riskRows(data);
1866
+ if (rows.length === 0) return "(no risk factors found)";
1867
+ const src = sourceInfo(rows);
1868
+ const period = rows.find((r) => r.periodEnd)?.periodEnd;
1869
+ const header = `Source: SEC 10-K${src ? ` ${src.how} ${src.date}` : ""}${period ? ` (fiscal year ended ${period})` : ""}`;
1870
+ const table = makeTable(
1871
+ ["Risk"],
1872
+ rows.map((r) => [truncate(String(r.keyPoint ?? r.details ?? "-"), 100)])
1873
+ );
1874
+ return `${header}
1875
+ ${table}`;
1242
1876
  }
1243
1877
 
1244
1878
  // src/commands/drawdown.ts
@@ -1246,52 +1880,24 @@ function registerDrawdownCommand(program2) {
1246
1880
  addGlobalOptions(
1247
1881
  program2.command("drawdown").description("Portfolio drawdown analysis").requiredOption("--symbols <s>", "Comma-separated symbols (e.g., AAPL,MSFT)").requiredOption("--allocations <a>", "Comma-separated weights (e.g., 0.5,0.5)")
1248
1882
  ).action(async (opts) => {
1249
- const data = await callRest("portfolios/drawdown/", {
1883
+ const data = await BloomClient.instance().getDrawdown({
1250
1884
  symbols: opts.symbols,
1251
1885
  allocations: opts.allocations
1252
1886
  });
1253
1887
  outputResult(data, opts, formatDrawdown);
1254
1888
  });
1255
1889
  }
1256
- function formatDrawdown(data) {
1257
- const obj = data;
1258
- if (!obj || typeof obj !== "object") return JSON.stringify(data, null, 2);
1259
- const intervals = obj.interval_results ?? obj;
1260
- const rows = [];
1261
- for (const [interval, dd] of Object.entries(intervals)) {
1262
- if (typeof dd !== "object" || !dd) continue;
1263
- const d = dd;
1264
- let troughDate = "-";
1265
- let recoveryDate = "not recovered";
1266
- const plotData = d.plot_data;
1267
- if (plotData && plotData.length > 0) {
1268
- let minDD = 0;
1269
- let minIdx = -1;
1270
- for (let i = 0; i < plotData.length; i++) {
1271
- if (plotData[i].drawdown < minDD) {
1272
- minDD = plotData[i].drawdown;
1273
- minIdx = i;
1274
- }
1275
- }
1276
- if (minIdx >= 0) {
1277
- troughDate = plotData[minIdx].date;
1278
- for (let i = minIdx + 1; i < plotData.length; i++) {
1279
- if (plotData[i].drawdown >= 0) {
1280
- recoveryDate = plotData[i].date;
1281
- break;
1282
- }
1283
- }
1284
- }
1285
- }
1286
- rows.push([
1287
- interval,
1288
- d.max_drawdown != null ? `${(Number(d.max_drawdown) * 100).toFixed(2)}%` : "-",
1289
- troughDate,
1290
- recoveryDate
1291
- ]);
1292
- }
1293
- if (rows.length === 0) return JSON.stringify(data, null, 2);
1294
- return makeTable(["Interval", "Max Drawdown", "Trough Date", "Recovery"], rows);
1890
+ function formatDrawdown(data, opts) {
1891
+ const intervals = data?.interval_results;
1892
+ if (!intervals) return JSON.stringify(data, null, 2);
1893
+ const rows = Object.entries(intervals).map(([iv, r]) => [iv, fmt2(r.max_drawdown ?? r.error)]);
1894
+ return makeTable(["Interval", "Max Drawdown"], rows, opts);
1895
+ }
1896
+ function fmt2(v) {
1897
+ if (v == null) return "-";
1898
+ const n = Number(v);
1899
+ if (isNaN(n)) return String(v);
1900
+ return `${(n * 100).toFixed(2)}%`;
1295
1901
  }
1296
1902
 
1297
1903
  // src/commands/macro.ts
@@ -1308,7 +1914,7 @@ Examples:
1308
1914
  if (opts.indicators) {
1309
1915
  args.indicators = opts.indicators;
1310
1916
  }
1311
- const data = await callTool("get_macro_indicators", args);
1917
+ const data = await BloomClient.instance().getMacro(args);
1312
1918
  outputResult(data, opts, formatMacro);
1313
1919
  });
1314
1920
  }
@@ -1345,7 +1951,7 @@ Examples:
1345
1951
  $ bloom sectors Sector performance across all time periods
1346
1952
  $ bloom sectors -f json Output as JSON
1347
1953
  `).action(async (opts) => {
1348
- const data = await callTool("get_sector_performance", {});
1954
+ const data = await BloomClient.instance().getSectors();
1349
1955
  outputResult(data, opts, formatSectors);
1350
1956
  });
1351
1957
  }
@@ -1404,7 +2010,7 @@ Examples:
1404
2010
  $ bloom dcf TSLA DCF valuation for Tesla
1405
2011
  `).action(async (symbol, opts) => {
1406
2012
  const sym = symbol.toUpperCase();
1407
- const result = await callTool("get_dcf_valuation", { symbol: sym });
2013
+ const result = await BloomClient.instance().getDcf(sym);
1408
2014
  outputResult(result, opts, () => formatDcf(result, sym));
1409
2015
  });
1410
2016
  }
@@ -1428,39 +2034,27 @@ function formatDcf(data, symbol) {
1428
2034
  // src/commands/holders.ts
1429
2035
  function registerHoldersCommand(program2) {
1430
2036
  addGlobalOptions(
1431
- program2.command("holders").description("Institutional and mutual fund holders").argument("<symbol>", "Ticker symbol").option("--type <t>", "institutional or mutual-fund (default: both)").option("--limit <n>", "Max holders to show", "15")
2037
+ program2.command("holders").description("Institutional holders of a stock").argument("<symbol>", "Ticker symbol")
1432
2038
  ).addHelpText("after", `
1433
2039
  Examples:
1434
- $ bloom holders AAPL All holders (institutional + mutual fund)
1435
- $ bloom holders TSLA --type institutional Institutional holders only
1436
- $ bloom holders NVDA --limit 5 Top 5 holders
2040
+ $ bloom holders AAPL Top institutional holders of Apple
2041
+ $ bloom holders TSLA Tesla's institutional ownership
1437
2042
  `).action(async (symbol, opts) => {
1438
2043
  const sym = symbol.toUpperCase();
1439
- const limit = parseIntSafe(opts.limit, 15);
1440
- const args = { symbol: sym };
1441
- if (opts.type) args.holder_type = opts.type;
1442
- const data = await callTool("get_holders", args);
1443
- outputResult(data, opts, () => formatHolders(data, limit));
2044
+ const data = await BloomClient.instance().getHolders(sym);
2045
+ outputResult(data, opts, formatHolders);
1444
2046
  });
1445
2047
  }
1446
- function formatHolders(data, limit) {
1447
- const parts = [];
1448
- const addSection = (title, list) => {
1449
- const items = list;
1450
- if (items && items.length > 0) {
1451
- const rows = items.slice(0, limit).map((h) => [
1452
- String(h.holder ?? "-"),
1453
- fmtNum2(h.shares),
1454
- h.dateReported ? String(h.dateReported).slice(0, 10) : "-",
1455
- fmtNum2(h.change)
1456
- ]);
1457
- parts.push(`${title}
1458
- ${makeTable(["Holder", "Shares", "Date", "Change"], rows)}`);
1459
- }
1460
- };
1461
- addSection("INSTITUTIONAL HOLDERS", data.institutional);
1462
- addSection("MUTUAL FUND HOLDERS", data.mutual_fund);
1463
- return parts.length > 0 ? parts.join("\n\n") : "(no holder data found)";
2048
+ function formatHolders(data) {
2049
+ if (!Array.isArray(data) || data.length === 0) return "(no holders data)";
2050
+ const rows = data.map((h) => [
2051
+ String(h.holder ?? "-"),
2052
+ fmtNum2(h.shares),
2053
+ h.dateReported ? String(h.dateReported).slice(0, 10) : "-",
2054
+ h.change != null ? String(h.change) : "-",
2055
+ h.weightPercent != null ? `${Number(h.weightPercent).toFixed(2)}%` : "-"
2056
+ ]);
2057
+ return makeTable(["Holder", "Shares", "Date", "Change", "Weight %"], rows);
1464
2058
  }
1465
2059
  function fmtNum2(v) {
1466
2060
  if (v == null) return "-";
@@ -1482,8 +2076,8 @@ Examples:
1482
2076
  $ bloom short-interest AMC --limit 20 Last 20 short interest records
1483
2077
  `).action(async (symbol, opts) => {
1484
2078
  const sym = symbol.toUpperCase();
1485
- const limit = parseIntSafe(opts.limit, 10);
1486
- const data = await callTool("get_short_interest", { symbol: sym, limit });
2079
+ const limit = parseIntArg(opts.limit, "--limit");
2080
+ const data = await BloomClient.instance().getShortInterest(sym, limit);
1487
2081
  outputResult(data, opts, formatShort);
1488
2082
  });
1489
2083
  }
@@ -1512,33 +2106,28 @@ function fmtNum3(v) {
1512
2106
  // src/commands/insider.ts
1513
2107
  function registerInsiderCommand(program2) {
1514
2108
  addGlobalOptions(
1515
- program2.command("insider").description("Insider trading activity (SEC Form 4)").argument("<symbol>", "Ticker symbol").option("--limit <n>", "Max transactions to show", "20")
2109
+ program2.command("insider").description("Insider trading activity").argument("<symbol>", "Ticker symbol").option("--limit <n>", "Max records", "20")
1516
2110
  ).addHelpText("after", `
1517
2111
  Examples:
1518
2112
  $ bloom insider AAPL Recent insider trades for Apple
1519
- $ bloom insider TSLA --limit 5 Last 5 insider transactions
2113
+ $ bloom insider TSLA --limit 10 Last 10 insider transactions
1520
2114
  `).action(async (symbol, opts) => {
1521
2115
  const sym = symbol.toUpperCase();
1522
- const limit = parseIntSafe(opts.limit, 20);
1523
- const data = await callTool("get_insider_trading", { symbol: sym, limit });
2116
+ const limit = parseIntArg(opts.limit, "--limit");
2117
+ const data = await BloomClient.instance().getInsider(sym, limit);
1524
2118
  outputResult(data, opts, formatInsider);
1525
2119
  });
1526
2120
  }
1527
2121
  function formatInsider(data) {
1528
- if (!Array.isArray(data) || data.length === 0) return "(no insider trading data)";
1529
- const rows = data.map((t) => {
1530
- const val = t.securitiesTransacted && t.price ? `$${(Number(t.securitiesTransacted) * Number(t.price)).toLocaleString()}` : "-";
1531
- return [
1532
- String(t.filingDate ?? t.transactionDate ?? "-").slice(0, 10),
1533
- String(t.reportingName ?? "-"),
1534
- String(t.typeOfOwner ?? "-"),
1535
- String(t.transactionType ?? t.acquistionOrDisposition ?? "-"),
1536
- fmtNum4(t.securitiesTransacted),
1537
- t.price != null ? `$${Number(t.price).toFixed(2)}` : "-",
1538
- val
1539
- ];
1540
- });
1541
- return makeTable(["Date", "Name", "Title", "Type", "Shares", "Price", "Value"], rows);
2122
+ if (!Array.isArray(data) || data.length === 0) return "(no insider data)";
2123
+ const rows = data.map((r) => [
2124
+ String(r.filingDate ?? r.date ?? "-").slice(0, 10),
2125
+ String(r.reportingName ?? r.name ?? "-"),
2126
+ String(r.transactionType ?? r.type ?? "-"),
2127
+ r.securitiesTransacted != null ? fmtNum4(r.securitiesTransacted) : "-",
2128
+ r.price != null ? `$${Number(r.price).toFixed(2)}` : "-"
2129
+ ]);
2130
+ return makeTable(["Date", "Name", "Type", "Shares", "Price"], rows);
1542
2131
  }
1543
2132
  function fmtNum4(v) {
1544
2133
  if (v == null) return "-";
@@ -1558,10 +2147,10 @@ Examples:
1558
2147
  $ bloom dividends JNJ --from 2024-01-01 Dividends since Jan 2024
1559
2148
  `).action(async (symbol, opts) => {
1560
2149
  const sym = symbol.toUpperCase();
1561
- const limit = parseIntSafe(opts.limit, 20);
2150
+ const limit = parseIntArg(opts.limit, "--limit");
1562
2151
  const args = { symbol: sym, limit };
1563
2152
  if (opts.from) args.from_date = opts.from;
1564
- const data = await callTool("get_dividends", args);
2153
+ const data = await BloomClient.instance().getDividends(args);
1565
2154
  outputResult(data, opts, formatDividends);
1566
2155
  });
1567
2156
  }
@@ -1590,7 +2179,7 @@ Examples:
1590
2179
  const sym = symbol.toUpperCase();
1591
2180
  const args = { symbol: sym };
1592
2181
  if (opts.from) args.from_date = opts.from;
1593
- const data = await callTool("get_splits", args);
2182
+ const data = await BloomClient.instance().getSplits(args);
1594
2183
  outputResult(data, opts, formatSplits);
1595
2184
  });
1596
2185
  }
@@ -1606,31 +2195,30 @@ function formatSplits(data) {
1606
2195
  // src/commands/ipo.ts
1607
2196
  function registerIpoCommand(program2) {
1608
2197
  addGlobalOptions(
1609
- program2.command("ipo").description("Upcoming and recent IPOs").option("--from <date>", "Start date (YYYY-MM-DD)").option("--to <date>", "End date (YYYY-MM-DD)")
2198
+ program2.command("ipo").description("IPO calendar and recent filings").option("--from <date>", "Start date (YYYY-MM-DD)").option("--to <date>", "End date (YYYY-MM-DD)")
1610
2199
  ).addHelpText("after", `
1611
2200
  Examples:
1612
- $ bloom ipo Recent and upcoming IPOs
1613
- $ bloom ipo --from 2025-01-01 --to 2025-06-30 IPOs in H1 2025
2201
+ $ bloom ipo Upcoming and recent IPOs
2202
+ $ bloom ipo --from 2025-01-01 IPOs since Jan 2025
1614
2203
  `).action(async (opts) => {
1615
2204
  const args = {};
1616
2205
  if (opts.from) args.from_date = opts.from;
1617
2206
  if (opts.to) args.to_date = opts.to;
1618
- const data = await callTool("get_ipo_calendar", args);
1619
- outputResult(data, opts, formatIpos);
2207
+ const data = await BloomClient.instance().getIpo(args);
2208
+ outputResult(data, opts, formatIpo);
1620
2209
  });
1621
2210
  }
1622
- function formatIpos(data) {
1623
- const ipos = Array.isArray(data) ? data : data?.ipos;
1624
- if (!Array.isArray(ipos) || ipos.length === 0) return "(no IPO data found)";
1625
- const rows = ipos.map((ipo) => [
1626
- String(ipo.date ?? ipo.start_date ?? "-"),
1627
- String(ipo.name ?? ipo.company ?? "-"),
1628
- String(ipo.code ?? ipo.ticker ?? ipo.symbol ?? "-"),
1629
- String(ipo.exchange ?? "-"),
1630
- ipo.price_from && ipo.price_to ? `$${ipo.price_from}-$${ipo.price_to}` : ipo.price ? `$${ipo.price}` : "-",
1631
- ipo.shares ? fmtNum5(ipo.shares) : "-"
2211
+ function formatIpo(data) {
2212
+ if (!Array.isArray(data) || data.length === 0) return "(no IPO data)";
2213
+ const rows = data.map((r) => [
2214
+ String(r.date ?? "-"),
2215
+ String(r.symbol ?? "-"),
2216
+ String(r.company ?? r.name ?? "-"),
2217
+ String(r.exchange ?? "-"),
2218
+ r.priceRange ? String(r.priceRange) : "-",
2219
+ r.shares ? fmtNum5(r.shares) : "-"
1632
2220
  ]);
1633
- return makeTable(["Date", "Company", "Symbol", "Exchange", "Price Range", "Shares"], rows);
2221
+ return makeTable(["Date", "Symbol", "Company", "Exchange", "Price Range", "Shares"], rows);
1634
2222
  }
1635
2223
  function fmtNum5(v) {
1636
2224
  if (v == null) return "-";
@@ -1651,7 +2239,7 @@ Examples:
1651
2239
  $ bloom compare TSLA RIVN LCID Compare EV manufacturers
1652
2240
  `).action(async (symbols, opts) => {
1653
2241
  const syms = symbols.map((s) => s.toUpperCase()).slice(0, 10);
1654
- const data = await callTool("get_symbols_metadata", { symbols: syms });
2242
+ const data = await BloomClient.instance().compare(syms);
1655
2243
  outputResult(data, opts, (d) => formatComparison(d, syms));
1656
2244
  });
1657
2245
  }
@@ -1662,12 +2250,10 @@ function formatComparison(data, symbols) {
1662
2250
  const metrics = [
1663
2251
  ["Price", "latest_price", "$"],
1664
2252
  ["Market Cap", "market_cap", "cap"],
1665
- ["P/E", "pe_ratio", ""],
1666
- ["EPS", "eps", "$"],
2253
+ ["P/E", "price_to_earnings", ""],
1667
2254
  ["Dividend Yield", "dividend_yield", "%"],
1668
2255
  ["52W High", "week_52_high", "$"],
1669
2256
  ["52W Low", "week_52_low", "$"],
1670
- ["Beta", "beta", ""],
1671
2257
  ["Sector", "sector", ""]
1672
2258
  ];
1673
2259
  const bySymbol = {};
@@ -1678,15 +2264,15 @@ function formatComparison(data, symbols) {
1678
2264
  bySymbol[sym] = meta;
1679
2265
  }
1680
2266
  const headers = ["Metric", ...symbols];
1681
- const rows = metrics.map(([label, key, fmt2]) => {
2267
+ const rows = metrics.map(([label, key, fmt3]) => {
1682
2268
  const vals = symbols.map((s) => {
1683
2269
  const meta = bySymbol[s];
1684
2270
  if (!meta) return "-";
1685
2271
  const v = meta[key];
1686
2272
  if (v == null) return "-";
1687
- if (fmt2 === "$") return `$${Number(v).toFixed(2)}`;
1688
- if (fmt2 === "%") return `${(Number(v) * 100).toFixed(2)}%`;
1689
- if (fmt2 === "cap") return fmtCap(v);
2273
+ if (fmt3 === "$") return `$${Number(v).toFixed(2)}`;
2274
+ if (fmt3 === "%") return `${(Number(v) * 100).toFixed(2)}%`;
2275
+ if (fmt3 === "cap") return fmtCap(v);
1690
2276
  return String(v);
1691
2277
  });
1692
2278
  return [label, ...vals];
@@ -1712,8 +2298,8 @@ Examples:
1712
2298
  $ bloom ratings NVDA --limit 5 Last 5 analyst actions
1713
2299
  `).action(async (symbol, opts) => {
1714
2300
  const sym = symbol.toUpperCase();
1715
- const limit = parseIntSafe(opts.limit, 20);
1716
- const result = await callTool("get_analyst_ratings", { symbol: sym, limit });
2301
+ const limit = parseIntArg(opts.limit, "--limit");
2302
+ const result = await BloomClient.instance().getRatings(sym, limit);
1717
2303
  outputResult(result, opts, () => {
1718
2304
  const obj = result;
1719
2305
  return formatRatings(obj.grades, obj.estimates);
@@ -1753,16 +2339,447 @@ function fmtNum6(v) {
1753
2339
  return `$${n.toLocaleString()}`;
1754
2340
  }
1755
2341
 
2342
+ // src/commands/analytics.ts
2343
+ import { writeFileSync as writeFileSync5, mkdirSync as mkdirSync5, readFileSync as readFileSync4 } from "fs";
2344
+ import { dirname as dirname2 } from "path";
2345
+ function parseHoldings(input) {
2346
+ let raw = input;
2347
+ try {
2348
+ raw = readFileSync4(input, "utf8");
2349
+ } catch {
2350
+ }
2351
+ try {
2352
+ const parsed = JSON.parse(raw);
2353
+ if (Array.isArray(parsed)) {
2354
+ return parsed.map((h) => ({
2355
+ symbol: String(h.symbol).toUpperCase(),
2356
+ value: Number(h.value),
2357
+ cost_basis: h.cost_basis !== void 0 ? Number(h.cost_basis) : void 0,
2358
+ shares: h.shares !== void 0 ? Number(h.shares) : void 0
2359
+ }));
2360
+ }
2361
+ return Object.entries(parsed).map(([symbol, value]) => ({
2362
+ symbol: symbol.toUpperCase(),
2363
+ value: Number(value)
2364
+ }));
2365
+ } catch {
2366
+ const parts = raw.split(",").map((s) => s.trim()).filter(Boolean);
2367
+ return parts.map((p) => {
2368
+ const [sym, val] = p.split("=");
2369
+ if (!sym || !val) {
2370
+ throw new Error(`Invalid holding: ${p}. Use 'AAPL=145000' format.`);
2371
+ }
2372
+ return { symbol: sym.toUpperCase().trim(), value: Number(val) };
2373
+ });
2374
+ }
2375
+ }
2376
+ var DIVIDER = "\u2500".repeat(60);
2377
+ function fmtMoney(n) {
2378
+ if (n >= 1e6) return `$${(n / 1e6).toFixed(2)}M`;
2379
+ if (n >= 1e3) return `$${(n / 1e3).toFixed(1)}K`;
2380
+ return `$${n.toFixed(0)}`;
2381
+ }
2382
+ function fmtPct(n, signed = false) {
2383
+ const v = (n * 100).toFixed(1);
2384
+ return signed && n >= 0 ? `+${v}%` : `${v}%`;
2385
+ }
2386
+ function bar(pct, width = 16) {
2387
+ const filled = Math.round(pct * width);
2388
+ return "\u2588".repeat(Math.max(0, filled)) + " ".repeat(Math.max(0, width - filled));
2389
+ }
2390
+ function renderText(data) {
2391
+ const lines = [];
2392
+ const s = data.summary;
2393
+ const headerParts = [fmtMoney(s.total_value)];
2394
+ if (s.ytd_return !== null && s.ytd_return !== void 0) {
2395
+ headerParts.push(`${fmtPct(s.ytd_return, true)} YTD`);
2396
+ }
2397
+ if (s.vs_spy !== null && s.vs_spy !== void 0) {
2398
+ headerParts.push(`${fmtPct(s.vs_spy, true)} SPY`);
2399
+ }
2400
+ lines.push("");
2401
+ lines.push(" " + headerParts.join(" \u2022 "));
2402
+ lines.push("");
2403
+ lines.push(" " + s.headline_insight);
2404
+ lines.push("");
2405
+ lines.push(" " + DIVIDER);
2406
+ lines.push("");
2407
+ lines.push(" CONCENTRATION");
2408
+ lines.push("");
2409
+ for (const sec of data.concentration.by_sector) {
2410
+ const name = sec.name.padEnd(14);
2411
+ lines.push(` ${name} ${bar(sec.pct)} ${fmtPct(sec.pct)}`);
2412
+ }
2413
+ lines.push("");
2414
+ lines.push(" " + data.concentration.insight);
2415
+ lines.push("");
2416
+ lines.push(" " + DIVIDER);
2417
+ lines.push("");
2418
+ lines.push(" HOW YOU TRADE");
2419
+ lines.push("");
2420
+ if (!data.behavior.available) {
2421
+ lines.push(" " + (data.behavior.reason || "Not enough trade history yet."));
2422
+ } else {
2423
+ if (data.behavior.insight) lines.push(" " + data.behavior.insight);
2424
+ lines.push("");
2425
+ for (const s2 of data.behavior.strengths) lines.push(` \u2713 ${s2.text}`);
2426
+ for (const w of data.behavior.weaknesses) lines.push(` \u26A0 ${w.text}`);
2427
+ }
2428
+ lines.push("");
2429
+ lines.push(" " + DIVIDER);
2430
+ lines.push("");
2431
+ lines.push(" RISK");
2432
+ lines.push("");
2433
+ const r = data.risk;
2434
+ if (r.volatility && r.volatility.value != null) {
2435
+ lines.push(
2436
+ ` Volatility ${r.volatility.label.padEnd(8)} ${fmtPct(r.volatility.value)}`
2437
+ );
2438
+ }
2439
+ if (r.correlation_spy != null) {
2440
+ const label = r.correlation_spy >= 0.8 ? "High" : r.correlation_spy >= 0.5 ? "Med" : "Low";
2441
+ lines.push(
2442
+ ` Correlation ${label.padEnd(8)} ${r.correlation_spy.toFixed(2)} to SPY`
2443
+ );
2444
+ }
2445
+ if (r.max_drawdown != null) {
2446
+ lines.push(` Max drawdown ${fmtPct(r.max_drawdown)}`);
2447
+ }
2448
+ if (r.sharpe != null) {
2449
+ lines.push(` Sharpe ${r.sharpe.toFixed(2)}`);
2450
+ }
2451
+ lines.push("");
2452
+ lines.push(" " + r.insight);
2453
+ lines.push("");
2454
+ lines.push(" " + DIVIDER);
2455
+ lines.push("");
2456
+ lines.push(" WHAT TO WATCH");
2457
+ lines.push("");
2458
+ if (data.watch.alerts.length === 0) {
2459
+ lines.push(" Nothing flagged.");
2460
+ } else {
2461
+ for (const w of data.watch.alerts) {
2462
+ lines.push(` ${w.ticker.padEnd(6)} ${w.reason}`);
2463
+ }
2464
+ }
2465
+ lines.push("");
2466
+ lines.push(" " + DIVIDER);
2467
+ lines.push("");
2468
+ lines.push(" PROJECTION");
2469
+ lines.push("");
2470
+ for (const p of data.projection.points) {
2471
+ if (p.year === 0) continue;
2472
+ lines.push(
2473
+ ` ${`${p.year}Y`.padEnd(4)} p10 ${fmtMoney(p.p10)} p50 ${fmtMoney(p.p50)} p90 ${fmtMoney(p.p90)}`
2474
+ );
2475
+ }
2476
+ lines.push("");
2477
+ lines.push(" " + data.projection.disclaimer);
2478
+ lines.push("");
2479
+ return lines.join("\n");
2480
+ }
2481
+ function renderMarkdown(data) {
2482
+ const lines = [];
2483
+ const s = data.summary;
2484
+ lines.push("# Portfolio Analytics");
2485
+ lines.push("");
2486
+ const hp = [`**${fmtMoney(s.total_value)}**`];
2487
+ if (s.ytd_return != null) hp.push(`${fmtPct(s.ytd_return, true)} YTD`);
2488
+ if (s.vs_spy != null) hp.push(`${fmtPct(s.vs_spy, true)} SPY`);
2489
+ lines.push(hp.join(" \u2022 "));
2490
+ lines.push("");
2491
+ lines.push(`> ${s.headline_insight}`);
2492
+ lines.push("");
2493
+ lines.push("## Concentration");
2494
+ lines.push("");
2495
+ lines.push("| Sector | Allocation | Value |");
2496
+ lines.push("|---|---|---|");
2497
+ for (const sec of data.concentration.by_sector) {
2498
+ lines.push(`| ${sec.name} | ${fmtPct(sec.pct)} | ${fmtMoney(sec.value)} |`);
2499
+ }
2500
+ lines.push("");
2501
+ lines.push(data.concentration.insight);
2502
+ lines.push("");
2503
+ lines.push("## How You Trade");
2504
+ lines.push("");
2505
+ if (!data.behavior.available) {
2506
+ lines.push(data.behavior.reason || "Not enough trade history yet.");
2507
+ } else {
2508
+ if (data.behavior.insight) {
2509
+ lines.push(data.behavior.insight);
2510
+ lines.push("");
2511
+ }
2512
+ for (const x of data.behavior.strengths) lines.push(`- \u2713 ${x.text}`);
2513
+ for (const x of data.behavior.weaknesses) lines.push(`- \u26A0 ${x.text}`);
2514
+ }
2515
+ lines.push("");
2516
+ lines.push("## Risk");
2517
+ lines.push("");
2518
+ const r = data.risk;
2519
+ if (r.volatility && r.volatility.value != null) lines.push(`- Volatility: ${r.volatility.label} (${fmtPct(r.volatility.value)})`);
2520
+ if (r.correlation_spy != null) lines.push(`- Correlation to SPY: ${r.correlation_spy.toFixed(2)}`);
2521
+ if (r.max_drawdown != null) lines.push(`- Max drawdown: ${fmtPct(r.max_drawdown)}`);
2522
+ if (r.sharpe != null) lines.push(`- Sharpe: ${r.sharpe.toFixed(2)}`);
2523
+ lines.push("");
2524
+ lines.push(r.insight);
2525
+ lines.push("");
2526
+ lines.push("## What to Watch");
2527
+ lines.push("");
2528
+ if (data.watch.alerts.length === 0) {
2529
+ lines.push("Nothing flagged.");
2530
+ } else {
2531
+ for (const w of data.watch.alerts) {
2532
+ lines.push(`- **${w.ticker}** \u2014 ${w.reason}`);
2533
+ }
2534
+ }
2535
+ lines.push("");
2536
+ lines.push("## Projection");
2537
+ lines.push("");
2538
+ lines.push("| Year | p10 | p50 | p90 |");
2539
+ lines.push("|---|---|---|---|");
2540
+ for (const p of data.projection.points) {
2541
+ lines.push(`| ${p.year}Y | ${fmtMoney(p.p10)} | ${fmtMoney(p.p50)} | ${fmtMoney(p.p90)} |`);
2542
+ }
2543
+ lines.push("");
2544
+ lines.push(`*${data.projection.disclaimer}*`);
2545
+ return lines.join("\n");
2546
+ }
2547
+ function emit2(content, opts) {
2548
+ if (opts.output) {
2549
+ mkdirSync5(dirname2(opts.output), { recursive: true });
2550
+ writeFileSync5(opts.output, content, "utf8");
2551
+ if (!opts.quiet) console.error(`Wrote ${opts.output}`);
2552
+ } else {
2553
+ console.log(content);
2554
+ }
2555
+ }
2556
+ function registerAnalyticsCommand(program2) {
2557
+ addGlobalOptions(
2558
+ program2.command("analytics").description(
2559
+ "One-page portfolio analytics: concentration, risk, watch, projection"
2560
+ ).argument(
2561
+ "<holdings>",
2562
+ "Holdings as JSON, file path, or shorthand (e.g. 'AAPL=145000,MSFT=91000')"
2563
+ ).option(
2564
+ "--section <s>",
2565
+ "Show only one section: concentration, behavior, risk, watch, projection"
2566
+ ).option("--md", "Output as markdown (alias for --format markdown)")
2567
+ ).action(
2568
+ async (holdingsInput, opts) => {
2569
+ let holdings;
2570
+ try {
2571
+ holdings = parseHoldings(holdingsInput);
2572
+ } catch (e) {
2573
+ console.error(`Error parsing holdings: ${e.message}`);
2574
+ process.exit(1);
2575
+ }
2576
+ const result = await callTool("analyze_portfolio", {
2577
+ holdings,
2578
+ parts: [
2579
+ "summary",
2580
+ "concentration",
2581
+ "asset_class",
2582
+ "geography",
2583
+ "behavior",
2584
+ "risk",
2585
+ "watch",
2586
+ "projection"
2587
+ ]
2588
+ });
2589
+ if (result && typeof result === "object" && "error" in result && result.error) {
2590
+ console.error(`Error: ${result.error}`);
2591
+ process.exit(1);
2592
+ }
2593
+ const data = result;
2594
+ if (opts.raw) {
2595
+ emit2(JSON.stringify(data, null, 2), opts);
2596
+ return;
2597
+ }
2598
+ let payload = data;
2599
+ if (opts.section) {
2600
+ const sec = opts.section.toLowerCase();
2601
+ const map = {
2602
+ summary: data.summary,
2603
+ concentration: data.concentration,
2604
+ behavior: data.behavior,
2605
+ risk: data.risk,
2606
+ watch: data.watch,
2607
+ projection: data.projection
2608
+ };
2609
+ if (!(sec in map)) {
2610
+ console.error(
2611
+ `Unknown section: ${sec}. Choose: summary, concentration, behavior, risk, watch, projection`
2612
+ );
2613
+ process.exit(1);
2614
+ }
2615
+ payload = map[sec];
2616
+ }
2617
+ const fmt3 = opts.md ? "markdown" : opts.format ?? resolveFormat(opts);
2618
+ if (fmt3 === "json") {
2619
+ emit2(JSON.stringify(payload, null, 2), opts);
2620
+ return;
2621
+ }
2622
+ if (fmt3 === "markdown") {
2623
+ if (opts.section) {
2624
+ emit2(JSON.stringify(payload, null, 2), opts);
2625
+ } else {
2626
+ emit2(renderMarkdown(data), opts);
2627
+ }
2628
+ return;
2629
+ }
2630
+ if (opts.section) {
2631
+ emit2(JSON.stringify(payload, null, 2), opts);
2632
+ } else {
2633
+ emit2(renderText(data), opts);
2634
+ }
2635
+ }
2636
+ );
2637
+ }
2638
+
2639
+ // src/commands/stats.ts
2640
+ function registerStatsCommand(program2) {
2641
+ addGlobalOptions(
2642
+ program2.command("stats").description("Key stats: beta, 52-week range, volume, P/E, dividend yield").argument("<symbol>", "Ticker symbol")
2643
+ ).addHelpText("after", `
2644
+ Examples:
2645
+ $ bloom stats AAPL Key statistics for Apple
2646
+ $ bloom stats TSLA -f json Stats as JSON
2647
+ `).action(async (symbol, opts) => {
2648
+ const data = await BloomClient.instance().getStats(symbol.toUpperCase());
2649
+ outputResult(data, opts);
2650
+ });
2651
+ }
2652
+
2653
+ // src/commands/peers.ts
2654
+ function registerPeersCommand(program2) {
2655
+ addGlobalOptions(
2656
+ program2.command("peers").description("Peer companies and competitors").argument("<symbol>", "Ticker symbol")
2657
+ ).addHelpText("after", `
2658
+ Examples:
2659
+ $ bloom peers AAPL Companies similar to Apple
2660
+ $ bloom peers TSLA Tesla's peer group
2661
+ `).action(async (symbol, opts) => {
2662
+ const data = await BloomClient.instance().getPeers(symbol.toUpperCase());
2663
+ outputResult(data, opts, formatPeers);
2664
+ });
2665
+ }
2666
+ function formatPeers(data, opts) {
2667
+ const peers = data?.results;
2668
+ if (!Array.isArray(peers)) return JSON.stringify(data, null, 2);
2669
+ const num = (v, f) => v == null || v === "" || isNaN(Number(v)) ? "-" : f(Number(v));
2670
+ const pct = (n) => `${(n * 100).toFixed(2)}%`;
2671
+ const cap = (n) => n >= 1e12 ? `$${(n / 1e12).toFixed(2)}T` : n >= 1e9 ? `$${(n / 1e9).toFixed(2)}B` : `$${(n / 1e6).toFixed(2)}M`;
2672
+ const rows = peers.map((p) => [
2673
+ String(p.symbol ?? ""),
2674
+ truncate(String(p.name ?? ""), 32),
2675
+ String(p.sector || p.category || ""),
2676
+ num(p.latestPrice, (n) => `$${n.toFixed(2)}`),
2677
+ num(p.changePercent1d, pct),
2678
+ num(p.changePercent1y, pct),
2679
+ num(p.priceToEarnings, (n) => n.toFixed(2)),
2680
+ num(p.marketCap, cap)
2681
+ ]);
2682
+ return makeTable(["Symbol", "Name", "Sector", "Price", "1D", "1Y", "P/E", "Mkt Cap"], rows, opts);
2683
+ }
2684
+
2685
+ // src/commands/bottom-line.ts
2686
+ function registerBottomLineCommand(program2) {
2687
+ addGlobalOptions(
2688
+ program2.command("bottom-line").description("Buy/sell/hold verdict with reasoning").argument("<symbol>", "Ticker symbol")
2689
+ ).addHelpText("after", `
2690
+ Examples:
2691
+ $ bloom bottom-line AAPL Bloom's bottom line on Apple
2692
+ $ bloom bottom-line NVDA Buy/sell/hold verdict for NVIDIA
2693
+ `).action(async (symbol, opts) => {
2694
+ const data = await BloomClient.instance().getBottomLine(symbol.toUpperCase());
2695
+ outputResult(data, opts, formatBottomLine);
2696
+ });
2697
+ }
2698
+ function formatBottomLine(data, opts) {
2699
+ const bl = data?.results;
2700
+ if (!bl?.verdict) return JSON.stringify(data, null, 2);
2701
+ const rows = bl.details.map((d) => [d.rating, d.title, d.descriptions.map((x) => `- ${x}`).join("\n")]);
2702
+ const table = makeTable(["Rating", "Area", "Reasoning"], rows, opts);
2703
+ return [`${bl.symbol}: ${bl.verdict}`, ...bl.lead ? [bl.lead] : [], "", table].join("\n");
2704
+ }
2705
+
2706
+ // src/commands/insights.ts
2707
+ function registerInsightsCommand(program2) {
2708
+ addGlobalOptions(
2709
+ program2.command("insights").description("AI-generated insights for stocks").argument("[symbols...]", "Ticker symbols (omit for all recent)")
2710
+ ).addHelpText("after", `
2711
+ Examples:
2712
+ $ bloom insights AAPL Insights for Apple
2713
+ $ bloom insights AAPL MSFT Insights for multiple stocks
2714
+ $ bloom insights All recent insights
2715
+ `).action(async (symbols, opts) => {
2716
+ if (symbols.length === 1) {
2717
+ const data = await BloomClient.instance().getInsights(symbols[0].toUpperCase());
2718
+ outputResult(data, opts);
2719
+ } else {
2720
+ const syms = symbols.length > 0 ? symbols.map((s) => s.toUpperCase()) : void 0;
2721
+ const data = await BloomClient.instance().getInsights(void 0, syms);
2722
+ outputResult(data, opts);
2723
+ }
2724
+ });
2725
+ }
2726
+
2727
+ // src/commands/arena-activity.ts
2728
+ function registerArenaActivityCommand(program2) {
2729
+ addGlobalOptions(
2730
+ program2.command("arena-activity").description("Live AI arena trade activity feed").option("--model <m>", "Filter by model: claude, openai, gemini").option("--limit <n>", "Max results", "20")
2731
+ ).addHelpText("after", `
2732
+ Examples:
2733
+ $ bloom arena-activity All recent arena trades
2734
+ $ bloom arena-activity --model claude Claude's trades only
2735
+ $ bloom arena-activity --limit 5 Last 5 trades
2736
+ `).action(async (opts) => {
2737
+ const limit = parseIntArg(opts.limit, "--limit");
2738
+ const data = await BloomClient.instance().getArenaActivity(opts.model, limit);
2739
+ outputResult(data, opts);
2740
+ });
2741
+ }
2742
+
2743
+ // src/commands/portfolio-news.ts
2744
+ function registerPortfolioNewsCommand(program2) {
2745
+ addGlobalOptions(
2746
+ program2.command("portfolio-news").description("Smart news summary for portfolio symbols").argument("[symbols...]", "Ticker symbols")
2747
+ ).addHelpText("after", `
2748
+ Examples:
2749
+ $ bloom portfolio-news AAPL MSFT GOOG News digest for holdings
2750
+ $ bloom portfolio-news News for all watched symbols
2751
+ `).action(async (symbols, opts) => {
2752
+ const syms = symbols.length > 0 ? symbols.map((s) => s.toUpperCase()) : void 0;
2753
+ const data = await BloomClient.instance().getPortfolioNews(syms);
2754
+ outputResult(data, opts);
2755
+ });
2756
+ }
2757
+
2758
+ // src/commands/collection-returns.ts
2759
+ function registerCollectionReturnsCommand(program2) {
2760
+ addGlobalOptions(
2761
+ program2.command("collection-returns").description("Performance returns for the given collections").requiredOption("--ids <ids>", "Comma-separated collection IDs (from `bloom collections`)").option("--timerange <range>", "1d|1w|1m|3m|ytd|1y|5y", "ytd")
2762
+ ).addHelpText("after", `
2763
+ Examples:
2764
+ $ bloom collection-returns --ids 113 YTD return for collection 113
2765
+ $ bloom collection-returns --ids 113,114 --timerange 1y
2766
+ $ bloom collection-returns --ids 113 -f table As table
2767
+ `).action(async (opts) => {
2768
+ const data = await BloomClient.instance().getCollectionReturns(opts.ids, opts.timerange);
2769
+ outputResult(data, opts);
2770
+ });
2771
+ }
2772
+
1756
2773
  // src/index.ts
1757
- var program = new Command();
2774
+ var program = new Command3();
1758
2775
  var __dirname = path.dirname(fileURLToPath(import.meta.url));
1759
2776
  var pkgPath = path.join(__dirname, "..", "package.json");
1760
- var compiledVersion = "0.1.6".length > 0 ? "0.1.6" : void 0;
2777
+ var compiledVersion = "0.1.8".length > 0 ? "0.1.8" : void 0;
1761
2778
  var envVersion = process.env.BLOOM_CLI_VERSION ?? process.env.npm_package_version;
1762
2779
  var fallbackVersion = compiledVersion ?? "unknown";
1763
2780
  var cliVersion = envVersion ?? fallbackVersion;
1764
2781
  try {
1765
- const pkg = JSON.parse(readFileSync2(pkgPath, "utf8"));
2782
+ const pkg = JSON.parse(readFileSync5(pkgPath, "utf8"));
1766
2783
  if (typeof pkg.version === "string") {
1767
2784
  cliVersion = pkg.version;
1768
2785
  }
@@ -1771,7 +2788,24 @@ try {
1771
2788
  if (cliVersion === "0.0.0") {
1772
2789
  cliVersion = fallbackVersion;
1773
2790
  }
1774
- program.name("bloom").description("Bloom CLI \u2014 financial data for coding agents and humans").version(cliVersion);
2791
+ var config = loadConfig();
2792
+ if (config.apiBase !== "https://api.getbloom.app") {
2793
+ setApiBase(config.apiBase);
2794
+ }
2795
+ setCacheDir(config.cacheDir);
2796
+ program.hook("preAction", (_thisCommand, actionCommand) => {
2797
+ for (const [key, value] of Object.entries(program.opts())) {
2798
+ if (program.getOptionValueSource(key) === "cli" && actionCommand.getOptionValueSource(key) !== "cli") {
2799
+ actionCommand.setOptionValueWithSource(key, value, "cli");
2800
+ }
2801
+ }
2802
+ const opts = actionCommand.opts();
2803
+ if (opts.debug) setDebug(true);
2804
+ if (opts.cache === false) setNoCache(true);
2805
+ });
2806
+ addGlobalOptions(
2807
+ program.name("bloom").description("Bloom CLI \u2014 financial data for coding agents and humans").version(cliVersion).enablePositionalOptions()
2808
+ );
1775
2809
  registerAuthCommand(program);
1776
2810
  registerInfoCommand(program);
1777
2811
  registerNewsCommand(program);
@@ -1798,6 +2832,7 @@ registerCorrelationCommand(program);
1798
2832
  registerRiskCommand(program);
1799
2833
  registerDrawdownCommand(program);
1800
2834
  registerMacroCommand(program);
2835
+ registerBriefingCommand(program);
1801
2836
  registerSectorsCommand(program);
1802
2837
  registerDcfCommand(program);
1803
2838
  registerHoldersCommand(program);
@@ -1808,7 +2843,50 @@ registerSplitsCommand(program);
1808
2843
  registerIpoCommand(program);
1809
2844
  registerCompareCommand(program);
1810
2845
  registerRatingsCommand(program);
2846
+ registerAnalyticsCommand(program);
2847
+ registerStatsCommand(program);
2848
+ registerPeersCommand(program);
2849
+ registerBottomLineCommand(program);
2850
+ registerInsightsCommand(program);
2851
+ registerArenaActivityCommand(program);
2852
+ registerPortfolioNewsCommand(program);
2853
+ registerCollectionReturnsCommand(program);
2854
+ var cacheCmd = program.command("cache").description("Manage disk cache");
2855
+ cacheCmd.command("clear").description("Clear all cached data").action(() => {
2856
+ const { cleared } = clearCache();
2857
+ console.log(`Cleared ${cleared} cached items.`);
2858
+ });
2859
+ cacheCmd.command("stats").description("Show cache statistics").action(() => {
2860
+ const stats = cacheStats();
2861
+ console.log(`Cache directory: ${stats.cacheDir}`);
2862
+ console.log(`Items: ${stats.items} (${stats.expired} expired)`);
2863
+ console.log(`Total size: ${(stats.totalBytes / 1024).toFixed(1)} KB`);
2864
+ if (Object.keys(stats.byCategory).length > 0) {
2865
+ console.log("By category:");
2866
+ for (const [cat, count] of Object.entries(stats.byCategory)) {
2867
+ console.log(` ${cat}: ${count}`);
2868
+ }
2869
+ }
2870
+ });
1811
2871
  program.parseAsync().catch((err) => {
1812
- console.error("Error:", err.message || err);
2872
+ if (err instanceof AuthError) {
2873
+ console.error(`Error: ${err.message}`);
2874
+ console.error("Run `bloom auth login` to authenticate.");
2875
+ process.exit(1);
2876
+ }
2877
+ if (err instanceof RateLimitError) {
2878
+ console.error("Rate limited. Try again in a moment.");
2879
+ process.exit(2);
2880
+ }
2881
+ if (err instanceof TickerNotFoundError) {
2882
+ console.error(`Ticker not found: ${err.ticker}`);
2883
+ process.exit(1);
2884
+ }
2885
+ if (err instanceof BloomError) {
2886
+ console.error(`Error: ${err.message}`);
2887
+ process.exit(1);
2888
+ }
2889
+ const msg = err instanceof Error ? err.message : String(err);
2890
+ console.error("Error:", msg);
1813
2891
  process.exit(1);
1814
2892
  });