opencode-windows-scheduler 1.0.0 → 1.1.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/CHANGELOG.md +14 -7
- package/README.md +2 -2
- package/README.ru.md +2 -2
- package/ROADMAP.md +11 -8
- package/dist/core/analytics.d.ts +119 -0
- package/dist/core/analytics.d.ts.map +1 -0
- package/dist/core/analytics.js +265 -0
- package/dist/core/retention.d.ts +29 -0
- package/dist/core/retention.d.ts.map +1 -0
- package/dist/core/retention.js +98 -0
- package/dist/db/history-repo.d.ts +33 -0
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +65 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +85 -3
- package/dist/rpc.d.ts +134 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +61 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +195 -5
- package/dist/settings.d.ts +23 -0
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +41 -0
- package/dist/version.d.ts +8 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +27 -0
- package/docs/ARCHITECTURE.md +13 -1
- package/docs/FEATURES.md +17 -5
- package/gui-experimental.cjs +2 -2
- package/package.json +4 -2
- package/src/core/analytics.ts +378 -0
- package/src/core/retention.ts +141 -0
- package/src/db/history-repo.ts +93 -0
- package/src/gui.tsx +2868 -2725
- package/src/index.ts +100 -4
- package/src/rpc.ts +66 -0
- package/src/server.ts +221 -5
- package/src/settings.ts +71 -0
- package/src/version.ts +27 -0
- package/dist/gui-experimental.cjs +0 -1
package/dist/server.js
CHANGED
|
@@ -3,7 +3,10 @@ import fs from "node:fs/promises";
|
|
|
3
3
|
import { execFile } from "node:child_process";
|
|
4
4
|
import { promisify } from "node:util";
|
|
5
5
|
import { loadHistory, loadMetrics } from "./history.js";
|
|
6
|
+
import { getHistory, countRunningRecords } from "./db/history-repo.js";
|
|
7
|
+
import { buildAnalytics, historyToCsv } from "./core/analytics.js";
|
|
6
8
|
import { getSchedulerTitle } from "./core/scheduler/index.js";
|
|
9
|
+
import { getPluginVersion } from "./version.js";
|
|
7
10
|
import { checkpointDb, getDbFile, getDbStatus } from "./db/index.js";
|
|
8
11
|
import { listWorkspaces } from "./workspaces.js";
|
|
9
12
|
import { simulatePipeline } from "./core/dry-run.js";
|
|
@@ -331,6 +334,8 @@ async function handleRequest(req, res, deps) {
|
|
|
331
334
|
pathname === "/api/history" ||
|
|
332
335
|
pathname === "/api/metrics" ||
|
|
333
336
|
pathname === "/api/models-analysis" ||
|
|
337
|
+
pathname === "/api/analytics" ||
|
|
338
|
+
pathname === "/api/history/export" ||
|
|
334
339
|
pathname === "/api/export-db" ||
|
|
335
340
|
pathname === "/api/workspaces" ||
|
|
336
341
|
pathname === "/api/health" ||
|
|
@@ -356,6 +361,9 @@ async function handleRequest(req, res, deps) {
|
|
|
356
361
|
ok: true,
|
|
357
362
|
app: DASHBOARD_MARKER,
|
|
358
363
|
port: getDashboardPort(),
|
|
364
|
+
version: getPluginVersion(),
|
|
365
|
+
scheduler: getSchedulerTitle(),
|
|
366
|
+
queueDepth: countRunningRecords(),
|
|
359
367
|
db: getDbStatus(),
|
|
360
368
|
});
|
|
361
369
|
return;
|
|
@@ -454,6 +462,40 @@ async function handleRequest(req, res, deps) {
|
|
|
454
462
|
sendJson(res, 200, aggregateModels(history));
|
|
455
463
|
return;
|
|
456
464
|
}
|
|
465
|
+
// Аналитика за период (Спринт 18): итоги, дневные бакеты, топ по стоимости.
|
|
466
|
+
if (req.method === "GET" && pathname === "/api/analytics") {
|
|
467
|
+
const days = Math.min(365, Math.max(1, Math.floor(Number(url.searchParams.get("days")) || 14)));
|
|
468
|
+
const topLimit = Math.max(1, Math.floor(Number(url.searchParams.get("top")) || 10));
|
|
469
|
+
const records = getHistory(null, 20000);
|
|
470
|
+
const tasks = await deps.getTasks();
|
|
471
|
+
const report = buildAnalytics(records, {
|
|
472
|
+
days,
|
|
473
|
+
topLimit,
|
|
474
|
+
tasks: tasks.map((task) => ({
|
|
475
|
+
name: task.name,
|
|
476
|
+
matrixParentId: task.matrixParentId ?? null,
|
|
477
|
+
})),
|
|
478
|
+
});
|
|
479
|
+
sendJson(res, 200, report);
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
// Экспорт истории: CSV (для Excel) или JSON (для скриптов).
|
|
483
|
+
if (req.method === "GET" && pathname === "/api/history/export") {
|
|
484
|
+
const format = (url.searchParams.get("format") || "csv").toLowerCase();
|
|
485
|
+
if (format !== "csv" && format !== "json") {
|
|
486
|
+
sendJson(res, 400, { error: "Неподдерживаемый формат экспорта. Допустимые: csv, json." });
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
const records = getHistory(null, 100000);
|
|
490
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
491
|
+
if (format === "json") {
|
|
492
|
+
sendAttachment(res, 200, "application/json; charset=utf-8", JSON.stringify({ exportedAt: new Date().toISOString(), records }, null, 2), `history-${stamp}.json`);
|
|
493
|
+
}
|
|
494
|
+
else {
|
|
495
|
+
sendAttachment(res, 200, "text/csv; charset=utf-8", historyToCsv(records), `history-${stamp}.csv`);
|
|
496
|
+
}
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
457
499
|
if (req.method === "GET" && (pathname === "/api/metrics" || pathname === "/api/summary")) {
|
|
458
500
|
const metrics = await loadMetrics();
|
|
459
501
|
// Токены и стоимость суммируем по history.json (как требует спринт):
|
|
@@ -637,6 +679,22 @@ function sendBuffer(res, status, contentType, body, filename) {
|
|
|
637
679
|
});
|
|
638
680
|
res.end(body);
|
|
639
681
|
}
|
|
682
|
+
/** Отправляет текстовый файл (CSV/JSON-экспорт истории). */
|
|
683
|
+
function sendAttachment(res, status, contentType, body, filename) {
|
|
684
|
+
if (res.headersSent) {
|
|
685
|
+
res.end();
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
res.writeHead(status, {
|
|
689
|
+
"Content-Type": contentType,
|
|
690
|
+
"Content-Length": String(Buffer.byteLength(body, "utf8")),
|
|
691
|
+
"Content-Disposition": `attachment; filename="${filename}"`,
|
|
692
|
+
"Cache-Control": "no-store",
|
|
693
|
+
"X-Content-Type-Options": "nosniff",
|
|
694
|
+
[DASHBOARD_HEADER]: DASHBOARD_MARKER,
|
|
695
|
+
});
|
|
696
|
+
res.end(body);
|
|
697
|
+
}
|
|
640
698
|
/**
|
|
641
699
|
* Список задач + метрики по каждой задаче, посчитанные из history.json
|
|
642
700
|
* (колонка «Метрики» в таблице дашборда).
|
|
@@ -733,6 +791,24 @@ function renderPage() {
|
|
|
733
791
|
.prio { font-size: 12px; color: #f5a623; white-space: nowrap; }
|
|
734
792
|
.hist { margin-top: 18px; background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 14px 18px; }
|
|
735
793
|
.hist h2 { margin: 0 0 10px; font-size: 14px; font-weight: 600; }
|
|
794
|
+
.an-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
|
795
|
+
.an-actions { display: flex; gap: 6px; }
|
|
796
|
+
.an-actions .btn { padding: 3px 8px; font-size: 11px; }
|
|
797
|
+
.an-kpis { display: flex; flex-wrap: wrap; gap: 14px; margin-bottom: 12px; font-size: 12px; color: var(--muted); }
|
|
798
|
+
.an-kpis b { color: var(--text); font-size: 14px; }
|
|
799
|
+
.an-chart { display: flex; align-items: flex-end; gap: 4px; height: 120px; padding: 6px 0 0; border-bottom: 1px solid var(--border); overflow-x: auto; }
|
|
800
|
+
.an-bar { flex: 1 1 0; min-width: 14px; display: flex; flex-direction: column; align-items: center; justify-content: flex-end; height: 100%; cursor: default; }
|
|
801
|
+
.an-bar-fill { width: 100%; border-radius: 3px 3px 0 0; background: var(--accent); opacity: .85; }
|
|
802
|
+
.an-label { font-size: 9px; color: var(--muted); margin-top: 4px; white-space: nowrap; }
|
|
803
|
+
.an-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; margin-top: 14px; }
|
|
804
|
+
.an-grid h3 { margin: 0 0 6px; font-size: 12px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: .5px; }
|
|
805
|
+
.an-table { width: 100%; border-collapse: collapse; font-size: 12px; }
|
|
806
|
+
.an-table th { text-align: left; color: var(--muted); font-weight: 600; padding: 3px 6px; border-bottom: 1px solid var(--border); }
|
|
807
|
+
.an-table td { padding: 3px 6px; border-bottom: 1px solid var(--border); color: var(--text); }
|
|
808
|
+
.an-table tr:last-child td { border-bottom: none; }
|
|
809
|
+
.an-rate.okr { color: var(--ok); }
|
|
810
|
+
.an-rate.midr { color: var(--run); }
|
|
811
|
+
.an-rate.errr { color: var(--err); }
|
|
736
812
|
.hist-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: 10px; padding: 5px 0; border-bottom: 1px solid var(--border); font-size: 12px; }
|
|
737
813
|
.hist-row:last-child { border-bottom: none; }
|
|
738
814
|
.hist-time { color: var(--muted); white-space: nowrap; }
|
|
@@ -741,8 +817,7 @@ function renderPage() {
|
|
|
741
817
|
.hist-hook { white-space: nowrap; }
|
|
742
818
|
.hist-hook.okh { color: #34c759; }
|
|
743
819
|
.hist-hook.errh { color: #ff3b30; }
|
|
744
|
-
.whatif-text { margin-top: 10px; font-size: 12px; color: var(--muted); line-height: 1.5; }
|
|
745
|
-
.whatif-text b { color: var(--text); }
|
|
820
|
+
.whatif-text { margin-top: 10px; font-size: 12px; color: var(--muted); line-height: 1.5; } .whatif-text b { color: var(--text); }
|
|
746
821
|
.wi-table { width: 100%; border-collapse: collapse; font-size: 12px; }
|
|
747
822
|
.wi-table th { text-align: left; color: var(--muted); font-weight: 600; padding: 4px 8px; border-bottom: 1px solid var(--border); }
|
|
748
823
|
.wi-table td { padding: 4px 8px; border-bottom: 1px solid var(--border); color: var(--text); }
|
|
@@ -833,6 +908,22 @@ function renderPage() {
|
|
|
833
908
|
<div id="history"><div class="empty">Загрузка…</div></div>
|
|
834
909
|
</div>
|
|
835
910
|
|
|
911
|
+
<div class="hist">
|
|
912
|
+
<div class="an-head">
|
|
913
|
+
<h2>📊 Аналитика за период</h2>
|
|
914
|
+
<div class="an-actions">
|
|
915
|
+
<a class="btn" href="/api/history/export?format=csv" download>⬇️ CSV</a>
|
|
916
|
+
<a class="btn" href="/api/history/export?format=json" download>⬇️ JSON</a>
|
|
917
|
+
</div>
|
|
918
|
+
</div>
|
|
919
|
+
<div class="an-kpis" id="an-kpis"><span>Загрузка…</span></div>
|
|
920
|
+
<div class="an-chart" id="an-chart"></div>
|
|
921
|
+
<div class="an-grid">
|
|
922
|
+
<div><h3>Топ задач по стоимости</h3><div id="an-top"></div></div>
|
|
923
|
+
<div><h3>Матрицы</h3><div id="an-matrices"></div></div>
|
|
924
|
+
</div>
|
|
925
|
+
</div>
|
|
926
|
+
|
|
836
927
|
<div class="hist">
|
|
837
928
|
<h2>📊 What-If: Анализ моделей</h2>
|
|
838
929
|
<div id="whatif-table"><div class="empty">Загрузка…</div></div>
|
|
@@ -1027,8 +1118,105 @@ function renderPage() {
|
|
|
1027
1118
|
box.innerHTML = html;
|
|
1028
1119
|
}
|
|
1029
1120
|
|
|
1030
|
-
function
|
|
1031
|
-
|
|
1121
|
+
function rateClass(rate) {
|
|
1122
|
+
if (rate >= 90) return 'okr';
|
|
1123
|
+
if (rate >= 60) return 'midr';
|
|
1124
|
+
return 'errr';
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
function money(value) {
|
|
1128
|
+
var n = Number(value) || 0;
|
|
1129
|
+
return '$' + n.toFixed(n >= 1 ? 2 : 4);
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
function durationText(ms) {
|
|
1133
|
+
var n = Number(ms) || 0;
|
|
1134
|
+
if (n <= 0) return '—';
|
|
1135
|
+
if (n < 1000) return n + ' мс';
|
|
1136
|
+
if (n < 60000) return (n / 1000).toFixed(1) + ' с';
|
|
1137
|
+
return Math.round(n / 60000) + ' мин';
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
function renderAnalytics(an) {
|
|
1141
|
+
var kpis = document.getElementById('an-kpis');
|
|
1142
|
+
var chart = document.getElementById('an-chart');
|
|
1143
|
+
var top = document.getElementById('an-top');
|
|
1144
|
+
var matrices = document.getElementById('an-matrices');
|
|
1145
|
+
if (!kpis || !chart || !top || !matrices) return;
|
|
1146
|
+
|
|
1147
|
+
if (!an || !an.totals) {
|
|
1148
|
+
kpis.innerHTML = '<span>Аналитика недоступна.</span>';
|
|
1149
|
+
chart.innerHTML = '';
|
|
1150
|
+
top.innerHTML = '<div class="empty" style="padding:10px">—</div>';
|
|
1151
|
+
matrices.innerHTML = '<div class="empty" style="padding:10px">—</div>';
|
|
1152
|
+
return;
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
var t = an.totals;
|
|
1156
|
+
kpis.innerHTML =
|
|
1157
|
+
'<span>Запусков: <b>' + t.total + '</b></span>' +
|
|
1158
|
+
'<span>Успех: <b class="an-rate ' + rateClass(t.successRate) + '">' + t.successRate + '%</b></span>' +
|
|
1159
|
+
'<span>Средняя длительность: <b>' + durationText(t.avgDurationMs) + '</b></span>' +
|
|
1160
|
+
'<span>Токены: <b>' + Number(t.tokens || 0).toLocaleString('ru-RU') + '</b></span>' +
|
|
1161
|
+
'<span>Стоимость: <b>' + money(t.costUsd) + '</b></span>' +
|
|
1162
|
+
'<span>Окно: <b>' + an.windowDays + ' дн.</b></span>' +
|
|
1163
|
+
(t.partial ? '<span>Частично: <b>' + t.partial + '</b></span>' : '');
|
|
1164
|
+
|
|
1165
|
+
var daily = an.daily || [];
|
|
1166
|
+
var max = 1;
|
|
1167
|
+
for (var i = 0; i < daily.length; i++) {
|
|
1168
|
+
if (daily[i].total > max) max = daily[i].total;
|
|
1169
|
+
}
|
|
1170
|
+
var bars = '';
|
|
1171
|
+
for (var j = 0; j < daily.length; j++) {
|
|
1172
|
+
var d = daily[j];
|
|
1173
|
+
var h = d.total > 0 ? Math.max(3, Math.round((d.total / max) * 92)) : 2;
|
|
1174
|
+
var color = d.total === 0 ? 'var(--border)' : (d.error > 0 ? 'var(--err)' : 'var(--ok)');
|
|
1175
|
+
var tip = d.date + ': всего ' + d.total + ', успех ' + d.success + ', ошибок ' + d.error + ', ' + money(d.costUsd);
|
|
1176
|
+
bars += '<div class="an-bar" title="' + esc(tip) + '">' +
|
|
1177
|
+
'<div class="an-bar-fill" style="height:' + h + '%' + ';background:' + esc(color) + '"></div>' +
|
|
1178
|
+
'<div class="an-label">' + esc(String(d.date).slice(5)) + '</div>' +
|
|
1179
|
+
'</div>';
|
|
1180
|
+
}
|
|
1181
|
+
chart.innerHTML = bars || '<div class="empty" style="padding:10px">Нет данных за период.</div>';
|
|
1182
|
+
|
|
1183
|
+
var topRows = an.topByCost || [];
|
|
1184
|
+
if (topRows.length === 0) {
|
|
1185
|
+
top.innerHTML = '<div class="empty" style="padding:10px">Нет запусков за период.</div>';
|
|
1186
|
+
} else {
|
|
1187
|
+
var html = '<table class="an-table"><thead><tr><th>Задача</th><th>Запусков</th><th>Успех</th><th>Стоимость</th></tr></thead><tbody>';
|
|
1188
|
+
for (var k = 0; k < topRows.length; k++) {
|
|
1189
|
+
var row = topRows[k];
|
|
1190
|
+
html += '<tr>' +
|
|
1191
|
+
'<td>' + (row.isMatrixClone ? '↳ ' : '') + esc(row.taskName) + '</td>' +
|
|
1192
|
+
'<td>' + row.total + '</td>' +
|
|
1193
|
+
'<td class="an-rate ' + rateClass(row.successRate) + '">' + row.successRate + '%</td>' +
|
|
1194
|
+
'<td>' + money(row.costUsd) + '</td>' +
|
|
1195
|
+
'</tr>';
|
|
1196
|
+
}
|
|
1197
|
+
top.innerHTML = html + '</tbody></table>';
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
var matrixRows = an.matrices || [];
|
|
1201
|
+
if (matrixRows.length === 0) {
|
|
1202
|
+
matrices.innerHTML = '<div class="empty" style="padding:10px">Матриц за период не запускалось.</div>';
|
|
1203
|
+
} else {
|
|
1204
|
+
var mhtml = '<table class="an-table"><thead><tr><th>Матрица</th><th>Клонов</th><th>Запусков</th><th>Успех</th><th>Стоимость</th></tr></thead><tbody>';
|
|
1205
|
+
for (var q = 0; q < matrixRows.length; q++) {
|
|
1206
|
+
var m = matrixRows[q];
|
|
1207
|
+
mhtml += '<tr>' +
|
|
1208
|
+
'<td>📦 ' + esc(m.parentId) + '</td>' +
|
|
1209
|
+
'<td>' + m.clones + '</td>' +
|
|
1210
|
+
'<td>' + m.total + '</td>' +
|
|
1211
|
+
'<td class="an-rate ' + rateClass(m.successRate) + '">' + m.successRate + '%</td>' +
|
|
1212
|
+
'<td>' + money(m.costUsd) + '</td>' +
|
|
1213
|
+
'</tr>';
|
|
1214
|
+
}
|
|
1215
|
+
matrices.innerHTML = mhtml + '</tbody></table>';
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
function renderModelsAnalysis(data) { var box = document.getElementById('whatif-table');
|
|
1032
1220
|
var text = document.getElementById('whatif-text');
|
|
1033
1221
|
if (!box || !text) return;
|
|
1034
1222
|
var models = (data && data.models) || [];
|
|
@@ -1270,7 +1458,8 @@ function renderPage() {
|
|
|
1270
1458
|
loadMetricsJson(),
|
|
1271
1459
|
safeJson('/api/history', { records: [] }),
|
|
1272
1460
|
safeJson('/api/models-analysis', { models: [], totals: {}, whatIf: [] }),
|
|
1273
|
-
safeJson('/api/workspaces', { workspaces: [] })
|
|
1461
|
+
safeJson('/api/workspaces', { workspaces: [] }),
|
|
1462
|
+
safeJson('/api/analytics?days=14', null)
|
|
1274
1463
|
]);
|
|
1275
1464
|
var tasks = (results[0] && results[0].tasks) || [];
|
|
1276
1465
|
var m = results[1] || {};
|
|
@@ -1289,6 +1478,7 @@ function renderPage() {
|
|
|
1289
1478
|
renderGraph(tasks);
|
|
1290
1479
|
renderHistory(history);
|
|
1291
1480
|
renderModelsAnalysis(modelsAnalysis);
|
|
1481
|
+
renderAnalytics(results[5]);
|
|
1292
1482
|
showServerWarn(results[0] ? null : 'Не удалось загрузить список задач — остальные блоки обновлены. Подробности в консоли (F12).');
|
|
1293
1483
|
updated.textContent = 'Обновлено: ' + new Date().toLocaleTimeString();
|
|
1294
1484
|
} catch (err) {
|
package/dist/settings.d.ts
CHANGED
|
@@ -19,6 +19,23 @@ export interface NotificationSettings {
|
|
|
19
19
|
/** Webhook-канал. */
|
|
20
20
|
webhook?: WebhookNotificationSettings;
|
|
21
21
|
}
|
|
22
|
+
/**
|
|
23
|
+
* Ретеншн истории (Спринт 18).
|
|
24
|
+
*
|
|
25
|
+
* Дашборд и метрики живут на агрегатах, поэтому удаление старых записей
|
|
26
|
+
* не искажает «Всего запусков» и стоимость: чистится только сырая история.
|
|
27
|
+
* 0 — соответствующее ограничение выключено.
|
|
28
|
+
*/
|
|
29
|
+
export interface HistorySettings {
|
|
30
|
+
/** Удалять завершённые записи старше N дней (0 — не удалять по возрасту). */
|
|
31
|
+
retentionDays: number;
|
|
32
|
+
/** Хранить не более N последних записей (0 — без ограничения). */
|
|
33
|
+
maxRecords: number;
|
|
34
|
+
/** Когда последний раз запускалась автоочистка (ISO). */
|
|
35
|
+
lastCleanupAt: string | null;
|
|
36
|
+
/** Сколько записей удалила последняя очистка (для дашборда). */
|
|
37
|
+
lastCleanupDeleted: number;
|
|
38
|
+
}
|
|
22
39
|
/**
|
|
23
40
|
* Глобальные настройки плагина, которые меняются из GUI.
|
|
24
41
|
* Хранятся в settings.json рядом с tasks.json / history.json.
|
|
@@ -30,10 +47,16 @@ export interface SchedulerSettings {
|
|
|
30
47
|
winterMode: boolean;
|
|
31
48
|
/** Уведомления о завершении задач. */
|
|
32
49
|
notifications: NotificationSettings;
|
|
50
|
+
/** Ретеншн истории запусков. */
|
|
51
|
+
history: HistorySettings;
|
|
33
52
|
}
|
|
34
53
|
export declare const SETTINGS_FILE: string;
|
|
35
54
|
export declare const DEFAULT_MAX_CONCURRENT = 1;
|
|
36
55
|
export declare const DEFAULT_WINTER_MODE = false;
|
|
56
|
+
export declare const DEFAULT_RETENTION_DAYS = 30;
|
|
57
|
+
export declare const DEFAULT_MAX_RECORDS = 5000;
|
|
58
|
+
/** Ретеншн по умолчанию: 30 дней и не больше 5000 записей. */
|
|
59
|
+
export declare function defaultHistorySettings(): HistorySettings;
|
|
37
60
|
/** Значения уведомлений по умолчанию: всё выключено, только ошибки. */
|
|
38
61
|
export declare function defaultNotifications(): NotificationSettings;
|
|
39
62
|
/** Читает настройки. Битый/отсутствующий файл — значения по умолчанию. */
|
package/dist/settings.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings.d.ts","sourceRoot":"","sources":["../src/settings.ts"],"names":[],"mappings":"AAIA,6DAA6D;AAC7D,MAAM,WAAW,2BAA2B;IAC1C,wBAAwB;IACxB,OAAO,EAAE,OAAO,CAAC;IACjB,mBAAmB;IACnB,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;;GAKG;AACH,MAAM,WAAW,oBAAoB;IACnC,uCAAuC;IACvC,OAAO,EAAE,OAAO,CAAC;IACjB,yEAAyE;IACzE,WAAW,EAAE,OAAO,CAAC;IACrB,qBAAqB;IACrB,OAAO,CAAC,EAAE,2BAA2B,CAAC;CACvC;AAED;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,sEAAsE;IACtE,aAAa,EAAE,MAAM,CAAC;IACtB,uEAAuE;IACvE,UAAU,EAAE,OAAO,CAAC;IACpB,sCAAsC;IACtC,aAAa,EAAE,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"settings.d.ts","sourceRoot":"","sources":["../src/settings.ts"],"names":[],"mappings":"AAIA,6DAA6D;AAC7D,MAAM,WAAW,2BAA2B;IAC1C,wBAAwB;IACxB,OAAO,EAAE,OAAO,CAAC;IACjB,mBAAmB;IACnB,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;;GAKG;AACH,MAAM,WAAW,oBAAoB;IACnC,uCAAuC;IACvC,OAAO,EAAE,OAAO,CAAC;IACjB,yEAAyE;IACzE,WAAW,EAAE,OAAO,CAAC;IACrB,qBAAqB;IACrB,OAAO,CAAC,EAAE,2BAA2B,CAAC;CACvC;AAED;;;;;;GAMG;AACH,MAAM,WAAW,eAAe;IAC9B,6EAA6E;IAC7E,aAAa,EAAE,MAAM,CAAC;IACtB,kEAAkE;IAClE,UAAU,EAAE,MAAM,CAAC;IACnB,yDAAyD;IACzD,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,gEAAgE;IAChE,kBAAkB,EAAE,MAAM,CAAC;CAC5B;AAED;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,sEAAsE;IACtE,aAAa,EAAE,MAAM,CAAC;IACtB,uEAAuE;IACvE,UAAU,EAAE,OAAO,CAAC;IACpB,sCAAsC;IACtC,aAAa,EAAE,oBAAoB,CAAC;IACpC,gCAAgC;IAChC,OAAO,EAAE,eAAe,CAAC;CAC1B;AAED,eAAO,MAAM,aAAa,QAAyC,CAAC;AACpE,eAAO,MAAM,sBAAsB,IAAI,CAAC;AACxC,eAAO,MAAM,mBAAmB,QAAQ,CAAC;AACzC,eAAO,MAAM,sBAAsB,KAAK,CAAC;AACzC,eAAO,MAAM,mBAAmB,OAAO,CAAC;AAExC,8DAA8D;AAC9D,wBAAgB,sBAAsB,IAAI,eAAe,CAOxD;AAkCD,uEAAuE;AACvE,wBAAgB,oBAAoB,IAAI,oBAAoB,CAM3D;AAsDD,0EAA0E;AAC1E,wBAAsB,YAAY,IAAI,OAAO,CAAC,iBAAiB,CAAC,CA6B/D;AAED,iEAAiE;AACjE,wBAAsB,YAAY,CAChC,KAAK,EAAE,OAAO,CAAC,iBAAiB,CAAC,GAChC,OAAO,CAAC,iBAAiB,CAAC,CAuB5B"}
|
package/dist/settings.js
CHANGED
|
@@ -4,6 +4,41 @@ import { PLUGIN_DIR } from "./types.js";
|
|
|
4
4
|
export const SETTINGS_FILE = path.join(PLUGIN_DIR, "settings.json");
|
|
5
5
|
export const DEFAULT_MAX_CONCURRENT = 1;
|
|
6
6
|
export const DEFAULT_WINTER_MODE = false;
|
|
7
|
+
export const DEFAULT_RETENTION_DAYS = 30;
|
|
8
|
+
export const DEFAULT_MAX_RECORDS = 5000;
|
|
9
|
+
/** Ретеншн по умолчанию: 30 дней и не больше 5000 записей. */
|
|
10
|
+
export function defaultHistorySettings() {
|
|
11
|
+
return {
|
|
12
|
+
retentionDays: DEFAULT_RETENTION_DAYS,
|
|
13
|
+
maxRecords: DEFAULT_MAX_RECORDS,
|
|
14
|
+
lastCleanupAt: null,
|
|
15
|
+
lastCleanupDeleted: 0,
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** Приводит счётчик ретеншна к безопасному целому (>= 0). */
|
|
19
|
+
function normalizeRetentionLimit(value, fallback) {
|
|
20
|
+
const n = Number(value);
|
|
21
|
+
if (!Number.isFinite(n))
|
|
22
|
+
return fallback;
|
|
23
|
+
const int = Math.floor(n);
|
|
24
|
+
return int >= 0 ? int : fallback;
|
|
25
|
+
}
|
|
26
|
+
/** Приводит настройки ретеншна к безопасному виду. */
|
|
27
|
+
function normalizeHistorySettings(value, fallback) {
|
|
28
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
29
|
+
return { ...fallback };
|
|
30
|
+
}
|
|
31
|
+
const raw = value;
|
|
32
|
+
const lastCleanupAt = typeof raw.lastCleanupAt === "string" && raw.lastCleanupAt.trim()
|
|
33
|
+
? raw.lastCleanupAt.trim()
|
|
34
|
+
: null;
|
|
35
|
+
return {
|
|
36
|
+
retentionDays: normalizeRetentionLimit(raw.retentionDays, fallback.retentionDays),
|
|
37
|
+
maxRecords: normalizeRetentionLimit(raw.maxRecords, fallback.maxRecords),
|
|
38
|
+
lastCleanupAt,
|
|
39
|
+
lastCleanupDeleted: normalizeRetentionLimit(raw.lastCleanupDeleted, fallback.lastCleanupDeleted),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
7
42
|
/** Значения уведомлений по умолчанию: всё выключено, только ошибки. */
|
|
8
43
|
export function defaultNotifications() {
|
|
9
44
|
return {
|
|
@@ -59,6 +94,7 @@ function normalizeNotifications(value, fallback) {
|
|
|
59
94
|
/** Читает настройки. Битый/отсутствующий файл — значения по умолчанию. */
|
|
60
95
|
export async function loadSettings() {
|
|
61
96
|
const fallbackNotifications = defaultNotifications();
|
|
97
|
+
const fallbackHistory = defaultHistorySettings();
|
|
62
98
|
try {
|
|
63
99
|
const raw = await fs.readFile(SETTINGS_FILE, "utf8");
|
|
64
100
|
const parsed = JSON.parse(raw);
|
|
@@ -66,6 +102,7 @@ export async function loadSettings() {
|
|
|
66
102
|
maxConcurrent: normalizeMaxConcurrent(parsed?.maxConcurrent, DEFAULT_MAX_CONCURRENT),
|
|
67
103
|
winterMode: normalizeWinterMode(parsed?.winterMode, DEFAULT_WINTER_MODE),
|
|
68
104
|
notifications: normalizeNotifications(parsed?.notifications, fallbackNotifications),
|
|
105
|
+
history: normalizeHistorySettings(parsed?.history, fallbackHistory),
|
|
69
106
|
};
|
|
70
107
|
}
|
|
71
108
|
catch {
|
|
@@ -73,6 +110,7 @@ export async function loadSettings() {
|
|
|
73
110
|
maxConcurrent: DEFAULT_MAX_CONCURRENT,
|
|
74
111
|
winterMode: DEFAULT_WINTER_MODE,
|
|
75
112
|
notifications: fallbackNotifications,
|
|
113
|
+
history: fallbackHistory,
|
|
76
114
|
};
|
|
77
115
|
}
|
|
78
116
|
}
|
|
@@ -89,6 +127,9 @@ export async function saveSettings(patch) {
|
|
|
89
127
|
notifications: patch.notifications !== undefined
|
|
90
128
|
? normalizeNotifications(patch.notifications, current.notifications)
|
|
91
129
|
: current.notifications,
|
|
130
|
+
history: patch.history !== undefined
|
|
131
|
+
? normalizeHistorySettings(patch.history, current.history)
|
|
132
|
+
: current.history,
|
|
92
133
|
};
|
|
93
134
|
await fs.mkdir(PLUGIN_DIR, { recursive: true });
|
|
94
135
|
await fs.writeFile(SETTINGS_FILE, JSON.stringify(next, null, 2), "utf8");
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Версия плагина из package.json.
|
|
3
|
+
*
|
|
4
|
+
* Читается в рантайме из корня пакета рядом со скомпилированным модулем
|
|
5
|
+
* (dist/version.js -> ../package.json). Если файл недоступен — «unknown».
|
|
6
|
+
*/
|
|
7
|
+
export declare function getPluginVersion(): string;
|
|
8
|
+
//# sourceMappingURL=version.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAMA;;;;;GAKG;AACH,wBAAgB,gBAAgB,IAAI,MAAM,CAczC"}
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
let cached = null;
|
|
5
|
+
/**
|
|
6
|
+
* Версия плагина из package.json.
|
|
7
|
+
*
|
|
8
|
+
* Читается в рантайме из корня пакета рядом со скомпилированным модулем
|
|
9
|
+
* (dist/version.js -> ../package.json). Если файл недоступен — «unknown».
|
|
10
|
+
*/
|
|
11
|
+
export function getPluginVersion() {
|
|
12
|
+
if (cached)
|
|
13
|
+
return cached;
|
|
14
|
+
try {
|
|
15
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
16
|
+
const raw = fs.readFileSync(path.join(here, "..", "package.json"), "utf8");
|
|
17
|
+
const pkg = JSON.parse(raw);
|
|
18
|
+
cached =
|
|
19
|
+
typeof pkg.version === "string" && pkg.version.trim()
|
|
20
|
+
? pkg.version.trim()
|
|
21
|
+
: "unknown";
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
cached = "unknown";
|
|
25
|
+
}
|
|
26
|
+
return cached;
|
|
27
|
+
}
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -121,9 +121,12 @@ from their clones instead of their own last run.
|
|
|
121
121
|
| `src/task-transfer.ts` | Export/import, validation, `MatrixConfig` types |
|
|
122
122
|
| `src/workspaces.ts` | Workspace registry and path validation |
|
|
123
123
|
| `src/templates.ts` | Reusable task templates |
|
|
124
|
-
| `src/settings.ts` | Plugin settings and
|
|
124
|
+
| `src/settings.ts` | Plugin settings: notifications and history retention |
|
|
125
125
|
| `src/notifications.ts` | Webhook notifications |
|
|
126
126
|
| `src/history.ts` | History model and status types |
|
|
127
|
+
| `src/version.ts` | Runtime plugin version (reads package.json) |
|
|
128
|
+
| `src/core/retention.ts` | Daily history prune and incremental vacuum |
|
|
129
|
+
| `src/core/analytics.ts` | Pure 14-day analytics and CSV export |
|
|
127
130
|
| `src/core/scheduler/` | Platform backends, registry, logs |
|
|
128
131
|
| `src/core/ps-wrapper.ts` | PowerShell wrapper template and `.cmd` generation |
|
|
129
132
|
| `src/core/wrappers/bash.ts` | POSIX wrapper template |
|
|
@@ -184,6 +187,15 @@ If the host or the machine dies mid-run, the row stays in `running`. On the next
|
|
|
184
187
|
plugin activation, `db/recovery.ts` marks stale `running` rows as `error`, so the UI
|
|
185
188
|
never shows a permanently running task.
|
|
186
189
|
|
|
190
|
+
History is bounded by retention: `settings.json` carries `history.retentionDays` and
|
|
191
|
+
`history.maxRecords` (defaults 30 / 5000, `0` disables). Cleanup runs at most once a
|
|
192
|
+
day on plugin start (`core/retention.ts`), prunes only finished rows via
|
|
193
|
+
`pruneHistory` in `db/history-repo.ts`, then `PRAGMA incremental_vacuum` frees space.
|
|
194
|
+
Aggregates in `metrics` are never pruned. Period analytics (per-day buckets, success
|
|
195
|
+
rate, tokens, cost, matrix/model breakdowns) are computed by `core/analytics.ts` and
|
|
196
|
+
exposed as `get_analytics` / `GET /api/analytics`; the dashboard renders a 14-day
|
|
197
|
+
block and `GET /api/history/export` serves CSV/JSON.
|
|
198
|
+
|
|
187
199
|
## Chains, retries and DAG
|
|
188
200
|
|
|
189
201
|
All three are evaluated by the recorder after a run finishes:
|
package/docs/FEATURES.md
CHANGED
|
@@ -204,7 +204,12 @@ pre/post-flight results, next chained task, workspace and tool restrictions. Sta
|
|
|
204
204
|
### Metrics
|
|
205
205
|
|
|
206
206
|
Per-task counters and totals: runs, successes, errors, tokens, cost. Available through
|
|
207
|
-
`get_history`, the RPC layer and the dashboard header.
|
|
207
|
+
`get_history`, the RPC layer and the dashboard header. A 14-day analytics slice —
|
|
208
|
+
per-day buckets (UTC), success rate, token-based cost estimate, top tasks by cost,
|
|
209
|
+
matrix and model breakdowns — is available through `get_analytics` /
|
|
210
|
+
`GET /api/analytics` and the dashboard's «📊 Аналитика за период» block. History is
|
|
211
|
+
pruned automatically (age and size limits, see Settings) and can be exported as
|
|
212
|
+
CSV/JSON (`GET /api/history/export`).
|
|
208
213
|
|
|
209
214
|
### Logs
|
|
210
215
|
|
|
@@ -219,8 +224,10 @@ fan-out and estimated time. Nothing is executed and nothing is created.
|
|
|
219
224
|
### Dashboard
|
|
220
225
|
|
|
221
226
|
A local web dashboard shows tasks, matrix tabs, per-workspace summaries, DAG markers,
|
|
222
|
-
metrics
|
|
223
|
-
|
|
227
|
+
metrics, a 14-day analytics block (KPIs, daily bar chart, top tasks by cost, matrices),
|
|
228
|
+
recent runs and CSV/JSON history export. It binds to localhost and has no authentication
|
|
229
|
+
— do not expose it. `GET /api/health` reports plugin version, scheduler backend, queue
|
|
230
|
+
depth and database status for external monitoring.
|
|
224
231
|
|
|
225
232
|
## Management
|
|
226
233
|
|
|
@@ -248,8 +255,13 @@ the timeline never lies. Orphaned matrix clones are cleaned up at startup as wel
|
|
|
248
255
|
|
|
249
256
|
### Settings
|
|
250
257
|
|
|
251
|
-
Global defaults (timeout, concurrency, notifications) live in
|
|
252
|
-
are editable from the GUI/RPC layer.
|
|
258
|
+
Global defaults (timeout, concurrency, notifications, history retention) live in
|
|
259
|
+
`settings.json` and are editable from the GUI/RPC layer. History retention keeps the
|
|
260
|
+
raw run log bounded: `history.retentionDays` (default 30) and `history.maxRecords`
|
|
261
|
+
(default 5000); `0` disables the respective limit. Cleanup runs at most once a day on
|
|
262
|
+
plugin start, records `lastCleanupAt` / `lastCleanupDeleted`, and is also available as
|
|
263
|
+
the `cleanup_history` RPC and the GUI's «Очистить сейчас» button. Aggregates in
|
|
264
|
+
`metrics.json` are not affected by retention.
|
|
253
265
|
|
|
254
266
|
## Agent interface
|
|
255
267
|
|