@narumitw/pi-ticker 0.0.0
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/LICENSE +21 -0
- package/README.md +189 -0
- package/dist/chunks/chunk-U5NETXSC.js +138 -0
- package/dist/chunks/chunk-U5NETXSC.js.map +7 -0
- package/dist/chunks/menu-WR7QV3P4.js +208 -0
- package/dist/chunks/menu-WR7QV3P4.js.map +7 -0
- package/dist/chunks/tui-menu-KQLX7NJ5.js +433 -0
- package/dist/chunks/tui-menu-KQLX7NJ5.js.map +7 -0
- package/dist/index.ts +496 -0
- package/dist/index.ts.map +7 -0
- package/package.json +60 -0
- package/src/index.ts +1 -0
- package/src/menu.ts +241 -0
- package/src/quotes.ts +104 -0
- package/src/render.ts +163 -0
- package/src/settings.ts +172 -0
- package/src/ticker.ts +341 -0
- package/src/tui-menu.ts +499 -0
package/src/ticker.ts
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import {
|
|
3
|
+
type ExtensionAPI,
|
|
4
|
+
type ExtensionCommandContext,
|
|
5
|
+
type ExtensionContext,
|
|
6
|
+
getAgentDir,
|
|
7
|
+
type Theme,
|
|
8
|
+
} from "@earendil-works/pi-coding-agent";
|
|
9
|
+
import type { AutocompleteItem } from "@earendil-works/pi-tui";
|
|
10
|
+
import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
|
|
11
|
+
import { fetchQuotes, QuoteRequestTimeoutError } from "./quotes.js";
|
|
12
|
+
import {
|
|
13
|
+
formatTickerPlain,
|
|
14
|
+
mergeQuoteResults,
|
|
15
|
+
renderTickerWidget,
|
|
16
|
+
type TickerItem,
|
|
17
|
+
type TickerView,
|
|
18
|
+
} from "./render.js";
|
|
19
|
+
import { createSettingsWriter, loadSettings, normalizeSymbols, parseSymbols } from "./settings.js";
|
|
20
|
+
|
|
21
|
+
export interface StockTickerDependencies {
|
|
22
|
+
createSettingsWriter: typeof createSettingsWriter;
|
|
23
|
+
loadSettings: typeof loadSettings;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const WIDGET_KEY = "ticker";
|
|
27
|
+
export const SETTINGS_FILE_NAME = "pi-ticker.json";
|
|
28
|
+
export const POLL_INTERVAL_MS = 30_000;
|
|
29
|
+
export const REQUEST_TIMEOUT_MS = 10_000;
|
|
30
|
+
|
|
31
|
+
const HELP = "Usage: /ticker [SYMBOL ...] | /ticker refresh | /ticker reset | /ticker help";
|
|
32
|
+
const COMPLETIONS: AutocompleteItem[] = [
|
|
33
|
+
{ value: "refresh", label: "refresh", description: "Refresh quotes now" },
|
|
34
|
+
{ value: "reset", label: "reset", description: "Explain why no default reset is available" },
|
|
35
|
+
{ value: "help", label: "help", description: "Show command usage" },
|
|
36
|
+
];
|
|
37
|
+
|
|
38
|
+
export default function stockTicker(
|
|
39
|
+
pi: ExtensionAPI,
|
|
40
|
+
dependencies: Partial<StockTickerDependencies> = {},
|
|
41
|
+
): void {
|
|
42
|
+
let activeSession: ExtensionContext["sessionManager"] | undefined;
|
|
43
|
+
let generation = 0;
|
|
44
|
+
let cycleVersion = 0;
|
|
45
|
+
let pollTimer: ReturnType<typeof setTimeout> | undefined;
|
|
46
|
+
let requestController: AbortController | undefined;
|
|
47
|
+
let sessionController: AbortController | undefined;
|
|
48
|
+
const activeMenus = new Set<Promise<void>>();
|
|
49
|
+
let symbols: string[] = [];
|
|
50
|
+
let widgetEnabled = true;
|
|
51
|
+
let view: TickerView = createInitialView(symbols);
|
|
52
|
+
const settingsWriter = (dependencies.createSettingsWriter ?? createSettingsWriter)();
|
|
53
|
+
const readSettings = dependencies.loadSettings ?? loadSettings;
|
|
54
|
+
|
|
55
|
+
const ownsSession = (ctx: ExtensionContext, expectedGeneration = generation): boolean =>
|
|
56
|
+
ctx.sessionManager === activeSession && expectedGeneration === generation;
|
|
57
|
+
|
|
58
|
+
const publish = (ctx: ExtensionContext): void => {
|
|
59
|
+
if (!ctx.hasUI || !ownsSession(ctx)) return;
|
|
60
|
+
if (!widgetEnabled || view.items.length === 0) {
|
|
61
|
+
ctx.ui.setWidget(WIDGET_KEY, undefined);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const snapshot = cloneView(view);
|
|
65
|
+
if (ctx.mode === "tui") {
|
|
66
|
+
ctx.ui.setWidget(
|
|
67
|
+
WIDGET_KEY,
|
|
68
|
+
(_tui: unknown, theme: Theme) => ({
|
|
69
|
+
render: (width: number) => renderTickerWidget(snapshot, theme, width),
|
|
70
|
+
invalidate: () => {},
|
|
71
|
+
}),
|
|
72
|
+
{ placement: "aboveEditor" },
|
|
73
|
+
);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
ctx.ui.setWidget(WIDGET_KEY, formatTickerPlain(snapshot), { placement: "aboveEditor" });
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const stopPolling = (): void => {
|
|
80
|
+
cycleVersion += 1;
|
|
81
|
+
if (pollTimer) clearTimeout(pollTimer);
|
|
82
|
+
pollTimer = undefined;
|
|
83
|
+
requestController?.abort();
|
|
84
|
+
requestController = undefined;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const clearWidget = (ctx: ExtensionContext): void => {
|
|
88
|
+
if (ctx.hasUI) ctx.ui.setWidget(WIDGET_KEY, undefined);
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const runCycle = async (
|
|
92
|
+
ctx: ExtensionContext,
|
|
93
|
+
expectedGeneration: number,
|
|
94
|
+
expectedCycle: number,
|
|
95
|
+
): Promise<void> => {
|
|
96
|
+
if (!ownsSession(ctx, expectedGeneration) || expectedCycle !== cycleVersion) return;
|
|
97
|
+
view = { ...view, loading: true };
|
|
98
|
+
publish(ctx);
|
|
99
|
+
|
|
100
|
+
const controller = new AbortController();
|
|
101
|
+
requestController = controller;
|
|
102
|
+
const timeout = setTimeout(() => {
|
|
103
|
+
controller.abort(new QuoteRequestTimeoutError());
|
|
104
|
+
}, REQUEST_TIMEOUT_MS);
|
|
105
|
+
try {
|
|
106
|
+
const results = await fetchQuotes(symbols, controller.signal);
|
|
107
|
+
if (!ownsSession(ctx, expectedGeneration) || expectedCycle !== cycleVersion) return;
|
|
108
|
+
view = {
|
|
109
|
+
items: mergeQuoteResults(view.items, results),
|
|
110
|
+
loading: false,
|
|
111
|
+
updatedAt: results.some((result) => result.quote) ? Date.now() : view.updatedAt,
|
|
112
|
+
};
|
|
113
|
+
publish(ctx);
|
|
114
|
+
} catch {
|
|
115
|
+
if (
|
|
116
|
+
!controller.signal.aborted &&
|
|
117
|
+
ownsSession(ctx, expectedGeneration) &&
|
|
118
|
+
expectedCycle === cycleVersion
|
|
119
|
+
) {
|
|
120
|
+
view = {
|
|
121
|
+
items: view.items.map((item) => ({
|
|
122
|
+
...item,
|
|
123
|
+
stale: Boolean(item.quote),
|
|
124
|
+
error: "unavailable",
|
|
125
|
+
})),
|
|
126
|
+
loading: false,
|
|
127
|
+
updatedAt: view.updatedAt,
|
|
128
|
+
};
|
|
129
|
+
publish(ctx);
|
|
130
|
+
}
|
|
131
|
+
} finally {
|
|
132
|
+
clearTimeout(timeout);
|
|
133
|
+
if (requestController === controller) requestController = undefined;
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
const startCycle = (ctx: ExtensionContext, expectedGeneration = generation): void => {
|
|
138
|
+
if (!ownsSession(ctx, expectedGeneration)) return;
|
|
139
|
+
if (!widgetEnabled || symbols.length === 0) {
|
|
140
|
+
stopPolling();
|
|
141
|
+
publish(ctx);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (pollTimer) clearTimeout(pollTimer);
|
|
145
|
+
requestController?.abort();
|
|
146
|
+
const expectedCycle = ++cycleVersion;
|
|
147
|
+
void runCycle(ctx, expectedGeneration, expectedCycle).finally(() => {
|
|
148
|
+
if (!ownsSession(ctx, expectedGeneration) || expectedCycle !== cycleVersion) return;
|
|
149
|
+
pollTimer = setTimeout(() => startCycle(ctx, expectedGeneration), POLL_INTERVAL_MS);
|
|
150
|
+
});
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
const openMenu = async (ctx: ExtensionCommandContext): Promise<void> => {
|
|
154
|
+
const controller = sessionController;
|
|
155
|
+
const expectedGeneration = generation;
|
|
156
|
+
if (!controller || controller.signal.aborted || !ownsSession(ctx, expectedGeneration)) return;
|
|
157
|
+
const running = (async () => {
|
|
158
|
+
const { showTickerMenu } = await import("./menu.js");
|
|
159
|
+
if (controller.signal.aborted || !ownsSession(ctx, expectedGeneration)) return;
|
|
160
|
+
await showTickerMenu(ctx, {
|
|
161
|
+
signal: controller.signal,
|
|
162
|
+
isCurrent: () => !controller.signal.aborted && ownsSession(ctx, expectedGeneration),
|
|
163
|
+
getSymbols: () => [...symbols],
|
|
164
|
+
applySymbols: async (nextSymbols, signal) => {
|
|
165
|
+
if (signal.aborted || !ownsSession(ctx, expectedGeneration)) return;
|
|
166
|
+
const normalized = normalizeSymbols(nextSymbols, true);
|
|
167
|
+
await settingsWriter.save(settingsPath(), normalized);
|
|
168
|
+
if (signal.aborted || !ownsSession(ctx, expectedGeneration)) return;
|
|
169
|
+
symbols = normalized;
|
|
170
|
+
view = createInitialView(symbols);
|
|
171
|
+
publish(ctx);
|
|
172
|
+
startCycle(ctx, expectedGeneration);
|
|
173
|
+
},
|
|
174
|
+
getWidgetEnabled: () => widgetEnabled,
|
|
175
|
+
applyWidgetEnabled: async (nextWidgetEnabled, signal) => {
|
|
176
|
+
if (signal.aborted || !ownsSession(ctx, expectedGeneration)) return;
|
|
177
|
+
await settingsWriter.saveWidgetEnabled(settingsPath(), nextWidgetEnabled);
|
|
178
|
+
if (signal.aborted || !ownsSession(ctx, expectedGeneration)) return;
|
|
179
|
+
widgetEnabled = nextWidgetEnabled;
|
|
180
|
+
if (!widgetEnabled) stopPolling();
|
|
181
|
+
publish(ctx);
|
|
182
|
+
if (widgetEnabled) startCycle(ctx, expectedGeneration);
|
|
183
|
+
},
|
|
184
|
+
refresh: () => {
|
|
185
|
+
if (!ownsSession(ctx, expectedGeneration)) return;
|
|
186
|
+
if (!widgetEnabled) {
|
|
187
|
+
notify(ctx, "Ticker widget is disabled. Enable it before refreshing.", "warning");
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
startCycle(ctx, expectedGeneration);
|
|
191
|
+
},
|
|
192
|
+
});
|
|
193
|
+
})();
|
|
194
|
+
activeMenus.add(running);
|
|
195
|
+
try {
|
|
196
|
+
await running;
|
|
197
|
+
} finally {
|
|
198
|
+
activeMenus.delete(running);
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
203
|
+
sessionController?.abort();
|
|
204
|
+
stopPolling();
|
|
205
|
+
activeSession = ctx.sessionManager;
|
|
206
|
+
sessionController = new AbortController();
|
|
207
|
+
const expectedGeneration = ++generation;
|
|
208
|
+
symbols = [];
|
|
209
|
+
widgetEnabled = true;
|
|
210
|
+
view = createInitialView(symbols);
|
|
211
|
+
publish(ctx);
|
|
212
|
+
|
|
213
|
+
await settingsWriter.flush();
|
|
214
|
+
if (!ownsSession(ctx, expectedGeneration)) return;
|
|
215
|
+
const loaded = await readSettings(settingsPath());
|
|
216
|
+
if (!ownsSession(ctx, expectedGeneration)) return;
|
|
217
|
+
symbols = loaded.settings.symbols;
|
|
218
|
+
widgetEnabled = loaded.settings.widgetEnabled;
|
|
219
|
+
view = createInitialView(symbols);
|
|
220
|
+
publish(ctx);
|
|
221
|
+
if (loaded.warning) notify(ctx, loaded.warning, "warning");
|
|
222
|
+
if (ctx.hasUI && widgetEnabled && symbols.length > 0) startCycle(ctx, expectedGeneration);
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
pi.on("session_shutdown", async (_event, ctx) => {
|
|
226
|
+
if (!ownsSession(ctx)) return;
|
|
227
|
+
sessionController?.abort();
|
|
228
|
+
stopPolling();
|
|
229
|
+
clearWidget(ctx);
|
|
230
|
+
activeSession = undefined;
|
|
231
|
+
sessionController = undefined;
|
|
232
|
+
generation += 1;
|
|
233
|
+
await Promise.allSettled([...activeMenus]);
|
|
234
|
+
await settingsWriter.flush();
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
pi.registerCommand("ticker", {
|
|
238
|
+
description: "Show or change the stock ticker symbols",
|
|
239
|
+
getArgumentCompletions: completeArguments,
|
|
240
|
+
handler: async (argumentsText, ctx) => {
|
|
241
|
+
if (!ctx.hasUI) {
|
|
242
|
+
throw new Error("The /ticker command requires TUI or RPC mode.");
|
|
243
|
+
}
|
|
244
|
+
const input = argumentsText.trim();
|
|
245
|
+
if (!input) {
|
|
246
|
+
await openMenu(ctx);
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const words = input.split(/\s+/);
|
|
251
|
+
const route = words[0]?.toLowerCase();
|
|
252
|
+
if (["help", "refresh", "reset"].includes(route ?? "") && words.length > 1) {
|
|
253
|
+
notify(ctx, `${route} does not accept trailing arguments.`, "error");
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
if (route === "help") {
|
|
257
|
+
notify(ctx, HELP);
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
if (route === "refresh") {
|
|
261
|
+
if (!widgetEnabled) {
|
|
262
|
+
notify(
|
|
263
|
+
ctx,
|
|
264
|
+
"Ticker widget is disabled. Enable it with /ticker before refreshing.",
|
|
265
|
+
"warning",
|
|
266
|
+
);
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if (ownsSession(ctx)) startCycle(ctx);
|
|
270
|
+
notify(ctx, "Refreshing stock quotes.");
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (route === "reset") {
|
|
275
|
+
notify(
|
|
276
|
+
ctx,
|
|
277
|
+
"No default ticker list is configured. Use /ticker SYMBOL ... instead.",
|
|
278
|
+
"error",
|
|
279
|
+
);
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
let nextSymbols: string[];
|
|
284
|
+
try {
|
|
285
|
+
nextSymbols = parseSymbols([input]);
|
|
286
|
+
} catch (error) {
|
|
287
|
+
notify(ctx, errorMessage(error), "error");
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
try {
|
|
291
|
+
await settingsWriter.save(settingsPath(), nextSymbols);
|
|
292
|
+
} catch (error) {
|
|
293
|
+
notify(ctx, `Could not save stock ticker settings: ${errorMessage(error)}`, "error");
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
if (!ownsSession(ctx)) return;
|
|
297
|
+
symbols = nextSymbols;
|
|
298
|
+
view = createInitialView(symbols);
|
|
299
|
+
publish(ctx);
|
|
300
|
+
startCycle(ctx);
|
|
301
|
+
notify(ctx, `Stock ticker symbols: ${symbols.join(" ")}`);
|
|
302
|
+
},
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export function settingsPath(): string {
|
|
307
|
+
return join(getAgentDir(), SETTINGS_FILE_NAME);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
export function completeArguments(prefix: string): AutocompleteItem[] | null {
|
|
311
|
+
if (/\s/.test(prefix)) return null;
|
|
312
|
+
const normalized = prefix.toLowerCase();
|
|
313
|
+
const matches = COMPLETIONS.filter((item) => item.value.toLowerCase().startsWith(normalized));
|
|
314
|
+
return matches.length > 0 ? matches : null;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function createInitialView(symbols: readonly string[]): TickerView {
|
|
318
|
+
return {
|
|
319
|
+
items: symbols.map((symbol): TickerItem => ({ symbol })),
|
|
320
|
+
loading: true,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function cloneView(view: TickerView): TickerView {
|
|
325
|
+
return {
|
|
326
|
+
...view,
|
|
327
|
+
items: view.items.map((item) => ({ ...item, quote: item.quote && { ...item.quote } })),
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function notify(
|
|
332
|
+
ctx: ExtensionContext,
|
|
333
|
+
message: string,
|
|
334
|
+
type: "info" | "warning" | "error" = "info",
|
|
335
|
+
): void {
|
|
336
|
+
if (ctx.hasUI) ctx.ui.notify(sanitizeTerminalText(message), type);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function errorMessage(error: unknown): string {
|
|
340
|
+
return error instanceof Error ? error.message : String(error);
|
|
341
|
+
}
|