agent-steward 0.0.1 → 0.0.2
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 +376 -0
- package/CROSS_PLATFORM.md +149 -0
- package/README.md +306 -15
- package/ROADMAP-STRATEGY.md +147 -0
- package/ROADMAP.md +1069 -0
- package/dist/core/analytics.d.ts +132 -0
- package/dist/core/analytics.d.ts.map +1 -0
- package/dist/core/analytics.js +290 -0
- package/dist/core/audit.d.ts +96 -0
- package/dist/core/audit.d.ts.map +1 -0
- package/dist/core/audit.js +297 -0
- package/dist/core/cron-to-schtasks.d.ts +20 -0
- package/dist/core/cron-to-schtasks.d.ts.map +1 -0
- package/dist/core/cron-to-schtasks.js +250 -0
- package/dist/core/dry-run.d.ts +102 -0
- package/dist/core/dry-run.d.ts.map +1 -0
- package/dist/core/dry-run.js +447 -0
- package/dist/core/file-watcher.d.ts +31 -0
- package/dist/core/file-watcher.d.ts.map +1 -0
- package/dist/core/file-watcher.js +186 -0
- package/dist/core/git-trigger.d.ts +82 -0
- package/dist/core/git-trigger.d.ts.map +1 -0
- package/dist/core/git-trigger.js +312 -0
- package/dist/core/glob.d.ts +38 -0
- package/dist/core/glob.d.ts.map +1 -0
- package/dist/core/glob.js +233 -0
- package/dist/core/local-ai.d.ts +52 -0
- package/dist/core/local-ai.d.ts.map +1 -0
- package/dist/core/local-ai.js +119 -0
- package/dist/core/lock.d.ts +57 -0
- package/dist/core/lock.d.ts.map +1 -0
- package/dist/core/lock.js +195 -0
- package/dist/core/matrix.d.ts +167 -0
- package/dist/core/matrix.d.ts.map +1 -0
- package/dist/core/matrix.js +724 -0
- package/dist/core/native-notify.d.ts +36 -0
- package/dist/core/native-notify.d.ts.map +1 -0
- package/dist/core/native-notify.js +113 -0
- package/dist/core/one-shot.d.ts +68 -0
- package/dist/core/one-shot.d.ts.map +1 -0
- package/dist/core/one-shot.js +139 -0
- package/dist/core/otel.d.ts +4 -0
- package/dist/core/otel.d.ts.map +1 -0
- package/dist/core/otel.js +98 -0
- package/dist/core/permissions.d.ts +69 -0
- package/dist/core/permissions.d.ts.map +1 -0
- package/dist/core/permissions.js +143 -0
- package/dist/core/prometheus.d.ts +23 -0
- package/dist/core/prometheus.d.ts.map +1 -0
- package/dist/core/prometheus.js +146 -0
- package/dist/core/ps-wrapper.d.ts +73 -0
- package/dist/core/ps-wrapper.d.ts.map +1 -0
- package/dist/core/ps-wrapper.js +1071 -0
- package/dist/core/record-history.d.ts +25 -0
- package/dist/core/record-history.d.ts.map +1 -0
- package/dist/core/record-history.js +471 -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/core/savings.d.ts +70 -0
- package/dist/core/savings.d.ts.map +1 -0
- package/dist/core/savings.js +87 -0
- package/dist/core/schedule-gate.d.ts +2 -0
- package/dist/core/schedule-gate.d.ts.map +1 -0
- package/dist/core/schedule-gate.js +211 -0
- package/dist/core/schedule-v2.d.ts +116 -0
- package/dist/core/schedule-v2.d.ts.map +1 -0
- package/dist/core/schedule-v2.js +586 -0
- package/dist/core/scheduler/index.d.ts +32 -0
- package/dist/core/scheduler/index.d.ts.map +1 -0
- package/dist/core/scheduler/index.js +63 -0
- package/dist/core/scheduler/linux.d.ts +44 -0
- package/dist/core/scheduler/linux.d.ts.map +1 -0
- package/dist/core/scheduler/linux.js +225 -0
- package/dist/core/scheduler/logs.d.ts +11 -0
- package/dist/core/scheduler/logs.d.ts.map +1 -0
- package/dist/core/scheduler/logs.js +34 -0
- package/dist/core/scheduler/mac.d.ts +40 -0
- package/dist/core/scheduler/mac.d.ts.map +1 -0
- package/dist/core/scheduler/mac.js +207 -0
- package/dist/core/scheduler/posix.d.ts +40 -0
- package/dist/core/scheduler/posix.d.ts.map +1 -0
- package/dist/core/scheduler/posix.js +89 -0
- package/dist/core/scheduler/registry.d.ts +41 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -0
- package/dist/core/scheduler/registry.js +57 -0
- package/dist/core/scheduler/types.d.ts +86 -0
- package/dist/core/scheduler/types.d.ts.map +1 -0
- package/dist/core/scheduler/types.js +1 -0
- package/dist/core/scheduler/windows.d.ts +99 -0
- package/dist/core/scheduler/windows.d.ts.map +1 -0
- package/dist/core/scheduler/windows.js +596 -0
- package/dist/core/secrets.d.ts +66 -0
- package/dist/core/secrets.d.ts.map +1 -0
- package/dist/core/secrets.js +433 -0
- package/dist/core/self-analysis.d.ts +117 -0
- package/dist/core/self-analysis.d.ts.map +1 -0
- package/dist/core/self-analysis.js +539 -0
- package/dist/core/self-analysis.test.d.ts +2 -0
- package/dist/core/self-analysis.test.d.ts.map +1 -0
- package/dist/core/self-analysis.test.js +219 -0
- package/dist/core/session.d.ts +42 -0
- package/dist/core/session.d.ts.map +1 -0
- package/dist/core/session.js +134 -0
- package/dist/core/shutdown.d.ts +26 -0
- package/dist/core/shutdown.d.ts.map +1 -0
- package/dist/core/shutdown.js +49 -0
- package/dist/core/structured-log.d.ts +84 -0
- package/dist/core/structured-log.d.ts.map +1 -0
- package/dist/core/structured-log.js +146 -0
- package/dist/core/summary.d.ts +69 -0
- package/dist/core/summary.d.ts.map +1 -0
- package/dist/core/summary.js +250 -0
- package/dist/core/telegram.d.ts +55 -0
- package/dist/core/telegram.d.ts.map +1 -0
- package/dist/core/telegram.js +344 -0
- package/dist/core/triage-chain.d.ts +40 -0
- package/dist/core/triage-chain.d.ts.map +1 -0
- package/dist/core/triage-chain.js +80 -0
- package/dist/core/triage-compare.d.ts +68 -0
- package/dist/core/triage-compare.d.ts.map +1 -0
- package/dist/core/triage-compare.js +184 -0
- package/dist/core/triage-rules.d.ts +23 -0
- package/dist/core/triage-rules.d.ts.map +1 -0
- package/dist/core/triage-rules.js +196 -0
- package/dist/core/triage-shadow.d.ts +91 -0
- package/dist/core/triage-shadow.d.ts.map +1 -0
- package/dist/core/triage-shadow.js +160 -0
- package/dist/core/triage-worker.d.ts +55 -0
- package/dist/core/triage-worker.d.ts.map +1 -0
- package/dist/core/triage-worker.js +314 -0
- package/dist/core/triage.d.ts +76 -0
- package/dist/core/triage.d.ts.map +1 -0
- package/dist/core/triage.js +271 -0
- package/dist/core/watch-paths.d.ts +6 -0
- package/dist/core/watch-paths.d.ts.map +1 -0
- package/dist/core/watch-paths.js +62 -0
- package/dist/core/wrappers/bash.d.ts +95 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -0
- package/dist/core/wrappers/bash.js +413 -0
- package/dist/db/git-state-repo.d.ts +16 -0
- package/dist/db/git-state-repo.d.ts.map +1 -0
- package/dist/db/git-state-repo.js +38 -0
- package/dist/db/history-repo.d.ts +110 -0
- package/dist/db/history-repo.d.ts.map +1 -0
- package/dist/db/history-repo.js +300 -0
- package/dist/db/index.d.ts +47 -0
- package/dist/db/index.d.ts.map +1 -0
- package/dist/db/index.js +120 -0
- package/dist/db/metrics-repo.d.ts +46 -0
- package/dist/db/metrics-repo.d.ts.map +1 -0
- package/dist/db/metrics-repo.js +103 -0
- package/dist/db/migrate.d.ts +24 -0
- package/dist/db/migrate.d.ts.map +1 -0
- package/dist/db/migrate.js +244 -0
- package/dist/db/recovery.d.ts +11 -0
- package/dist/db/recovery.d.ts.map +1 -0
- package/dist/db/recovery.js +38 -0
- package/dist/db/schema.d.ts +24 -0
- package/dist/db/schema.d.ts.map +1 -0
- package/dist/db/schema.js +170 -0
- package/dist/db/settings-repo.d.ts +8 -0
- package/dist/db/settings-repo.d.ts.map +1 -0
- package/dist/db/settings-repo.js +27 -0
- package/dist/db/tasks-repo.d.ts +26 -0
- package/dist/db/tasks-repo.d.ts.map +1 -0
- package/dist/db/tasks-repo.js +120 -0
- package/dist/db/templates-repo.d.ts +17 -0
- package/dist/db/templates-repo.d.ts.map +1 -0
- package/dist/db/templates-repo.js +57 -0
- package/dist/gui-experimental.cjs +1 -0
- package/dist/history.d.ts +60 -0
- package/dist/history.d.ts.map +1 -0
- package/dist/history.js +70 -0
- package/dist/i18n.d.ts +75 -0
- package/dist/i18n.d.ts.map +1 -0
- package/dist/i18n.js +357 -0
- package/dist/index.d.ts +858 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5179 -0
- package/dist/integrations.d.ts +72 -0
- package/dist/integrations.d.ts.map +1 -0
- package/dist/integrations.js +233 -0
- package/dist/notifications.d.ts +199 -0
- package/dist/notifications.d.ts.map +1 -0
- package/dist/notifications.js +967 -0
- package/dist/profiles.d.ts +60 -0
- package/dist/profiles.d.ts.map +1 -0
- package/dist/profiles.js +227 -0
- package/dist/rpc.d.ts +3806 -0
- package/dist/rpc.d.ts.map +1 -0
- package/dist/rpc.js +1507 -0
- package/dist/schtasks.d.ts +32 -0
- package/dist/schtasks.d.ts.map +1 -0
- package/dist/schtasks.js +45 -0
- package/dist/server.d.ts +128 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +2413 -0
- package/dist/settings.d.ts +389 -0
- package/dist/settings.d.ts.map +1 -0
- package/dist/settings.js +770 -0
- package/dist/shared/jobs-view.d.ts +59 -0
- package/dist/shared/jobs-view.d.ts.map +1 -0
- package/dist/shared/jobs-view.js +146 -0
- package/dist/skill.d.ts +15 -0
- package/dist/skill.d.ts.map +1 -0
- package/dist/skill.js +93 -0
- package/dist/task-transfer.d.ts +252 -0
- package/dist/task-transfer.d.ts.map +1 -0
- package/dist/task-transfer.js +628 -0
- package/dist/templates.d.ts +57 -0
- package/dist/templates.d.ts.map +1 -0
- package/dist/templates.js +16 -0
- package/dist/types.d.ts +96 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +130 -0
- package/dist/version.d.ts +8 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +27 -0
- package/dist/workspaces.d.ts +113 -0
- package/dist/workspaces.d.ts.map +1 -0
- package/dist/workspaces.js +393 -0
- package/docs/ARCHITECTURE.md +457 -0
- package/docs/COMPATIBILITY.md +233 -0
- package/docs/CONCEPT.md +230 -0
- package/docs/CROSS_PLATFORM.ru.md +150 -0
- package/docs/CROSS_PLATFORM.zh.md +146 -0
- package/docs/FAQ.md +52 -0
- package/docs/FAQ.ru.md +53 -0
- package/docs/FAQ.zh.md +43 -0
- package/docs/FEATURES.md +698 -0
- package/docs/FEATURES.zh.md +655 -0
- package/docs/LOCAL-AI.md +300 -0
- package/docs/MIGRATION.md +355 -0
- package/docs/README.ru.md +268 -0
- package/docs/README.zh.md +305 -0
- package/docs/SAVINGS.md +61 -0
- package/docs/SAVINGS.ru.md +60 -0
- package/docs/SAVINGS.zh.md +52 -0
- package/docs/V1-V2-COMPATIBILITY-PLAN.md +366 -0
- package/docs/ZH-LOCALE-PLAN.md +324 -0
- package/docs/dashboard.png +0 -0
- package/docs/spikes/local-model-structured-output.md +81 -0
- package/docs/spikes/ollama-qwen3-4b-smoke.json +28 -0
- package/docs/spikes/ollama-qwen3-4b.json +163 -0
- package/gui-experimental.cjs +9 -0
- package/index.js +1 -0
- package/locales/en.json +780 -0
- package/locales/ru.json +780 -0
- package/locales/zh.json +780 -0
- package/package.json +133 -13
- package/scripts/bench-local.mjs +321 -0
- package/scripts/check-zh-locale.mjs +218 -0
- package/scripts/demo-dashboard.mjs +209 -0
- package/scripts/run-tests.mjs +236 -0
- package/scripts/spike-local-structured.mjs +182 -0
- package/scripts/test-locale.mjs +45 -0
- package/skills/scheduled-job-best-practices/SKILL.md +158 -0
- package/skills/scheduled-job-best-practices/references/recipes.md +163 -0
- package/src/core/analytics.ts +424 -0
- package/src/core/audit.ts +418 -0
- package/src/core/cron-to-schtasks.ts +288 -0
- package/src/core/dry-run.ts +601 -0
- package/src/core/file-watcher.ts +245 -0
- package/src/core/git-trigger.ts +391 -0
- package/src/core/glob.ts +226 -0
- package/src/core/local-ai.ts +173 -0
- package/src/core/lock.ts +219 -0
- package/src/core/matrix.ts +947 -0
- package/src/core/native-notify.ts +157 -0
- package/src/core/one-shot.ts +189 -0
- package/src/core/otel.ts +128 -0
- package/src/core/permissions.ts +200 -0
- package/src/core/prometheus.ts +215 -0
- package/src/core/ps-wrapper.ts +1140 -0
- package/src/core/record-history.ts +615 -0
- package/src/core/retention.ts +141 -0
- package/src/core/savings.ts +150 -0
- package/src/core/schedule-gate.ts +253 -0
- package/src/core/schedule-v2.ts +668 -0
- package/src/core/scheduler/index.ts +82 -0
- package/src/core/scheduler/linux.ts +257 -0
- package/src/core/scheduler/logs.ts +37 -0
- package/src/core/scheduler/mac.ts +270 -0
- package/src/core/scheduler/posix.ts +114 -0
- package/src/core/scheduler/registry.ts +99 -0
- package/src/core/scheduler/types.ts +90 -0
- package/src/core/scheduler/windows.ts +711 -0
- package/src/core/secrets.ts +503 -0
- package/src/core/self-analysis.ts +744 -0
- package/src/core/session.ts +150 -0
- package/src/core/shutdown.ts +69 -0
- package/src/core/structured-log.ts +214 -0
- package/src/core/summary.ts +318 -0
- package/src/core/telegram.ts +436 -0
- package/src/core/triage-chain.ts +125 -0
- package/src/core/triage-compare.ts +277 -0
- package/src/core/triage-rules.ts +238 -0
- package/src/core/triage-shadow.ts +240 -0
- package/src/core/triage-worker.ts +344 -0
- package/src/core/triage.ts +366 -0
- package/src/core/watch-paths.ts +70 -0
- package/src/core/wrappers/bash.ts +532 -0
- package/src/db/git-state-repo.ts +62 -0
- package/src/db/history-repo.ts +492 -0
- package/src/db/index.ts +166 -0
- package/src/db/metrics-repo.ts +170 -0
- package/src/db/migrate.ts +328 -0
- package/src/db/recovery.ts +46 -0
- package/src/db/schema.ts +188 -0
- package/src/db/settings-repo.ts +31 -0
- package/src/db/tasks-repo.ts +162 -0
- package/src/db/templates-repo.ts +77 -0
- package/src/gui.tsx +5222 -0
- package/src/history.ts +128 -0
- package/src/i18n.ts +413 -0
- package/src/index.ts +6605 -0
- package/src/integrations.ts +297 -0
- package/src/notifications.ts +1346 -0
- package/src/profiles.ts +254 -0
- package/src/rpc.ts +1609 -0
- package/src/schtasks.ts +75 -0
- package/src/server.ts +2662 -0
- package/src/settings.ts +1369 -0
- package/src/shared/jobs-view.ts +188 -0
- package/src/skill.ts +113 -0
- package/src/task-transfer.ts +944 -0
- package/src/templates.ts +67 -0
- package/src/tui-v1.tsx +341 -0
- package/src/tui.tsx +329 -0
- package/src/types.ts +191 -0
- package/src/version.ts +27 -0
- package/src/workspaces.ts +487 -0
package/src/history.ts
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { PLUGIN_DIR } from "./types.js";
|
|
3
|
+
import {
|
|
4
|
+
getHistory,
|
|
5
|
+
insertHistory,
|
|
6
|
+
recordRun,
|
|
7
|
+
} from "./db/history-repo.js";
|
|
8
|
+
import { getTotals, incrementGlobalMetrics } from "./db/metrics-repo.js";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Публичный фасад истории/метрик (Спринт 12).
|
|
12
|
+
*
|
|
13
|
+
* Раньше модуль читал history.json и metrics.json. Теперь источник данных —
|
|
14
|
+
* SQLite, но экспортируемые типы и функции сохранены: index.ts, server.ts и
|
|
15
|
+
* внешние потребители (GUI/агент) не заметят разницы.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** @deprecated Оставлено для обратной совместимости импортов. */
|
|
19
|
+
export const HISTORY_FILE = path.join(PLUGIN_DIR, "history.json");
|
|
20
|
+
/** @deprecated Оставлено для обратной совместимости импортов. */
|
|
21
|
+
export const METRICS_FILE = path.join(PLUGIN_DIR, "metrics.json");
|
|
22
|
+
|
|
23
|
+
export type TaskStatus = "success" | "error" | "timeout" | "partial";
|
|
24
|
+
|
|
25
|
+
export interface HistoryRecord {
|
|
26
|
+
taskName: string;
|
|
27
|
+
status: TaskStatus;
|
|
28
|
+
startedAt: string;
|
|
29
|
+
finishedAt: string;
|
|
30
|
+
durationMs: number;
|
|
31
|
+
error?: string | null;
|
|
32
|
+
/** Имя задачи, запущенной по цепочке после этого запуска (если была). */
|
|
33
|
+
nextTask?: string | null;
|
|
34
|
+
/** Сколько токенов потратил запуск (если удалось распарсить лог). */
|
|
35
|
+
tokens?: number;
|
|
36
|
+
/** Стоимость запуска в USD (если в логе была информация о цене). */
|
|
37
|
+
costUsd?: number;
|
|
38
|
+
/** LLM-модель, использованная в запуске (если задана в задаче). */
|
|
39
|
+
model?: string;
|
|
40
|
+
/** Итог pre-flight хука: success / error / skipped (хук не задан). */
|
|
41
|
+
preFlightStatus?: "success" | "error" | "skipped";
|
|
42
|
+
/** Итог post-flight хука: success / error / skipped (хук не задан). */
|
|
43
|
+
postFlightStatus?: "success" | "error" | "skipped";
|
|
44
|
+
/** Ограничения инструментов, действовавшие на момент запуска. */
|
|
45
|
+
allowedTools?: string[] | null;
|
|
46
|
+
deniedTools?: string[] | null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface Metrics {
|
|
50
|
+
total: number;
|
|
51
|
+
success: number;
|
|
52
|
+
error: number;
|
|
53
|
+
/** Частичные выполнения (post-flight/quality gate не прошёл). */
|
|
54
|
+
partial: number;
|
|
55
|
+
tokens?: number;
|
|
56
|
+
costUsd?: number;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Оставляет по одной самой свежей записи на задачу.
|
|
61
|
+
* `records` должны быть отсортированы от новых к старым (как loadHistory).
|
|
62
|
+
*/
|
|
63
|
+
export function latestHistoryByTask(
|
|
64
|
+
records: readonly HistoryRecord[]
|
|
65
|
+
): Map<string, HistoryRecord> {
|
|
66
|
+
const latest = new Map<string, HistoryRecord>();
|
|
67
|
+
for (const record of records) {
|
|
68
|
+
const key = record.taskName.toLowerCase();
|
|
69
|
+
if (!latest.has(key)) latest.set(key, record);
|
|
70
|
+
}
|
|
71
|
+
return latest;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Читает историю запусков из БД (от новых к старым; фильтры применяются в SQLite). */
|
|
75
|
+
export async function loadHistory(
|
|
76
|
+
taskName?: string | null,
|
|
77
|
+
limit = 200,
|
|
78
|
+
status?: string | null
|
|
79
|
+
): Promise<HistoryRecord[]> {
|
|
80
|
+
return getHistory(taskName, limit, status).map((record) => ({
|
|
81
|
+
taskName: record.taskName,
|
|
82
|
+
// Незавершённые записи до recovery показываем как error для GUI.
|
|
83
|
+
status: (record.status === "running" ? "error" : record.status) as TaskStatus,
|
|
84
|
+
startedAt: record.startedAt,
|
|
85
|
+
finishedAt: record.finishedAt ?? "",
|
|
86
|
+
durationMs: record.durationMs ?? 0,
|
|
87
|
+
error: record.error ?? null,
|
|
88
|
+
nextTask: record.nextTask ?? null,
|
|
89
|
+
...(record.tokens !== undefined ? { tokens: record.tokens } : {}),
|
|
90
|
+
...(record.costUsd !== undefined ? { costUsd: record.costUsd } : {}),
|
|
91
|
+
...(record.model !== undefined ? { model: record.model } : {}),
|
|
92
|
+
...(record.preFlightStatus !== undefined
|
|
93
|
+
? { preFlightStatus: record.preFlightStatus }
|
|
94
|
+
: {}),
|
|
95
|
+
...(record.postFlightStatus !== undefined
|
|
96
|
+
? { postFlightStatus: record.postFlightStatus }
|
|
97
|
+
: {}),
|
|
98
|
+
...(record.allowedTools ? { allowedTools: record.allowedTools } : {}),
|
|
99
|
+
...(record.deniedTools ? { deniedTools: record.deniedTools } : {}),
|
|
100
|
+
}));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Добавляет запись истории (без изменения метрик — совместимость). */
|
|
104
|
+
export async function appendHistory(record: HistoryRecord): Promise<void> {
|
|
105
|
+
insertHistory(record);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Читает суммарные метрики из БД. */
|
|
109
|
+
export async function loadMetrics(): Promise<Metrics> {
|
|
110
|
+
return getTotals();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Старый appendMetric(status): глобальный счётчик без привязки к задаче. */
|
|
114
|
+
export async function appendMetric(status: TaskStatus): Promise<void> {
|
|
115
|
+
incrementGlobalMetrics(status);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Записывает завершённый запуск: история + метрики одной транзакцией. */
|
|
119
|
+
export async function recordTaskRun(
|
|
120
|
+
taskName: string,
|
|
121
|
+
status: TaskStatus,
|
|
122
|
+
durationMs: number,
|
|
123
|
+
error?: string | null
|
|
124
|
+
): Promise<void> {
|
|
125
|
+
const finishedAt = new Date().toISOString();
|
|
126
|
+
const startedAt = new Date(Date.now() - durationMs).toISOString();
|
|
127
|
+
recordRun(taskName, status, startedAt, durationMs, error, null, undefined, undefined, undefined, undefined, undefined, finishedAt);
|
|
128
|
+
}
|
package/src/i18n.ts
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* i18n-фундамент (Спринт 28).
|
|
3
|
+
*
|
|
4
|
+
* Каталоги строк живут в `<корень пакета>/locales/<locale>.json` — плоские
|
|
5
|
+
* ключи вида `"server.notFound"`. Загрузчик читает их синхронно при первом
|
|
6
|
+
* обращении и кэширует: файлы маленькие, а горячий путь — `t()` в рендере.
|
|
7
|
+
*
|
|
8
|
+
* Поддерживается ICU-подмножество без зависимостей:
|
|
9
|
+
* - `{name}` — подстановка параметра;
|
|
10
|
+
* - `{count, plural, one {…} few {…} many {…} other {…}}` — плюрализация
|
|
11
|
+
* через встроенный `Intl.PluralRules`; `#` внутри ветки — число.
|
|
12
|
+
*
|
|
13
|
+
* Русский — локаль по умолчанию (`DEFAULT_LOCALE`). Если ключа нет в текущей
|
|
14
|
+
* локали, берётся русский вариант; если нет и там — возвращается сам ключ,
|
|
15
|
+
* чтобы пропажа была видна, а не превращалась в пустую строку.
|
|
16
|
+
*
|
|
17
|
+
* Локаль процесса меняется через `setLocale()` — без перезапуска плагина.
|
|
18
|
+
*/
|
|
19
|
+
import fs from "node:fs";
|
|
20
|
+
import path from "node:path";
|
|
21
|
+
import { fileURLToPath } from "node:url";
|
|
22
|
+
|
|
23
|
+
export type Locale = "ru" | "en" | "zh";
|
|
24
|
+
|
|
25
|
+
/** Порядок важен для UI: первым идёт локаль по умолчанию. */
|
|
26
|
+
export const SUPPORTED_LOCALES: readonly Locale[] = ["ru", "en", "zh"];
|
|
27
|
+
|
|
28
|
+
/** Русский остаётся локалью по умолчанию (см. ROADMAP, спринт 28). */
|
|
29
|
+
export const DEFAULT_LOCALE: Locale = "ru";
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Режим локали (T7): `auto` — следовать за языком интерфейса OpenCode,
|
|
33
|
+
* конкретное значение — всегда использовать эту локаль.
|
|
34
|
+
*/
|
|
35
|
+
export type LocaleMode = "auto" | Locale;
|
|
36
|
+
|
|
37
|
+
/** Значение режима «следовать за OpenCode». */
|
|
38
|
+
export const LOCALE_AUTO = "auto" as const;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Каталог модуля: `src/` при запуске из исходников, `dist/` из сборки.
|
|
42
|
+
*
|
|
43
|
+
* В GUI-бандле (renderer Electron/webview) нет ни `import.meta.url` с реальным
|
|
44
|
+
* путём к пакету, ни `process`; любой бросок на этапе загрузки модуля валит
|
|
45
|
+
* весь плагин, поэтому путь вычисляется лениво и молча.
|
|
46
|
+
*/
|
|
47
|
+
function moduleDir(): string | null {
|
|
48
|
+
try {
|
|
49
|
+
return path.dirname(fileURLToPath(import.meta.url));
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Каталоги, где может лежать `locales/` (оба варианта дают корень пакета). */
|
|
56
|
+
function candidateCatalogDirs(): string[] {
|
|
57
|
+
const dir = moduleDir();
|
|
58
|
+
if (!dir) return [];
|
|
59
|
+
return [path.resolve(dir, "../locales"), path.resolve(dir, "locales")];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const catalogs = new Map<Locale, Record<string, string>>();
|
|
63
|
+
const pluralRules = new Map<Locale, Intl.PluralRules>();
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Локаль запуска: `OPENCODE_SCHEDULER_LOCALE=en` позволяет прогнать набор
|
|
67
|
+
* тестов на английском без правки настроек. Не задана — русский.
|
|
68
|
+
*
|
|
69
|
+
* `process` отсутствует в GUI-бандле (renderer), поэтому обращение к нему
|
|
70
|
+
* защищено: иначе `ReferenceError: process is not defined` ломает загрузку
|
|
71
|
+
* всего плагина ещё до регистрации панели.
|
|
72
|
+
*/
|
|
73
|
+
function envLocale(): string | undefined {
|
|
74
|
+
try {
|
|
75
|
+
return typeof process !== "undefined" && process.env
|
|
76
|
+
? process.env.OPENCODE_SCHEDULER_LOCALE
|
|
77
|
+
: undefined;
|
|
78
|
+
} catch {
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const INITIAL_LOCALE: Locale = normalizeLocale(envLocale());
|
|
84
|
+
|
|
85
|
+
let currentLocale: Locale = INITIAL_LOCALE;
|
|
86
|
+
|
|
87
|
+
/** true, если значение — поддерживаемая локаль. */
|
|
88
|
+
export function isLocale(value: unknown): value is Locale {
|
|
89
|
+
return (
|
|
90
|
+
typeof value === "string" &&
|
|
91
|
+
(SUPPORTED_LOCALES as readonly string[]).includes(value)
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** true, если значение — допустимый режим локали (включая `auto`). */
|
|
96
|
+
export function isLocaleMode(value: unknown): value is LocaleMode {
|
|
97
|
+
return value === LOCALE_AUTO || isLocale(value);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Маппинг BCP 47 → поддерживаемая локаль: `zh-CN`/`zh-Hans` → `zh`,
|
|
102
|
+
* `en-GB` → `en`, `ru-RU` → `ru`; неизвестное значение → `fallback`.
|
|
103
|
+
* Регистр и разделитель (`-` или `_`) не важны.
|
|
104
|
+
*/
|
|
105
|
+
export function mapAppLocale(
|
|
106
|
+
value: unknown,
|
|
107
|
+
fallback: Locale = DEFAULT_LOCALE
|
|
108
|
+
): Locale {
|
|
109
|
+
if (typeof value !== "string") return fallback;
|
|
110
|
+
const base = value.trim().toLowerCase().split(/[-_]/)[0];
|
|
111
|
+
return isLocale(base) ? base : fallback;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Приводит произвольное значение к поддерживаемой локали (с учётом BCP 47). */
|
|
115
|
+
export function normalizeLocale(
|
|
116
|
+
value: unknown,
|
|
117
|
+
fallback: Locale = DEFAULT_LOCALE
|
|
118
|
+
): Locale {
|
|
119
|
+
return mapAppLocale(value, fallback);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Приводит значение к режиму локали: `auto` или поддерживаемая локаль. */
|
|
123
|
+
export function normalizeLocaleMode(
|
|
124
|
+
value: unknown,
|
|
125
|
+
fallback: LocaleMode = DEFAULT_LOCALE
|
|
126
|
+
): LocaleMode {
|
|
127
|
+
if (value === LOCALE_AUTO) return LOCALE_AUTO;
|
|
128
|
+
if (typeof value === "string") {
|
|
129
|
+
const base = value.trim().toLowerCase().split(/[-_]/)[0];
|
|
130
|
+
if (isLocale(base)) return base;
|
|
131
|
+
}
|
|
132
|
+
return fallback;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Разрешает режим в конкретную локаль. Серверный процесс языка OpenCode не
|
|
137
|
+
* видит, поэтому при `auto` берётся последняя известная локаль интерфейса
|
|
138
|
+
* (`uiLocale`, её присылает GUI), иначе — локаль по умолчанию.
|
|
139
|
+
*/
|
|
140
|
+
export function resolveLocale(mode: LocaleMode, lastKnown?: Locale): Locale {
|
|
141
|
+
if (mode !== LOCALE_AUTO) return mode;
|
|
142
|
+
return isLocale(lastKnown) ? lastKnown : DEFAULT_LOCALE;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Текущая локаль процесса. */
|
|
146
|
+
export function getLocale(): Locale {
|
|
147
|
+
return currentLocale;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Переключает локаль процесса. Возвращает фактическую локаль (невалидное
|
|
152
|
+
* значение откатывается к локали по умолчанию).
|
|
153
|
+
*/
|
|
154
|
+
export function setLocale(locale: unknown): Locale {
|
|
155
|
+
currentLocale = normalizeLocale(locale, DEFAULT_LOCALE);
|
|
156
|
+
return currentLocale;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Путь к файлу каталога или null, если файла нет. */
|
|
160
|
+
export function catalogPath(locale: Locale): string | null {
|
|
161
|
+
for (const dir of candidateCatalogDirs()) {
|
|
162
|
+
const file = path.join(dir, `${locale}.json`);
|
|
163
|
+
try {
|
|
164
|
+
if (fs.statSync(file).isFile()) return file;
|
|
165
|
+
} catch {
|
|
166
|
+
// Нет файла — пробуем следующий каталог.
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Читает каталог с диска (с кэшем). Битый файл — пустой каталог. */
|
|
173
|
+
function readCatalog(locale: Locale): Record<string, string> {
|
|
174
|
+
const cached = catalogs.get(locale);
|
|
175
|
+
if (cached) return cached;
|
|
176
|
+
|
|
177
|
+
const file = catalogPath(locale);
|
|
178
|
+
const parsed: Record<string, string> = {};
|
|
179
|
+
if (file) {
|
|
180
|
+
try {
|
|
181
|
+
const raw = JSON.parse(fs.readFileSync(file, "utf8")) as unknown;
|
|
182
|
+
if (raw && typeof raw === "object" && !Array.isArray(raw)) {
|
|
183
|
+
for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
|
|
184
|
+
if (typeof value === "string" && value.length > 0) parsed[key] = value;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
} catch (err: any) {
|
|
188
|
+
console.error(
|
|
189
|
+
`[i18n] Не удалось прочитать ${file}: ${
|
|
190
|
+
err instanceof Error ? err.message : String(err)
|
|
191
|
+
}`
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
catalogs.set(locale, parsed);
|
|
197
|
+
return parsed;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Регистрирует каталог, встроенный в GUI-бандл.
|
|
202
|
+
*
|
|
203
|
+
* В webview OpenCode нет доступа к файлам пакета: `document.currentScript`
|
|
204
|
+
* указывает на ресурс приложения, поэтому `catalogPath()` не находит
|
|
205
|
+
* `locales/*.json` и `t()` возвращает сырые ключи. GUI импортирует JSON на
|
|
206
|
+
* этапе сборки и кладёт его сюда — файлы на диске больше не нужны.
|
|
207
|
+
*/
|
|
208
|
+
export function registerCatalog(
|
|
209
|
+
locale: Locale,
|
|
210
|
+
messages: Record<string, unknown>
|
|
211
|
+
): void {
|
|
212
|
+
const parsed: Record<string, string> = {};
|
|
213
|
+
for (const [key, value] of Object.entries(messages)) {
|
|
214
|
+
if (typeof value === "string" && value.length > 0) parsed[key] = value;
|
|
215
|
+
}
|
|
216
|
+
catalogs.set(locale, parsed);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Список ключей каталога (отсортированный). */
|
|
220
|
+
export function catalogKeys(locale: Locale = currentLocale): string[] {
|
|
221
|
+
return Object.keys(readCatalog(locale)).sort();
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** true, если ключ есть в каталоге указанной локали. */
|
|
225
|
+
export function hasKey(key: string, locale: Locale = currentLocale): boolean {
|
|
226
|
+
return Object.prototype.hasOwnProperty.call(readCatalog(locale), key);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Значение ключа в конкретной локали без fallback; undefined — ключа нет. */
|
|
230
|
+
export function messageIn(locale: Locale, key: string): string | undefined {
|
|
231
|
+
return readCatalog(locale)[key];
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Ключи, которых не хватает относительно русской локали.
|
|
236
|
+
* Пустой массив — каталог полный.
|
|
237
|
+
*/
|
|
238
|
+
export function missingKeys(locale: Locale): string[] {
|
|
239
|
+
const base = new Set(catalogKeys(DEFAULT_LOCALE));
|
|
240
|
+
return catalogKeys(locale).filter((key) => !base.has(key));
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Ключи, которые есть в русской локали, но отсутствуют в указанной. */
|
|
244
|
+
export function absentKeys(locale: Locale): string[] {
|
|
245
|
+
const target = new Set(catalogKeys(locale));
|
|
246
|
+
return catalogKeys(DEFAULT_LOCALE).filter((key) => !target.has(key));
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Сбрасывает кэш каталогов и локаль к локали запуска (для тестов). */
|
|
250
|
+
export function resetI18n(): void {
|
|
251
|
+
catalogs.clear();
|
|
252
|
+
pluralRules.clear();
|
|
253
|
+
currentLocale = INITIAL_LOCALE;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Категория плюрализации для числа (`one`/`few`/`many`/`other`). */
|
|
257
|
+
function pluralCategory(count: number, locale: Locale): string {
|
|
258
|
+
let rules = pluralRules.get(locale);
|
|
259
|
+
if (!rules) {
|
|
260
|
+
rules = new Intl.PluralRules(locale);
|
|
261
|
+
pluralRules.set(locale, rules);
|
|
262
|
+
}
|
|
263
|
+
return rules.select(count);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Форматирует число для подстановки `#` в плюральной ветке. */
|
|
267
|
+
function formatCount(count: number, locale: Locale): string {
|
|
268
|
+
try {
|
|
269
|
+
return new Intl.NumberFormat(locale).format(count);
|
|
270
|
+
} catch {
|
|
271
|
+
return String(count);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** Индекс парной `}` для `{` на позиции `openIndex`; -1 — не закрыта. */
|
|
276
|
+
function findClosingBrace(text: string, openIndex: number): number {
|
|
277
|
+
let depth = 0;
|
|
278
|
+
for (let i = openIndex; i < text.length; i++) {
|
|
279
|
+
const ch = text[i];
|
|
280
|
+
if (ch === "{") depth++;
|
|
281
|
+
else if (ch === "}") {
|
|
282
|
+
depth--;
|
|
283
|
+
if (depth === 0) return i;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return -1;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Индекс первой запятой верхнего уровня (вне фигурных скобок); -1 — нет. */
|
|
290
|
+
function topLevelCommaIndex(body: string): number {
|
|
291
|
+
let depth = 0;
|
|
292
|
+
for (let i = 0; i < body.length; i++) {
|
|
293
|
+
const ch = body[i];
|
|
294
|
+
if (ch === "{") depth++;
|
|
295
|
+
else if (ch === "}") depth--;
|
|
296
|
+
else if (ch === "," && depth === 0) return i;
|
|
297
|
+
}
|
|
298
|
+
return -1;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Разбирает ветки plural: `one {…} few {…} many {…} other {…}`.
|
|
303
|
+
* Ветки разделены пробелами/запятыми, содержимое — в фигурных скобках.
|
|
304
|
+
*/
|
|
305
|
+
function parsePluralBranches(text: string): Record<string, string> {
|
|
306
|
+
const branches: Record<string, string> = {};
|
|
307
|
+
let i = 0;
|
|
308
|
+
while (i < text.length) {
|
|
309
|
+
while (i < text.length && /[\s,]/.test(text[i])) i++;
|
|
310
|
+
const keyStart = i;
|
|
311
|
+
while (i < text.length && text[i] !== "{") i++;
|
|
312
|
+
if (i >= text.length) break;
|
|
313
|
+
const key = text.slice(keyStart, i).trim();
|
|
314
|
+
const end = findClosingBrace(text, i);
|
|
315
|
+
if (end === -1) break;
|
|
316
|
+
if (key) branches[key] = text.slice(i + 1, end);
|
|
317
|
+
i = end + 1;
|
|
318
|
+
}
|
|
319
|
+
return branches;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Разворачивает шаблон: `{name}` и `{count, plural, …}`.
|
|
324
|
+
* `count` передаётся только внутри плюральной ветки — там `#` становится числом.
|
|
325
|
+
*/
|
|
326
|
+
function renderTemplate(
|
|
327
|
+
template: string,
|
|
328
|
+
locale: Locale,
|
|
329
|
+
params: Record<string, unknown>,
|
|
330
|
+
count?: number
|
|
331
|
+
): string {
|
|
332
|
+
let out = "";
|
|
333
|
+
let i = 0;
|
|
334
|
+
while (i < template.length) {
|
|
335
|
+
const ch = template[i];
|
|
336
|
+
if (ch === "#" && count !== undefined) {
|
|
337
|
+
out += formatCount(count, locale);
|
|
338
|
+
i++;
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
if (ch !== "{") {
|
|
342
|
+
out += ch;
|
|
343
|
+
i++;
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
const end = findClosingBrace(template, i);
|
|
347
|
+
if (end === -1) {
|
|
348
|
+
out += template.slice(i);
|
|
349
|
+
break;
|
|
350
|
+
}
|
|
351
|
+
out += renderExpression(template.slice(i + 1, end), locale, params);
|
|
352
|
+
i = end + 1;
|
|
353
|
+
}
|
|
354
|
+
return out;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Разворачивает одно выражение `{…}` (параметр или plural). */
|
|
358
|
+
function renderExpression(
|
|
359
|
+
body: string,
|
|
360
|
+
locale: Locale,
|
|
361
|
+
params: Record<string, unknown>
|
|
362
|
+
): string {
|
|
363
|
+
const comma = topLevelCommaIndex(body);
|
|
364
|
+
const name = (comma === -1 ? body : body.slice(0, comma)).trim();
|
|
365
|
+
const value = params[name];
|
|
366
|
+
|
|
367
|
+
if (comma === -1) {
|
|
368
|
+
// Нет параметра — оставляем плейсхолдер, чтобы пропажа была видна.
|
|
369
|
+
return value === undefined || value === null ? `{${body}}` : String(value);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const rest = body.slice(comma + 1).trim();
|
|
373
|
+
const typeMatch = /^([a-zA-Z]+)/.exec(rest);
|
|
374
|
+
const type = typeMatch ? typeMatch[1] : "";
|
|
375
|
+
|
|
376
|
+
if (type === "plural") {
|
|
377
|
+
const numeric = Number(value);
|
|
378
|
+
const count = Number.isFinite(numeric) ? numeric : 0;
|
|
379
|
+
const branches = parsePluralBranches(rest.slice(type.length));
|
|
380
|
+
const category = pluralCategory(count, locale);
|
|
381
|
+
const chosen = branches[category] ?? branches.other ?? "";
|
|
382
|
+
return renderTemplate(chosen, locale, params, count);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// Неизвестный тип аргумента — подставляем значение как есть.
|
|
386
|
+
return value === undefined || value === null ? `{${body}}` : String(value);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Параметры подстановки: `{name}` или `count` для плюрализации. */
|
|
390
|
+
export type TranslateParams = Record<string, unknown>;
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Переводит ключ. Отсутствующий ключ → русский вариант → сам ключ.
|
|
394
|
+
* Если сработал fallback, плюрализация тоже считается по русским правилам.
|
|
395
|
+
*/
|
|
396
|
+
export function t(key: string, params?: TranslateParams): string {
|
|
397
|
+
const locale = currentLocale;
|
|
398
|
+
let template = readCatalog(locale)[key];
|
|
399
|
+
let renderLocale = locale;
|
|
400
|
+
|
|
401
|
+
if (template === undefined && locale !== DEFAULT_LOCALE) {
|
|
402
|
+
template = readCatalog(DEFAULT_LOCALE)[key];
|
|
403
|
+
renderLocale = DEFAULT_LOCALE;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
if (template === undefined) return key;
|
|
407
|
+
return renderTemplate(template, renderLocale, params ?? {});
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** Все локали, у которых каталог реально найден на диске. */
|
|
411
|
+
export function availableLocales(): Locale[] {
|
|
412
|
+
return SUPPORTED_LOCALES.filter((locale) => catalogPath(locale) !== null);
|
|
413
|
+
}
|