routstrd 0.3.1 → 0.3.3

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.
@@ -1,17 +1,8 @@
1
1
  import { CLIENT_COLORS, COLORS, MODEL_COLORS } from "./constants.ts";
2
2
  import type { Tab } from "./types.ts";
3
3
  import {
4
- formatDate,
5
4
  formatNumber,
6
5
  formatTime,
7
- getClientStats,
8
- getDayStats,
9
- getHourlyToday,
10
- getModelStats,
11
- getNpubStats,
12
- getProviderStats,
13
- getTodayStart,
14
- getTotals,
15
6
  type ClientInfo,
16
7
  } from "./data.ts";
17
8
  import { vimState } from "./state.ts";
@@ -120,8 +111,7 @@ export function renderBarChart(
120
111
 
121
112
 
122
113
  export function renderOverview(stats: UsageStats, balance: BalanceInfo | null, status: StatusInfo | null, width: number): string {
123
- // Use the server-calculated totals (all entries) instead of summing limited entries
124
- const totals = getTotals(stats.entries);
114
+ const totals = stats.summary.totals;
125
115
  const totalRequests = stats.totalEntries; // Use server's total count, not entries.length
126
116
  const totalVisibleCost = stats.totalSatsCost; // <-- Use server's total, not client-side sum of limited entries
127
117
  const avgCost = totalRequests > 0 ? totalVisibleCost / totalRequests : 0;
@@ -240,7 +230,7 @@ export function renderOverview(stats: UsageStats, balance: BalanceInfo | null, s
240
230
  output = renderBox(statusLines, width, "System Status") + "\n" + output;
241
231
  }
242
232
 
243
- const modelStats = getModelStats(stats.entries);
233
+ const modelStats = stats.summary.models;
244
234
  if (modelStats.length > 0) {
245
235
  const maxCost = modelStats[0]!.satsCost;
246
236
  const totalCost = Math.max(totalVisibleCost, 1);
@@ -259,7 +249,7 @@ export function renderOverview(stats: UsageStats, balance: BalanceInfo | null, s
259
249
  output += "\n" + renderBox(modelLines, width, "Top Models by Cost");
260
250
  }
261
251
 
262
- const clientStats = getClientStats(stats.entries);
252
+ const clientStats = stats.summary.clients;
263
253
  if (clientStats.length > 0) {
264
254
  const maxCost = clientStats[0]!.satsCost;
265
255
  const totalCost = Math.max(totalVisibleCost, 1);
@@ -282,19 +272,28 @@ export function renderOverview(stats: UsageStats, balance: BalanceInfo | null, s
282
272
  }
283
273
 
284
274
  export function renderToday(stats: UsageStats, width: number): string {
285
- const hourly = getHourlyToday(stats.entries);
286
- const todayStart = getTodayStart();
287
275
  const currentHour = new Date().getHours();
288
- const todayStats = { date: formatDate(Date.now()), requests: 0, satsCost: 0, promptTokens: 0, completionTokens: 0, totalTokens: 0 };
289
-
290
- for (const entry of stats.entries) {
291
- if (entry.timestamp >= todayStart) {
292
- todayStats.requests++;
293
- todayStats.satsCost += entry.satsCost;
294
- todayStats.promptTokens += entry.promptTokens;
295
- todayStats.completionTokens += entry.completionTokens;
296
- todayStats.totalTokens += entry.totalTokens;
297
- }
276
+ // Build today's date string from LOCAL date components so it matches the
277
+ // server's tz-bucketed day keys (which use the client's tzOffsetMinutes).
278
+ const _now = new Date();
279
+ const todayDateStr = `${_now.getFullYear()}-${String(_now.getMonth() + 1).padStart(2, "0")}-${String(_now.getDate()).padStart(2, "0")}`;
280
+
281
+ let todayStats: { date: string; requests: number; satsCost: number; promptTokens: number; completionTokens: number; totalTokens: number };
282
+ let recentDays: Array<{ date: string; requests: number; satsCost: number; totalTokens: number; promptTokens: number; completionTokens: number }>;
283
+ let hourlyMap: Map<number, { requests: number; satsCost: number }>;
284
+
285
+ if (stats.summary) {
286
+ // Use server-aggregated data
287
+ const { days, hoursToday } = stats.summary;
288
+ // days[0] is most-recent-first; check if it's today
289
+ const todayDayStat = days[0]?.date === todayDateStr ? days[0] : undefined;
290
+ todayStats = todayDayStat
291
+ ? { date: todayDayStat.date, requests: todayDayStat.requests, satsCost: todayDayStat.satsCost, promptTokens: todayDayStat.promptTokens, completionTokens: todayDayStat.completionTokens, totalTokens: todayDayStat.totalTokens }
292
+ : { date: todayDateStr, requests: 0, satsCost: 0, promptTokens: 0, completionTokens: 0, totalTokens: 0 };
293
+ // Exclude today by date (it has its own box) rather than by position —
294
+ // days[0] is only today when there was activity today.
295
+ recentDays = days.filter((d) => d.date !== todayDateStr).slice(0, 6);
296
+ hourlyMap = new Map(hoursToday.map((h) => [h.hour, { requests: h.requests, satsCost: h.satsCost }]));
298
297
  }
299
298
 
300
299
  const summaryLines = [
@@ -306,18 +305,17 @@ export function renderToday(stats: UsageStats, width: number): string {
306
305
 
307
306
  let output = renderBox(summaryLines, width, "Today");
308
307
 
309
- const days = Array.from(getDayStats(stats.entries).values()).slice(0, 7);
310
- if (days.length > 1) {
311
- const dayLines = days.slice(1).map((d) => `${d.date}: ${formatReqs(d.requests)} req, ${formatCost(d.satsCost)} sats, ${formatNumber(d.totalTokens)} tokens`);
308
+ if (recentDays.length > 0) {
309
+ const dayLines = recentDays.map((d) => `${d.date}: ${formatReqs(d.requests)} req, ${formatCost(d.satsCost)} sats, ${formatNumber(d.totalTokens)} tokens`);
312
310
  output += "\n" + renderBox(dayLines, width, "Recent Days");
313
311
  }
314
312
 
315
313
  const hourLines: string[] = [];
316
- const maxHourCost = Math.max(...Array.from(hourly.values()).map((h) => h.satsCost), 1);
314
+ const maxHourCost = Math.max(...Array.from(hourlyMap.values()).map((h) => h.satsCost), 1);
317
315
  const totalTodayCost = Math.max(todayStats.satsCost, 1);
318
316
  const hourLabels: string[] = [];
319
317
  for (let h = currentHour; h >= 0; h--) {
320
- const hStat = hourly.get(h);
318
+ const hStat = hourlyMap.get(h);
321
319
  const reqs = hStat?.requests || 0;
322
320
  const cost = hStat?.satsCost || 0;
323
321
  hourLabels.push(`${h.toString().padStart(2, "0")}:00 (${formatReqs(reqs)} req, ${formatCost(cost)} sats) `);
@@ -325,7 +323,7 @@ export function renderToday(stats: UsageStats, width: number): string {
325
323
  const maxHourLabel = Math.max(...hourLabels.map((l) => l.length));
326
324
  startBarSection("hourly", maxHourLabel);
327
325
  for (let i = currentHour; i >= 0; i--) {
328
- const hStat = hourly.get(i);
326
+ const hStat = hourlyMap.get(i);
329
327
  const reqs = hStat?.requests || 0;
330
328
  const cost = hStat?.satsCost || 0;
331
329
  hourLines.push(renderBarChart(
@@ -346,7 +344,7 @@ export function renderToday(stats: UsageStats, width: number): string {
346
344
  }
347
345
 
348
346
  export function renderModels(stats: UsageStats, width: number): string {
349
- const modelStats = getModelStats(stats.entries);
347
+ const modelStats = stats.summary.models;
350
348
  if (modelStats.length === 0) return renderBox(["No model data available"], width, "Models");
351
349
 
352
350
  // Use totalSatsCost (all-time) for percentage calculations to match header
@@ -373,7 +371,7 @@ export function renderModels(stats: UsageStats, width: number): string {
373
371
  }
374
372
 
375
373
  export function renderProviders(stats: UsageStats, width: number): string {
376
- const providerStats = getProviderStats(stats.entries);
374
+ const providerStats = stats.summary.providers;
377
375
  if (providerStats.length === 0) return renderBox(["No provider data available"], width, "Providers");
378
376
 
379
377
  const lines: string[] = [];
@@ -389,8 +387,8 @@ export function renderProviders(stats: UsageStats, width: number): string {
389
387
  }
390
388
 
391
389
  export function renderTokens(stats: UsageStats, width: number): string {
392
- const totals = getTotals(stats.entries);
393
- const modelStats = getModelStats(stats.entries);
390
+ const totals = stats.summary.totals;
391
+ const modelStats = stats.summary.models;
394
392
  const summaryLines = [
395
393
  `${COLORS.bold}Total Prompt Tokens:${COLORS.reset} ${formatNumber(totals.promptTokens)}`,
396
394
  `${COLORS.bold}Total Completion Tokens:${COLORS.reset} ${formatNumber(totals.completionTokens)}`,
@@ -410,23 +408,7 @@ export function renderTokens(stats: UsageStats, width: number): string {
410
408
  output += "\n" + renderBox(tokenLines, width, "Tokens by Model");
411
409
  }
412
410
 
413
- const sizeBuckets = {
414
- tiny: { min: 0, max: 1000, count: 0, cost: 0 },
415
- small: { min: 1000, max: 10000, count: 0, cost: 0 },
416
- medium: { min: 10000, max: 50000, count: 0, cost: 0 },
417
- large: { min: 50000, max: 100000, count: 0, cost: 0 },
418
- huge: { min: 100000, max: Infinity, count: 0, cost: 0 },
419
- };
420
-
421
- for (const entry of stats.entries) {
422
- for (const bucket of Object.values(sizeBuckets)) {
423
- if (entry.totalTokens >= bucket.min && entry.totalTokens < bucket.max) {
424
- bucket.count++;
425
- bucket.cost += entry.satsCost;
426
- break;
427
- }
428
- }
429
- }
411
+ const sizeBuckets = stats.summary.sizeBuckets;
430
412
 
431
413
  const sizeLines = Object.entries(sizeBuckets).map(([name, bucket]) => `${name.padEnd(6)}: ${formatReqs(bucket.count).padStart(5)} reqs, ${formatCost(bucket.cost)} sats`);
432
414
  output += "\n" + renderBox(sizeLines, width, "Request Size Distribution");
@@ -434,7 +416,7 @@ export function renderTokens(stats: UsageStats, width: number): string {
434
416
  }
435
417
 
436
418
  export function renderClients(stats: UsageStats, width: number): string {
437
- const clientStats = getClientStats(stats.entries);
419
+ const clientStats = stats.summary.clients;
438
420
  if (clientStats.length === 0) return renderBox(["No client data available (API key auth not used)"], width, "Client Breakdown");
439
421
 
440
422
  // Use totalSatsCost (all-time) for percentage calculations to match header
@@ -478,31 +460,19 @@ export function renderClients(stats: UsageStats, width: number): string {
478
460
  endBarSection("client-detail");
479
461
 
480
462
  let output = renderBox(lines, width, "Client Breakdown");
481
- const clientModelMap = new Map<string, Map<string, { requests: number; satsCost: number; tokens: number }>>();
482
-
483
- for (const entry of stats.entries) {
484
- const client = entry.client || "unknown";
485
- const model = entry.modelId;
486
- if (!clientModelMap.has(client)) clientModelMap.set(client, new Map());
487
- const modelMap = clientModelMap.get(client)!;
488
- const existing = modelMap.get(model) || { requests: 0, satsCost: 0, tokens: 0 };
489
- modelMap.set(model, {
490
- requests: existing.requests + 1,
491
- satsCost: existing.satsCost + entry.satsCost,
492
- tokens: existing.tokens + entry.totalTokens,
493
- });
494
- }
495
-
496
463
  const clientModelLines: string[] = [];
497
- for (const topClient of clientStats.slice(0, 3)) {
498
- const modelMap = clientModelMap.get(topClient.client);
499
- if (!modelMap) continue;
500
- const models = Array.from(modelMap.entries()).sort((a, b) => b[1].satsCost - a[1].satsCost).slice(0, 5);
501
- clientModelLines.push(`${COLORS.bold}${topClient.client}${COLORS.reset} (${formatReqs(topClient.requests)} reqs, ${formatCost(topClient.satsCost)} sats)`);
502
- for (const [model, data] of models) {
503
- clientModelLines.push(` ${(MODEL_COLORS[model] || MODEL_COLORS.default)}${model.padEnd(18)}${COLORS.reset} ${formatNumber(data.tokens).padEnd(8)} tokens ${formatCost(data.satsCost)} sats`);
464
+
465
+ if (stats.summary) {
466
+ // Use pre-aggregated topModels from summary; exclude the "unknown" bucket
467
+ // (null client rows have no meaningful model attribution to display here).
468
+ for (const topClient of stats.summary.clients.filter((c) => c.client !== "unknown").slice(0, 3)) {
469
+ if (topClient.topModels.length === 0) continue;
470
+ clientModelLines.push(`${COLORS.bold}${topClient.client}${COLORS.reset} (${formatReqs(topClient.requests)} reqs, ${formatCost(topClient.satsCost)} sats)`);
471
+ for (const m of topClient.topModels) {
472
+ clientModelLines.push(` ${(MODEL_COLORS[m.modelId] || MODEL_COLORS.default)}${m.modelId.padEnd(18)}${COLORS.reset} ${formatNumber(m.totalTokens).padEnd(8)} tokens ${formatCost(m.satsCost)} sats`);
473
+ }
474
+ clientModelLines.push("");
504
475
  }
505
- clientModelLines.push("");
506
476
  }
507
477
 
508
478
  if (clientModelLines.length > 0) {
@@ -512,7 +482,7 @@ export function renderClients(stats: UsageStats, width: number): string {
512
482
  }
513
483
 
514
484
  export function renderNpubs(stats: UsageStats, clients: ClientInfo[], width: number): string {
515
- const npubStats = getNpubStats(stats.entries, clients);
485
+ const npubStats = stats.summary.npubs;
516
486
  if (npubStats.length === 0) return renderBox(["No npub data available"], width, "Npub Breakdown");
517
487
 
518
488
  const totalCost = stats.totalSatsCost;
@@ -557,38 +527,18 @@ export function renderNpubs(stats: UsageStats, clients: ClientInfo[], width: num
557
527
  endBarSection("npub-detail");
558
528
 
559
529
  let output = renderBox(lines, width, "Npub Breakdown");
560
-
561
- // Top models per npub (same pattern as clients tab)
562
- const npubModelMap = new Map<string, Map<string, { requests: number; satsCost: number; tokens: number }>>();
563
- const clientNpubMap = new Map<string, string>();
564
- for (const c of clients) {
565
- if (c.ownerNpub) clientNpubMap.set(c.clientId, c.ownerNpub);
566
- }
567
-
568
- for (const entry of stats.entries) {
569
- const npub = clientNpubMap.get(entry.client || "");
570
- if (!npub) continue;
571
- const model = entry.modelId;
572
- if (!npubModelMap.has(npub)) npubModelMap.set(npub, new Map());
573
- const modelMap = npubModelMap.get(npub)!;
574
- const existing = modelMap.get(model) || { requests: 0, satsCost: 0, tokens: 0 };
575
- modelMap.set(model, {
576
- requests: existing.requests + 1,
577
- satsCost: existing.satsCost + entry.satsCost,
578
- tokens: existing.tokens + entry.totalTokens,
579
- });
580
- }
581
-
582
530
  const npubModelLines: string[] = [];
583
- for (const topNpub of npubStats.slice(0, 5)) {
584
- const modelMap = npubModelMap.get(topNpub.npub);
585
- if (!modelMap) continue;
586
- const models = Array.from(modelMap.entries()).sort((a, b) => b[1].satsCost - a[1].satsCost).slice(0, 5);
587
- npubModelLines.push(`${COLORS.bold}${truncateNpub(topNpub.npub)}${COLORS.reset} (${formatReqs(topNpub.requests)} reqs, ${formatCost(topNpub.satsCost)} sats)`);
588
- for (const [model, data] of models) {
589
- npubModelLines.push(` ${(MODEL_COLORS[model] || MODEL_COLORS.default)}${model.padEnd(18)}${COLORS.reset} ${formatNumber(data.tokens).padEnd(8)} tokens ${formatCost(data.satsCost)} sats`);
531
+
532
+ if (stats.summary) {
533
+ // Use pre-aggregated topModels from summary
534
+ for (const topNpub of stats.summary.npubs.slice(0, 5)) {
535
+ if (topNpub.topModels.length === 0) continue;
536
+ npubModelLines.push(`${COLORS.bold}${truncateNpub(topNpub.npub)}${COLORS.reset} (${formatReqs(topNpub.requests)} reqs, ${formatCost(topNpub.satsCost)} sats)`);
537
+ for (const m of topNpub.topModels) {
538
+ npubModelLines.push(` ${(MODEL_COLORS[m.modelId] || MODEL_COLORS.default)}${m.modelId.padEnd(18)}${COLORS.reset} ${formatNumber(m.totalTokens).padEnd(8)} tokens ${formatCost(m.satsCost)} sats`);
539
+ }
540
+ npubModelLines.push("");
590
541
  }
591
- npubModelLines.push("");
592
542
  }
593
543
 
594
544
  if (npubModelLines.length > 0) {
@@ -609,20 +559,35 @@ export function renderRecent(stats: UsageStats, width: number): string {
609
559
  if (recentEntries.length === 0) return renderBox(["No recent entries"], width, "Recent Requests");
610
560
 
611
561
  const clientCol = 14;
562
+ const tokensCol = 18;
563
+ const costCol = 18;
564
+ const providerCol = Math.max(16, width - 4 - 10 - 18 - tokensCol - costCol - clientCol - 5);
565
+ const msatsToSats = (msats?: number) => typeof msats === "number" ? msats / 1000 : 0;
612
566
  const lines: string[] = [];
613
- lines.push(`${COLORS.bold}${"TIME".padEnd(10)} ${"MODEL".padEnd(18)} ${"TOKENS".padEnd(10)} ${"COST".padEnd(12)} ${"PROVIDER".padEnd(16)} ${"CLIENT".slice(0, clientCol)}${COLORS.reset}`);
567
+ lines.push(`${COLORS.bold}${"TIME".padEnd(10)} ${"MODEL".padEnd(18)} ${"I/CR/CW/O".padEnd(tokensCol)} ${"I/O/T in sats".padEnd(costCol)} ${"BASE:PROVIDER".padEnd(providerCol)} ${"CLIENT".slice(0, clientCol)}${COLORS.reset}`);
614
568
  lines.push(COLORS.dim + "─".repeat(width - 4) + COLORS.reset);
615
569
 
616
570
  for (const entry of recentEntries) {
617
571
  const time = formatTime(entry.timestamp).slice(0, 8);
618
572
  const model = entry.modelId.slice(0, 18).padEnd(18);
619
- const tokens = `${formatNumber(entry.totalTokens).padEnd(6)} (${formatNumber(entry.promptTokens)}+${formatNumber(entry.completionTokens)})`;
620
- const cost = `${formatCost(entry.satsCost).padEnd(8)} sats`;
621
- const provider = (entry.baseUrl || "unknown").replace("https://", "").replace("http://", "").slice(0, 16).padEnd(16);
573
+ const tokens = [
574
+ entry.promptTokens,
575
+ entry.cacheReadInputTokens || 0,
576
+ entry.cacheCreationInputTokens || 0,
577
+ entry.completionTokens,
578
+ ].map(formatNumber).join("/");
579
+ const totalSats = typeof entry.totalMsats === "number" ? entry.totalMsats / 1000 : entry.satsCost;
580
+ const cost = [
581
+ formatCost(msatsToSats(entry.inputMsats)),
582
+ formatCost(msatsToSats(entry.outputMsats)),
583
+ formatCost(totalSats),
584
+ ].join("/");
585
+ const baseUrl = (entry.baseUrl || "unknown").replace("https://", "").replace("http://", "");
586
+ const provider = `${baseUrl}:${entry.provider || "unknown"}`.slice(0, providerCol).padEnd(providerCol);
622
587
  const clientName = (entry.client || "unknown").slice(0, clientCol - 1);
623
588
  const clientColor = CLIENT_COLORS[entry.client || "unknown"] || CLIENT_COLORS.default || COLORS.white;
624
589
  const modelColor = MODEL_COLORS[entry.modelId] || MODEL_COLORS.default;
625
- lines.push(`${COLORS.dim}${time}${COLORS.reset} ${modelColor}${model}${COLORS.reset} ${tokens.padEnd(10)} ${COLORS.green}${cost}${COLORS.reset} ${COLORS.dim}${provider}${COLORS.reset} ${clientColor}${clientName}${COLORS.reset}`);
590
+ lines.push(`${COLORS.dim}${time}${COLORS.reset} ${modelColor}${model}${COLORS.reset} ${tokens.padEnd(tokensCol)} ${COLORS.green}${cost.padEnd(costCol)}${COLORS.reset} ${COLORS.dim}${provider}${COLORS.reset} ${clientColor}${clientName}${COLORS.reset}`);
626
591
  }
627
592
 
628
593
  return renderBox(lines, width, `Recent Requests (${stats.entries.length} shown)`);
@@ -1,4 +1,7 @@
1
1
  import type { UsageTrackingEntry } from "../../daemon/types.ts";
2
+ import type { UsageSummary } from "../../daemon/http/usage-summary.ts";
3
+
4
+ export type { UsageSummary };
2
5
 
3
6
  export interface UsageStats {
4
7
  entries: UsageTrackingEntry[];
@@ -6,42 +9,7 @@ export interface UsageStats {
6
9
  totalSatsCost: number;
7
10
  recentSatsCost: number;
8
11
  limit: number;
9
- }
10
-
11
- export interface DayStats {
12
- date: string;
13
- requests: number;
14
- satsCost: number;
15
- promptTokens: number;
16
- completionTokens: number;
17
- totalTokens: number;
18
- }
19
-
20
- export interface ModelStats {
21
- modelId: string;
22
- requests: number;
23
- satsCost: number;
24
- promptTokens: number;
25
- completionTokens: number;
26
- totalTokens: number;
27
- }
28
-
29
- export interface ProviderStats {
30
- baseUrl: string;
31
- requests: number;
32
- satsCost: number;
33
- promptTokens: number;
34
- completionTokens: number;
35
- totalTokens: number;
36
- }
37
-
38
- export interface ClientStats {
39
- client: string;
40
- requests: number;
41
- satsCost: number;
42
- promptTokens: number;
43
- completionTokens: number;
44
- totalTokens: number;
12
+ summary: UsageSummary;
45
13
  }
46
14
 
47
15
  export type TabId = "overview" | "today" | "models" | "providers" | "tokens" | "clients" | "npubs" | "recent";
@@ -52,15 +20,6 @@ export interface Tab {
52
20
  key: string;
53
21
  }
54
22
 
55
- export interface NpubStats {
56
- npub: string;
57
- requests: number;
58
- satsCost: number;
59
- promptTokens: number;
60
- completionTokens: number;
61
- totalTokens: number;
62
- }
63
-
64
23
  export interface VimState {
65
24
  scrollPos: number;
66
25
  searchQuery: string;
@@ -1,5 +1,4 @@
1
1
  import {
2
- callAuth,
3
2
  callDaemon,
4
3
  loadConfig,
5
4
  getDaemonBaseUrl,
@@ -57,7 +56,7 @@ export function getClientsFromStore(store: { getState(): any }): ClientEntry[] {
57
56
  * Use this when running remotely (CLI in remote mode).
58
57
  */
59
58
  export async function getClientsList(): Promise<ClientEntry[]> {
60
- const result = await callAuth("/clients");
59
+ const result = await callDaemon("/clients");
61
60
  const clients = (
62
61
  result.output as
63
62
  | {
@@ -108,7 +107,7 @@ export async function addDaemonClient(
108
107
  return { client, created: false };
109
108
  }
110
109
 
111
- const result = await callAuth("/clients/add", {
110
+ const result = await callDaemon("/clients/add", {
112
111
  method: "POST",
113
112
  body: { name, id: derivedId },
114
113
  });
@@ -160,7 +159,7 @@ export async function listClientsAction(): Promise<void> {
160
159
  export async function deleteClientAction(id: string): Promise<void> {
161
160
  await ensureDaemonRunning();
162
161
 
163
- const result = await callAuth("/clients/delete", {
162
+ const result = await callDaemon("/clients/delete", {
164
163
  method: "POST",
165
164
  body: { id },
166
165
  });
@@ -6,6 +6,7 @@ export const PID_FILE = process.env.ROUTSTRD_PID || `${CONFIG_DIR}/routstrd.pid`
6
6
  export const DB_PATH = `${CONFIG_DIR}/routstr.db`;
7
7
  export const CONFIG_FILE = `${CONFIG_DIR}/config.json`;
8
8
  export const LOGS_DIR = `${CONFIG_DIR}/logs`;
9
+ export const REQUEST_RESPONSE_LOGS_DIR = `${CONFIG_DIR}/request-response-logs`;
9
10
 
10
11
  /** NWC auto-refill configuration */
11
12
  export interface NwcAutoRefillConfig {
@@ -34,6 +35,13 @@ export interface RoutstrdConfig {
34
35
  provider: string | null;
35
36
  cocodPath: string | null;
36
37
  mode?: "xcashu" | "apikeys";
38
+ /** Raw upstream request/response logging. Disabled by default because logs can contain sensitive prompts, outputs, and auth/payment headers. */
39
+ requestResponseLogging?: {
40
+ /** Enable raw request/response file logging. */
41
+ enabled?: boolean;
42
+ /** Root log directory. SDK writes requests/*.json and responses/*.jsonl below this directory. Defaults to ~/.routstrd/request-response-logs. */
43
+ dir?: string;
44
+ };
37
45
  daemonUrl?: string;
38
46
  /** URL of the auth proxy (routstrd-auth) for management endpoints (npubs, clients, usage).
39
47
  * Defaults to daemonUrl or localhost:{port} if not set. */
@@ -41,6 +49,9 @@ export interface RoutstrdConfig {
41
49
  nsec?: string;
42
50
  /** Nostr hex pubkey for routstr review/model events (kind 38425/38423). */
43
51
  routstrPubkey?: string;
52
+ /** Nostr relay URLs for provider/model discovery (kinds 38421/38423/38425).
53
+ * When unset, each method uses its own built-in defaults. */
54
+ relays?: string[];
44
55
  /** NWC integration configuration */
45
56
  nwc?: NwcConfig;
46
57
  }
package/new-task.md DELETED
@@ -1,60 +0,0 @@
1
- # Hot-reload NWC connection (remove restart requirement)
2
-
3
- ## Problem
4
-
5
- `nwc connect` and `nwc disconnect` require a daemon restart to take effect. The
6
- CLI writes the new connection string to disk, but the daemon never re-reads it.
7
-
8
- ## Current flow
9
-
10
- 1. **Startup** — `createWalletAdapter` reads `options.nwcConnectionString` and
11
- creates a `WalletConnect` (relay pool + NWC wallet service) once:
12
- ```ts
13
- // src/daemon/wallet/index.ts:70-78
14
- if (options.nwcConnectionString) {
15
- wallet = WalletConnect.fromConnectURI(options.nwcConnectionString, { pool });
16
- }
17
- ```
18
-
19
- 2. **CLI `nwc connect`** — HTTP handler at `POST /nwc/connect` only calls
20
- `saveDaemonConfig(config)`. The running `WalletConnect` instance is untouched.
21
-
22
- 3. **Result** — the old connection (or lack thereof) stays active until restart.
23
-
24
- ## What needs to happen
25
-
26
- Provide a way for the daemon to tear down the old `WalletConnect` and create a
27
- new one from the updated connection string, triggered by the HTTP handler,
28
- **without restarting the process**.
29
-
30
- ### Key pieces
31
-
32
- - **`src/daemon/wallet/index.ts`** — `createWalletAdapter` needs to expose a
33
- `reconnect(connectionString: string)` method that:
34
- - Closes the old relay pool / WalletConnect
35
- - Creates a new `WalletConnect` from the new connection string
36
- - Updates the adapter's internal `wallet` reference
37
- - If connection string is empty/undefined, disconnects and sets `wallet` to
38
- `undefined`
39
-
40
- - **`src/daemon/http/index.ts`** — `POST /nwc/connect` and `POST /nwc/disconnect`
41
- handlers should call `reconnect()` after saving config, and drop the "Restart
42
- daemon" message.
43
-
44
- - **`src/daemon/index.ts`** — may need to store the `reconnect` function and pass
45
- it through `DaemonDeps` to the HTTP handler.
46
-
47
- - **`src/cli.ts`** — remove `console.log("\nRun 'routstrd restart' to connect...")`
48
- from the connect/disconnect commands.
49
-
50
- ### Considerations
51
-
52
- - The `WalletConnect` instance is referenced in the auto-refill loop (passed to
53
- `startAutoRefillLoop`). After a reconnect, the auto-refill loop's captured
54
- `wallet` reference would be stale. The loop already reads config from disk
55
- each cycle, so it should also reference the latest `wallet` instance.
56
- - Could make the auto-refill loop accept a `getWallet: () => WalletConnect |
57
- undefined` getter, same pattern as the config getter.
58
- - Relay pool cleanup — `applesauce-wallet-connect` / `applesauce-relay` may need
59
- explicit `pool.close()` or `pool.destroy()` to free connections.
60
- - Edge case: a refill is in progress when reconnect is triggered.