agent-steward 0.0.2 → 0.0.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.
- package/CHANGELOG.md +25 -2
- package/CROSS_PLATFORM.md +11 -9
- package/README.md +9 -8
- package/ROADMAP-STRATEGY.md +93 -44
- package/ROADMAP.md +114 -999
- package/dist/core/cron-to-schtasks.d.ts +0 -8
- package/dist/core/cron-to-schtasks.d.ts.map +1 -1
- package/dist/core/cron-to-schtasks.js +11 -86
- package/dist/core/dry-run.js +1 -1
- package/dist/core/file-watcher.js +9 -9
- package/dist/core/git-trigger.js +4 -4
- package/dist/core/lock.js +2 -4
- package/dist/core/one-shot.d.ts +27 -5
- package/dist/core/one-shot.d.ts.map +1 -1
- package/dist/core/one-shot.js +53 -10
- package/dist/core/otel.js +2 -2
- package/dist/core/ps-wrapper.d.ts +1 -1
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +55 -35
- package/dist/core/record-history.js +22 -22
- package/dist/core/schedule-v2.d.ts +2 -2
- package/dist/core/schedule-v2.d.ts.map +1 -1
- package/dist/core/schedule-v2.js +7 -7
- package/dist/core/scheduler/at-fallback.d.ts +42 -0
- package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
- package/dist/core/scheduler/at-fallback.js +70 -0
- package/dist/core/scheduler/linux.d.ts +3 -1
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +43 -7
- package/dist/core/scheduler/mac.d.ts +14 -8
- package/dist/core/scheduler/mac.d.ts.map +1 -1
- package/dist/core/scheduler/mac.js +71 -22
- package/dist/core/scheduler/posix.d.ts.map +1 -1
- package/dist/core/scheduler/posix.js +12 -1
- package/dist/core/scheduler/registry.d.ts +2 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -1
- package/dist/core/scheduler/windows.d.ts +16 -3
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +249 -96
- package/dist/core/secrets.js +2 -2
- package/dist/core/self-analysis.js +55 -55
- package/dist/core/summary.js +1 -1
- package/dist/core/triage-chain.js +1 -1
- package/dist/core/triage-worker.js +2 -2
- package/dist/core/triage.js +1 -1
- package/dist/core/wrappers/bash.js +33 -33
- package/dist/db/index.d.ts +2 -0
- package/dist/db/index.d.ts.map +1 -1
- package/dist/db/index.js +9 -1
- package/dist/db/run-journal.d.ts +60 -0
- package/dist/db/run-journal.d.ts.map +1 -0
- package/dist/db/run-journal.js +143 -0
- package/dist/db/run-resume.d.ts +48 -0
- package/dist/db/run-resume.d.ts.map +1 -0
- package/dist/db/run-resume.js +137 -0
- package/dist/db/runs-repo.d.ts +120 -0
- package/dist/db/runs-repo.d.ts.map +1 -0
- package/dist/db/runs-repo.js +319 -0
- package/dist/db/schema.d.ts +16 -2
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +190 -35
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +66 -36
- package/dist/notifications.js +18 -18
- package/dist/profiles.d.ts +7 -3
- package/dist/profiles.d.ts.map +1 -1
- package/dist/profiles.js +85 -7
- package/dist/rpc.d.ts +109 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +89 -0
- package/dist/server.d.ts +2 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +20 -19
- package/dist/shared/jobs-view.d.ts.map +1 -1
- package/dist/skill.js +1 -1
- package/dist/task-transfer.d.ts +1 -1
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +14 -10
- package/dist/types.d.ts +20 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +37 -9
- package/dist/workspaces.js +1 -1
- package/docs/ARCHITECTURE.md +110 -8
- package/docs/COMPATIBILITY.md +10 -6
- package/docs/CONCEPT.md +15 -3
- package/docs/CROSS_PLATFORM.ru.md +11 -9
- package/docs/CROSS_PLATFORM.zh.md +11 -9
- package/docs/FAQ.md +2 -2
- package/docs/FAQ.ru.md +2 -2
- package/docs/FAQ.zh.md +2 -2
- package/docs/FEATURES.md +5 -4
- package/docs/FEATURES.zh.md +5 -4
- package/docs/MIGRATION.md +34 -26
- package/docs/README.ru.md +26 -7
- package/docs/README.zh.md +9 -8
- package/docs/V1-V2-COMPATIBILITY-PLAN.md +6 -6
- package/gui-experimental.cjs +8 -8
- package/index.js +1 -0
- package/locales/en.json +1 -0
- package/locales/ru.json +1 -0
- package/locales/zh.json +1 -0
- package/package.json +31 -10
- package/src/core/analytics.ts +2 -2
- package/src/core/audit.ts +17 -17
- package/src/core/cron-to-schtasks.ts +14 -93
- package/src/core/dry-run.ts +26 -26
- package/src/core/file-watcher.ts +17 -17
- package/src/core/git-trigger.ts +9 -9
- package/src/core/glob.ts +1 -1
- package/src/core/local-ai.ts +2 -2
- package/src/core/lock.ts +9 -9
- package/src/core/matrix.ts +31 -31
- package/src/core/native-notify.ts +2 -2
- package/src/core/one-shot.ts +63 -13
- package/src/core/otel.ts +4 -4
- package/src/core/permissions.ts +5 -5
- package/src/core/prometheus.ts +17 -17
- package/src/core/ps-wrapper.ts +57 -37
- package/src/core/record-history.ts +40 -40
- package/src/core/retention.ts +3 -3
- package/src/core/savings.ts +1 -1
- package/src/core/schedule-gate.ts +12 -12
- package/src/core/schedule-v2.ts +24 -24
- package/src/core/scheduler/at-fallback.ts +113 -0
- package/src/core/scheduler/index.ts +3 -3
- package/src/core/scheduler/linux.ts +64 -13
- package/src/core/scheduler/logs.ts +1 -1
- package/src/core/scheduler/mac.ts +112 -60
- package/src/core/scheduler/posix.ts +15 -1
- package/src/core/scheduler/registry.ts +6 -4
- package/src/core/scheduler/windows.ts +295 -125
- package/src/core/secrets.ts +13 -13
- package/src/core/self-analysis.ts +61 -61
- package/src/core/session.ts +3 -3
- package/src/core/structured-log.ts +3 -3
- package/src/core/summary.ts +25 -25
- package/src/core/telegram.ts +16 -16
- package/src/core/triage-chain.ts +4 -4
- package/src/core/triage-compare.ts +8 -8
- package/src/core/triage-rules.ts +4 -4
- package/src/core/triage-shadow.ts +7 -7
- package/src/core/triage-worker.ts +6 -6
- package/src/core/triage.ts +23 -23
- package/src/core/watch-paths.ts +1 -1
- package/src/core/wrappers/bash.ts +41 -41
- package/src/db/git-state-repo.ts +1 -1
- package/src/db/history-repo.ts +22 -22
- package/src/db/index.ts +16 -6
- package/src/db/metrics-repo.ts +10 -10
- package/src/db/migrate.ts +10 -10
- package/src/db/recovery.ts +3 -3
- package/src/db/run-journal.ts +212 -0
- package/src/db/run-resume.ts +220 -0
- package/src/db/runs-repo.ts +481 -0
- package/src/db/schema.ts +205 -44
- package/src/db/settings-repo.ts +2 -2
- package/src/db/tasks-repo.ts +10 -10
- package/src/db/templates-repo.ts +7 -7
- package/src/gui.tsx +1 -1
- package/src/history.ts +4 -4
- package/src/i18n.ts +7 -7
- package/src/index.ts +341 -304
- package/src/integrations.ts +6 -6
- package/src/notifications.ts +76 -76
- package/src/profiles.ts +98 -7
- package/src/rpc.ts +96 -1
- package/src/schtasks.ts +2 -2
- package/src/server.ts +43 -42
- package/src/settings.ts +44 -44
- package/src/shared/jobs-view.ts +60 -60
- package/src/skill.ts +1 -1
- package/src/task-transfer.ts +58 -56
- package/src/templates.ts +1 -1
- package/src/types.ts +45 -10
- package/src/workspaces.ts +16 -16
- package/dist/core/self-analysis.test.d.ts +0 -2
- package/dist/core/self-analysis.test.d.ts.map +0 -1
- package/dist/core/self-analysis.test.js +0 -219
- package/dist/gui-experimental.cjs +0 -1
package/src/core/secrets.ts
CHANGED
|
@@ -59,7 +59,7 @@ let keyCache: { stamp: string; key: Buffer } | null = null;
|
|
|
59
59
|
function warn(message: string, err: unknown): void {
|
|
60
60
|
try {
|
|
61
61
|
console.warn(
|
|
62
|
-
`[secrets] ${message}: ${err instanceof Error ? err.message : String(err)}
|
|
62
|
+
`[secrets] ${message}: ${err instanceof Error ? err.message : String(err)}`,
|
|
63
63
|
);
|
|
64
64
|
} catch {
|
|
65
65
|
// console может быть недоступен — молча игнорируем.
|
|
@@ -71,7 +71,7 @@ export function validateSecretName(name: string): string {
|
|
|
71
71
|
const value = String(name ?? "").trim();
|
|
72
72
|
if (!SECRET_NAME_RE.test(value)) {
|
|
73
73
|
throw new Error(
|
|
74
|
-
"Имя секрета: латиница, цифры, '_', '.', '-', от 1 до 64 символов."
|
|
74
|
+
"Имя секрета: латиница, цифры, '_', '.', '-', от 1 до 64 символов.",
|
|
75
75
|
);
|
|
76
76
|
}
|
|
77
77
|
return value;
|
|
@@ -115,18 +115,18 @@ function restrictWindowsAcl(file: string): void {
|
|
|
115
115
|
const result = spawnSync(
|
|
116
116
|
"icacls",
|
|
117
117
|
[file, "/inheritance:r", "/grant:r", `${currentWindowsUser()}:F`],
|
|
118
|
-
{ windowsHide: true, stdio: "ignore" }
|
|
118
|
+
{ windowsHide: true, stdio: "ignore" },
|
|
119
119
|
);
|
|
120
120
|
if (result.status === 0) return;
|
|
121
121
|
throw new Error(
|
|
122
|
-
result.error?.message ?? `icacls завершился с кодом ${result.status}
|
|
122
|
+
result.error?.message ?? `icacls завершился с кодом ${result.status}`,
|
|
123
123
|
);
|
|
124
124
|
} catch (err) {
|
|
125
125
|
if (windowsAclWarned) return;
|
|
126
126
|
windowsAclWarned = true;
|
|
127
127
|
warn(
|
|
128
128
|
"не удалось ограничить ACL файла секретов; ключ может быть доступен другим локальным пользователям",
|
|
129
|
-
err
|
|
129
|
+
err,
|
|
130
130
|
);
|
|
131
131
|
}
|
|
132
132
|
}
|
|
@@ -197,8 +197,8 @@ function quarantineCorruptStore(err: unknown): boolean {
|
|
|
197
197
|
corruptedStore = target;
|
|
198
198
|
warn(
|
|
199
199
|
`secrets.json повреждён, но его не удалось переместить в ${target}. ` +
|
|
200
|
-
|
|
201
|
-
renameErr
|
|
200
|
+
"Запись новых секретов заблокирована, чтобы не потерять данные.",
|
|
201
|
+
renameErr,
|
|
202
202
|
);
|
|
203
203
|
return false;
|
|
204
204
|
}
|
|
@@ -214,7 +214,7 @@ function readFileSafe(): SecretsFile {
|
|
|
214
214
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
215
215
|
throw new Error("некорректный формат secrets.json");
|
|
216
216
|
}
|
|
217
|
-
const rawSecrets = (parsed
|
|
217
|
+
const rawSecrets = (parsed).secrets;
|
|
218
218
|
const secrets: Record<string, StoredSecret> = {};
|
|
219
219
|
if (rawSecrets && typeof rawSecrets === "object" && !Array.isArray(rawSecrets)) {
|
|
220
220
|
for (const [name, entry] of Object.entries(rawSecrets)) {
|
|
@@ -285,7 +285,7 @@ function decryptValue(name: string, entry: StoredSecret, key: Buffer): string {
|
|
|
285
285
|
const decipher = crypto.createDecipheriv(
|
|
286
286
|
"aes-256-gcm",
|
|
287
287
|
key,
|
|
288
|
-
Buffer.from(entry.iv, "base64")
|
|
288
|
+
Buffer.from(entry.iv, "base64"),
|
|
289
289
|
);
|
|
290
290
|
decipher.setAAD(Buffer.from(name, "utf8"));
|
|
291
291
|
decipher.setAuthTag(Buffer.from(entry.tag, "base64"));
|
|
@@ -300,7 +300,7 @@ export function setSecret(name: string, value: string): SecretListItem {
|
|
|
300
300
|
if (corruptedStore) {
|
|
301
301
|
throw new Error(
|
|
302
302
|
`Хранилище секретов повреждено (${corruptedStore}). ` +
|
|
303
|
-
"Устраните проблему с файлом перед записью новых секретов."
|
|
303
|
+
"Устраните проблему с файлом перед записью новых секретов.",
|
|
304
304
|
);
|
|
305
305
|
}
|
|
306
306
|
const secretName = validateSecretName(name);
|
|
@@ -372,7 +372,7 @@ export function listSecrets(): SecretListItem[] {
|
|
|
372
372
|
/** Подставляет все ссылки `${secret:NAME}` в строку. Если задан allowedSecretNames — заменяются только ссылки на имена из этого списка (scoped-инъекция), остальные оставляются без изменений. */
|
|
373
373
|
export function expandSecretRefs(
|
|
374
374
|
value: string,
|
|
375
|
-
allowedSecretNames?: string[]
|
|
375
|
+
allowedSecretNames?: string[],
|
|
376
376
|
): { value: string; missing: string[] } {
|
|
377
377
|
const missing = new Set<string>();
|
|
378
378
|
const allowed = allowedSecretNames ? new Set(allowedSecretNames) : null;
|
|
@@ -401,7 +401,7 @@ export function expandSecretRefs(
|
|
|
401
401
|
*/
|
|
402
402
|
export function resolveSecretRefs(
|
|
403
403
|
env: Record<string, string>,
|
|
404
|
-
allowedSecretNames?: string[]
|
|
404
|
+
allowedSecretNames?: string[],
|
|
405
405
|
): { env: Record<string, string>; missing: string[] } {
|
|
406
406
|
const resolved: Record<string, string> = {};
|
|
407
407
|
const missing = new Set<string>();
|
|
@@ -466,7 +466,7 @@ export function redactSecretsInText(text: unknown): string {
|
|
|
466
466
|
|
|
467
467
|
result = result.replace(
|
|
468
468
|
/\b([A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|APIKEY|CREDENTIAL|AUTH)[A-Za-z0-9_]*)\b(\s*[=:]\s*)(["']?)([^\s"',;]+)\3/gi,
|
|
469
|
-
(_match: string, key: string, sep: string, quote: string) => `${key}${sep}${quote}***${quote}
|
|
469
|
+
(_match: string, key: string, sep: string, quote: string) => `${key}${sep}${quote}***${quote}`,
|
|
470
470
|
);
|
|
471
471
|
|
|
472
472
|
// Восстанавливаем защищённые ссылки.
|
|
@@ -142,8 +142,8 @@ export function calculateHealthScore(report: AnalyticsReport): HealthScore {
|
|
|
142
142
|
const successRateScore = totals.successRate;
|
|
143
143
|
const errorRateScore = Math.max(0, 100 - (totals.error / Math.max(1, totals.total)) * 100);
|
|
144
144
|
const avgDurationScore = Math.min(100, Math.max(0, 100 - (totals.avgDurationMs / 300000) * 100)); // 5 минут = 0 баллов
|
|
145
|
-
const timeoutRateScore = Math.min(100, Math.max(0, 100 - (errors.filter(e => e.message.includes(
|
|
146
|
-
const crashRecoveryRateScore = Math.min(100, Math.max(0, 100 - (errors.filter(e => e.message.includes(
|
|
145
|
+
const timeoutRateScore = Math.min(100, Math.max(0, 100 - (errors.filter(e => e.message.includes("timeout")).length / Math.max(1, totals.total)) * 100));
|
|
146
|
+
const crashRecoveryRateScore = Math.min(100, Math.max(0, 100 - (errors.filter(e => e.message.includes("Прервано")).length / Math.max(1, totals.total)) * 100));
|
|
147
147
|
|
|
148
148
|
// Взвешенная сумма
|
|
149
149
|
const score = Math.round(
|
|
@@ -151,7 +151,7 @@ export function calculateHealthScore(report: AnalyticsReport): HealthScore {
|
|
|
151
151
|
errorRateScore * 0.25 +
|
|
152
152
|
avgDurationScore * 0.20 +
|
|
153
153
|
timeoutRateScore * 0.10 +
|
|
154
|
-
crashRecoveryRateScore * 0.10
|
|
154
|
+
crashRecoveryRateScore * 0.10,
|
|
155
155
|
);
|
|
156
156
|
|
|
157
157
|
// Уровень здоровья
|
|
@@ -199,7 +199,7 @@ export function calculateHealthScore(report: AnalyticsReport): HealthScore {
|
|
|
199
199
|
/** Обнаруживает аномалии в данных. */
|
|
200
200
|
export function detectAnomalies(
|
|
201
201
|
records: AnalyticsRecord[],
|
|
202
|
-
options: SelfAnalysisOptions = {}
|
|
202
|
+
options: SelfAnalysisOptions = {},
|
|
203
203
|
): Anomaly[] {
|
|
204
204
|
const anomalies: Anomaly[] = [];
|
|
205
205
|
const now = options.now ?? new Date();
|
|
@@ -251,8 +251,8 @@ function detectErrorSpike(records: AnalyticsRecord[], windowDays: number): Anoma
|
|
|
251
251
|
const older = records.slice(half);
|
|
252
252
|
const recent = records.slice(0, half);
|
|
253
253
|
|
|
254
|
-
const recentErrorRate = recent.filter(r => r.status ===
|
|
255
|
-
const olderErrorRate = older.filter(r => r.status ===
|
|
254
|
+
const recentErrorRate = recent.filter(r => r.status === "error").length / recent.length;
|
|
255
|
+
const olderErrorRate = older.filter(r => r.status === "error").length / older.length;
|
|
256
256
|
|
|
257
257
|
// Всплеск ошибок: недавний период значительно хуже старого
|
|
258
258
|
if (olderErrorRate < 0.5 && recentErrorRate > olderErrorRate * 2 && recentErrorRate > 0.3) {
|
|
@@ -264,13 +264,13 @@ function detectErrorSpike(records: AnalyticsRecord[], windowDays: number): Anoma
|
|
|
264
264
|
recommendations: [
|
|
265
265
|
"Проверьте логи ошибок за последнее время",
|
|
266
266
|
"Убедитесь, что Quality Gate настроен правильно",
|
|
267
|
-
"Рассмотрите добавление retryCount"
|
|
267
|
+
"Рассмотрите добавление retryCount",
|
|
268
268
|
],
|
|
269
269
|
metadata: {
|
|
270
270
|
recentErrorRate,
|
|
271
271
|
olderErrorRate,
|
|
272
|
-
windowDays
|
|
273
|
-
}
|
|
272
|
+
windowDays,
|
|
273
|
+
},
|
|
274
274
|
};
|
|
275
275
|
}
|
|
276
276
|
return null;
|
|
@@ -298,13 +298,13 @@ function detectDurationSpike(records: AnalyticsRecord[]): Anomaly | null {
|
|
|
298
298
|
recommendations: [
|
|
299
299
|
"Проверьте, не завис ли процесс",
|
|
300
300
|
"Увеличьте timeoutSeconds если задача легитимно долгая",
|
|
301
|
-
"Рассмотрите разделение задачи на части"
|
|
301
|
+
"Рассмотрите разделение задачи на части",
|
|
302
302
|
],
|
|
303
303
|
metadata: {
|
|
304
304
|
recentDuration,
|
|
305
305
|
medianDuration: median,
|
|
306
|
-
ratio: recentDuration / median
|
|
307
|
-
}
|
|
306
|
+
ratio: recentDuration / median,
|
|
307
|
+
},
|
|
308
308
|
};
|
|
309
309
|
}
|
|
310
310
|
return null;
|
|
@@ -313,7 +313,7 @@ function detectDurationSpike(records: AnalyticsRecord[]): Anomaly | null {
|
|
|
313
313
|
function detectTimeoutSpike(records: AnalyticsRecord[]): Anomaly | null {
|
|
314
314
|
if (records.length < 5) return null;
|
|
315
315
|
|
|
316
|
-
const timeoutCount = records.filter(r => r.error?.includes(
|
|
316
|
+
const timeoutCount = records.filter(r => r.error?.includes("timeout")).length;
|
|
317
317
|
const timeoutRate = timeoutCount / records.length;
|
|
318
318
|
|
|
319
319
|
if (timeoutRate > 0.2) {
|
|
@@ -325,13 +325,13 @@ function detectTimeoutSpike(records: AnalyticsRecord[]): Anomaly | null {
|
|
|
325
325
|
recommendations: [
|
|
326
326
|
"Увеличьте timeoutSeconds",
|
|
327
327
|
"Упростите промпты задачи",
|
|
328
|
-
"Проверьте производительность модели"
|
|
328
|
+
"Проверьте производительность модели",
|
|
329
329
|
],
|
|
330
330
|
metadata: {
|
|
331
331
|
timeoutCount,
|
|
332
332
|
totalRecords: records.length,
|
|
333
|
-
timeoutRate
|
|
334
|
-
}
|
|
333
|
+
timeoutRate,
|
|
334
|
+
},
|
|
335
335
|
};
|
|
336
336
|
}
|
|
337
337
|
return null;
|
|
@@ -359,13 +359,13 @@ function detectCostSpike(records: AnalyticsRecord[]): Anomaly | null {
|
|
|
359
359
|
recommendations: [
|
|
360
360
|
"Проверьте, не используется ли более дорогая модель",
|
|
361
361
|
"Оптимизируйте промпты для снижения токенов",
|
|
362
|
-
"Рассмотрите использование локальной модели"
|
|
362
|
+
"Рассмотрите использование локальной модели",
|
|
363
363
|
],
|
|
364
364
|
metadata: {
|
|
365
365
|
recentCost,
|
|
366
366
|
medianCost: median,
|
|
367
|
-
ratio: recentCost / median
|
|
368
|
-
}
|
|
367
|
+
ratio: recentCost / median,
|
|
368
|
+
},
|
|
369
369
|
};
|
|
370
370
|
}
|
|
371
371
|
return null;
|
|
@@ -376,8 +376,8 @@ function detectUnusualPattern(records: AnalyticsRecord[]): Anomaly | null {
|
|
|
376
376
|
|
|
377
377
|
// Проверяем паттерн: все подряд ошибки или все подряд успехи
|
|
378
378
|
const recent = records.slice(0, 5);
|
|
379
|
-
const allErrors = recent.every(r => r.status ===
|
|
380
|
-
const allSuccess = recent.every(r => r.status ===
|
|
379
|
+
const allErrors = recent.every(r => r.status === "error");
|
|
380
|
+
const allSuccess = recent.every(r => r.status === "success");
|
|
381
381
|
|
|
382
382
|
if (allErrors) {
|
|
383
383
|
return {
|
|
@@ -388,12 +388,12 @@ function detectUnusualPattern(records: AnalyticsRecord[]): Anomaly | null {
|
|
|
388
388
|
recommendations: [
|
|
389
389
|
"Проверьте, не сломалась ли зависимость",
|
|
390
390
|
"Проверьте доступность внешних сервисов",
|
|
391
|
-
"Рассмотрите приостановку задачи до устранения проблемы"
|
|
391
|
+
"Рассмотрите приостановку задачи до устранения проблемы",
|
|
392
392
|
],
|
|
393
393
|
metadata: {
|
|
394
394
|
pattern: "consecutive_errors",
|
|
395
|
-
count: 5
|
|
396
|
-
}
|
|
395
|
+
count: 5,
|
|
396
|
+
},
|
|
397
397
|
};
|
|
398
398
|
}
|
|
399
399
|
|
|
@@ -401,7 +401,7 @@ function detectUnusualPattern(records: AnalyticsRecord[]): Anomaly | null {
|
|
|
401
401
|
}
|
|
402
402
|
|
|
403
403
|
function detectStalledRun(records: AnalyticsRecord[], now: Date): Anomaly | null {
|
|
404
|
-
const running = records.find(r => r.status ===
|
|
404
|
+
const running = records.find(r => r.status === "running");
|
|
405
405
|
if (!running) return null;
|
|
406
406
|
|
|
407
407
|
const startedAt = new Date(running.startedAt);
|
|
@@ -416,13 +416,13 @@ function detectStalledRun(records: AnalyticsRecord[], now: Date): Anomaly | null
|
|
|
416
416
|
recommendations: [
|
|
417
417
|
"Проверьте, не завис ли процесс",
|
|
418
418
|
"Рассмотрите принудительное завершение",
|
|
419
|
-
"Проверьте блокировки (lock file)"
|
|
419
|
+
"Проверьте блокировки (lock file)",
|
|
420
420
|
],
|
|
421
421
|
metadata: {
|
|
422
422
|
hoursRunning,
|
|
423
423
|
startedAt: running.startedAt,
|
|
424
|
-
taskId: (running as any).id
|
|
425
|
-
}
|
|
424
|
+
taskId: (running as any).id,
|
|
425
|
+
},
|
|
426
426
|
};
|
|
427
427
|
}
|
|
428
428
|
return null;
|
|
@@ -433,7 +433,7 @@ function detectStalledRun(records: AnalyticsRecord[], now: Date): Anomaly | null
|
|
|
433
433
|
/** Анализирует тренды метрик. */
|
|
434
434
|
export function analyzeTrends(
|
|
435
435
|
records: AnalyticsRecord[],
|
|
436
|
-
options: SelfAnalysisOptions = {}
|
|
436
|
+
options: SelfAnalysisOptions = {},
|
|
437
437
|
): Trend[] {
|
|
438
438
|
const trends: Trend[] = [];
|
|
439
439
|
const windowDays = options.days ?? 14;
|
|
@@ -446,8 +446,8 @@ export function analyzeTrends(
|
|
|
446
446
|
if (older.length < 3 || recent.length < 3) return trends;
|
|
447
447
|
|
|
448
448
|
// 1. Тренд успешности
|
|
449
|
-
const olderSuccessRate = older.filter(r => r.status ===
|
|
450
|
-
const recentSuccessRate = recent.filter(r => r.status ===
|
|
449
|
+
const olderSuccessRate = older.filter(r => r.status === "success").length / older.length;
|
|
450
|
+
const recentSuccessRate = recent.filter(r => r.status === "success").length / recent.length;
|
|
451
451
|
const successChange = ((recentSuccessRate - olderSuccessRate) / Math.max(olderSuccessRate, 0.01)) * 100;
|
|
452
452
|
|
|
453
453
|
trends.push({
|
|
@@ -457,8 +457,8 @@ export function analyzeTrends(
|
|
|
457
457
|
description: `Успешность: ${Math.round(olderSuccessRate * 100)}% → ${Math.round(recentSuccessRate * 100)}%`,
|
|
458
458
|
recommendations: successChange < -10 ? [
|
|
459
459
|
"Проверьте, что изменилось в последнее время",
|
|
460
|
-
"Проверьте логи ошибок"
|
|
461
|
-
] : []
|
|
460
|
+
"Проверьте логи ошибок",
|
|
461
|
+
] : [],
|
|
462
462
|
});
|
|
463
463
|
|
|
464
464
|
// 2. Тренд длительности
|
|
@@ -477,8 +477,8 @@ export function analyzeTrends(
|
|
|
477
477
|
description: `Средняя длительность: ${Math.round(olderAvgDuration / 1000)}с → ${Math.round(recentAvgDuration / 1000)}с`,
|
|
478
478
|
recommendations: durationChange > 20 ? [
|
|
479
479
|
"Оптимизируйте промпты",
|
|
480
|
-
"Проверьте, не увеличилась ли нагрузка"
|
|
481
|
-
] : []
|
|
480
|
+
"Проверьте, не увеличилась ли нагрузка",
|
|
481
|
+
] : [],
|
|
482
482
|
});
|
|
483
483
|
}
|
|
484
484
|
|
|
@@ -498,8 +498,8 @@ export function analyzeTrends(
|
|
|
498
498
|
description: `Средняя стоимость: $${olderAvgCost.toFixed(4)} → $${recentAvgCost.toFixed(4)}`,
|
|
499
499
|
recommendations: costChange > 20 ? [
|
|
500
500
|
"Проверьте, не используется ли более дорогая модель",
|
|
501
|
-
"Оптимизируйте промпты для снижения токенов"
|
|
502
|
-
] : []
|
|
501
|
+
"Оптимизируйте промпты для снижения токенов",
|
|
502
|
+
] : [],
|
|
503
503
|
});
|
|
504
504
|
}
|
|
505
505
|
|
|
@@ -512,7 +512,7 @@ export function analyzeTrends(
|
|
|
512
512
|
export function generateRecommendations(
|
|
513
513
|
report: AnalyticsReport,
|
|
514
514
|
anomalies: Anomaly[],
|
|
515
|
-
trends: Trend[]
|
|
515
|
+
trends: Trend[],
|
|
516
516
|
): Recommendation[] {
|
|
517
517
|
const recommendations: Recommendation[] = [];
|
|
518
518
|
|
|
@@ -534,8 +534,8 @@ export function generateRecommendations(
|
|
|
534
534
|
"Проверьте логи ошибок за последние 7 дней",
|
|
535
535
|
"Убедитесь, что Quality Gate настроен правильно",
|
|
536
536
|
"Добавьте retryCount для флакких задач",
|
|
537
|
-
"Проверьте доступность внешних сервисов"
|
|
538
|
-
]
|
|
537
|
+
"Проверьте доступность внешних сервисов",
|
|
538
|
+
],
|
|
539
539
|
});
|
|
540
540
|
}
|
|
541
541
|
|
|
@@ -544,12 +544,12 @@ export function generateRecommendations(
|
|
|
544
544
|
if (anomaly.severity > 70) {
|
|
545
545
|
recommendations.push({
|
|
546
546
|
priority: Math.min(10, Math.round(anomaly.severity / 10)),
|
|
547
|
-
category: anomaly.type.includes(
|
|
547
|
+
category: anomaly.type.includes("cost") ? "cost" : "performance",
|
|
548
548
|
title: `Устраните аномалию: ${anomaly.type}`,
|
|
549
549
|
description: anomaly.description,
|
|
550
550
|
expectedImpact: "Снизит нагрузку и улучшит стабильность",
|
|
551
551
|
effort: "medium",
|
|
552
|
-
steps: anomaly.recommendations
|
|
552
|
+
steps: anomaly.recommendations,
|
|
553
553
|
});
|
|
554
554
|
}
|
|
555
555
|
}
|
|
@@ -559,12 +559,12 @@ export function generateRecommendations(
|
|
|
559
559
|
if (trend.direction === "degrading" && Math.abs(trend.changePercent) > 20) {
|
|
560
560
|
recommendations.push({
|
|
561
561
|
priority: 7,
|
|
562
|
-
category: trend.metric.includes(
|
|
562
|
+
category: trend.metric.includes("cost") ? "cost" : "performance",
|
|
563
563
|
title: `Обратите внимание на тренд: ${trend.metric}`,
|
|
564
564
|
description: trend.description,
|
|
565
565
|
expectedImpact: "Предотвратит дальнейшее ухудшение",
|
|
566
566
|
effort: "low",
|
|
567
|
-
steps: trend.recommendations
|
|
567
|
+
steps: trend.recommendations,
|
|
568
568
|
});
|
|
569
569
|
}
|
|
570
570
|
}
|
|
@@ -582,8 +582,8 @@ export function generateRecommendations(
|
|
|
582
582
|
"Проверьте, не используется ли более дорогая модель для простых задач",
|
|
583
583
|
"Оптимизируйте промпты для снижения токенов",
|
|
584
584
|
"Рассмотрите использование локальной модели для простых задач",
|
|
585
|
-
"Настройте лимиты на задачи с высокими затратами"
|
|
586
|
-
]
|
|
585
|
+
"Настройте лимиты на задачи с высокими затратами",
|
|
586
|
+
],
|
|
587
587
|
});
|
|
588
588
|
}
|
|
589
589
|
|
|
@@ -600,13 +600,13 @@ export function generateRecommendations(
|
|
|
600
600
|
"Разбейте длинные задачи на более мелкие",
|
|
601
601
|
"Упростите промпты",
|
|
602
602
|
"Проверьте, не используются ли медленные модели",
|
|
603
|
-
"Увеличьте timeoutSeconds если задачи легитимно долгие"
|
|
604
|
-
]
|
|
603
|
+
"Увеличьте timeoutSeconds если задачи легитимно долгие",
|
|
604
|
+
],
|
|
605
605
|
});
|
|
606
606
|
}
|
|
607
607
|
|
|
608
608
|
// Рекомендации на основе таймаутов
|
|
609
|
-
const timeoutErrors = report.errors.filter(e => e.message.includes(
|
|
609
|
+
const timeoutErrors = report.errors.filter(e => e.message.includes("timeout"));
|
|
610
610
|
if (timeoutErrors.length > 0) {
|
|
611
611
|
recommendations.push({
|
|
612
612
|
priority: 8,
|
|
@@ -619,13 +619,13 @@ export function generateRecommendations(
|
|
|
619
619
|
"Увеличьте timeoutSeconds для затронутых задач",
|
|
620
620
|
"Упростите промпты",
|
|
621
621
|
"Проверьте производительность модели",
|
|
622
|
-
"Рассмотрите разделение сложных задач"
|
|
623
|
-
]
|
|
622
|
+
"Рассмотрите разделение сложных задач",
|
|
623
|
+
],
|
|
624
624
|
});
|
|
625
625
|
}
|
|
626
626
|
|
|
627
627
|
// Рекомендации на основе крашей
|
|
628
|
-
const crashErrors = report.errors.filter(e => e.message.includes(
|
|
628
|
+
const crashErrors = report.errors.filter(e => e.message.includes("Прервано"));
|
|
629
629
|
if (crashErrors.length > 0) {
|
|
630
630
|
recommendations.push({
|
|
631
631
|
priority: 7,
|
|
@@ -638,8 +638,8 @@ export function generateRecommendations(
|
|
|
638
638
|
"Проверьте стабильность системы",
|
|
639
639
|
"Проверьте, нет ли конфликтов между задачами",
|
|
640
640
|
"Убедитесь, что задачи не превышают лимиты ресурсов",
|
|
641
|
-
"Рассмотрите настройку crash recovery"
|
|
642
|
-
]
|
|
641
|
+
"Рассмотрите настройку crash recovery",
|
|
642
|
+
],
|
|
643
643
|
});
|
|
644
644
|
}
|
|
645
645
|
|
|
@@ -652,7 +652,7 @@ export function generateRecommendations(
|
|
|
652
652
|
/** Генерирует полный отчёт самоанализа. */
|
|
653
653
|
export function generateSelfAnalysisReport(
|
|
654
654
|
records: AnalyticsRecord[],
|
|
655
|
-
options: SelfAnalysisOptions = {}
|
|
655
|
+
options: SelfAnalysisOptions = {},
|
|
656
656
|
): SelfAnalysisReport {
|
|
657
657
|
const windowDays = options.days ?? 14;
|
|
658
658
|
const now = options.now ?? new Date();
|
|
@@ -662,7 +662,7 @@ export function generateSelfAnalysisReport(
|
|
|
662
662
|
days: windowDays,
|
|
663
663
|
now,
|
|
664
664
|
topLimit: options.topLimit,
|
|
665
|
-
tasks: options.tasks
|
|
665
|
+
tasks: options.tasks,
|
|
666
666
|
});
|
|
667
667
|
|
|
668
668
|
// Health Score
|
|
@@ -691,8 +691,8 @@ export function generateSelfAnalysisReport(
|
|
|
691
691
|
sources: {
|
|
692
692
|
historyRecords: records.length,
|
|
693
693
|
recordsInWindow: analyticsReport.sources.recordsInWindow,
|
|
694
|
-
tasksAnalyzed: analyticsReport.tasks.length
|
|
695
|
-
}
|
|
694
|
+
tasksAnalyzed: analyticsReport.tasks.length,
|
|
695
|
+
},
|
|
696
696
|
};
|
|
697
697
|
}
|
|
698
698
|
|
|
@@ -700,7 +700,7 @@ function generateSummary(
|
|
|
700
700
|
health: HealthScore,
|
|
701
701
|
anomalies: Anomaly[],
|
|
702
702
|
trends: Trend[],
|
|
703
|
-
recommendations: Recommendation[]
|
|
703
|
+
recommendations: Recommendation[],
|
|
704
704
|
): string {
|
|
705
705
|
const parts: string[] = [];
|
|
706
706
|
|
|
@@ -710,7 +710,7 @@ function generateSummary(
|
|
|
710
710
|
good: "хорошее",
|
|
711
711
|
fair: "удовлетворительное",
|
|
712
712
|
poor: "плохое",
|
|
713
|
-
critical: "критическое"
|
|
713
|
+
critical: "критическое",
|
|
714
714
|
};
|
|
715
715
|
parts.push(`Здоровье системы: ${levelNames[health.level]} (${health.score}/100)`);
|
|
716
716
|
|
|
@@ -727,7 +727,7 @@ function generateSummary(
|
|
|
727
727
|
}
|
|
728
728
|
|
|
729
729
|
// Тренды
|
|
730
|
-
const degradingTrends = trends.filter(t => t.direction ===
|
|
730
|
+
const degradingTrends = trends.filter(t => t.direction === "degrading").length;
|
|
731
731
|
if (degradingTrends > 0) {
|
|
732
732
|
parts.push(`${degradingTrends} метрик ухудшаются`);
|
|
733
733
|
}
|
package/src/core/session.ts
CHANGED
|
@@ -67,7 +67,7 @@ export function preservedSessionRunCount(
|
|
|
67
67
|
| { session?: SessionMode; sessionId?: string; sessionRunCount?: number }
|
|
68
68
|
| undefined,
|
|
69
69
|
session: SessionMode,
|
|
70
|
-
sessionId: string | undefined
|
|
70
|
+
sessionId: string | undefined,
|
|
71
71
|
): number {
|
|
72
72
|
if (!previous) return 0;
|
|
73
73
|
if (previous.session !== session || previous.sessionId !== sessionId) return 0;
|
|
@@ -86,7 +86,7 @@ export function sessionStatePath(taskName: string): string {
|
|
|
86
86
|
*/
|
|
87
87
|
export async function writeSessionStateFile(
|
|
88
88
|
taskName: string,
|
|
89
|
-
sessionId: string | undefined
|
|
89
|
+
sessionId: string | undefined,
|
|
90
90
|
): Promise<void> {
|
|
91
91
|
try {
|
|
92
92
|
const file = sessionStatePath(taskName);
|
|
@@ -99,7 +99,7 @@ export async function writeSessionStateFile(
|
|
|
99
99
|
} catch (error) {
|
|
100
100
|
console.warn(
|
|
101
101
|
`[session] Не удалось обновить файл сессии задачи "${taskName}":`,
|
|
102
|
-
error
|
|
102
|
+
error,
|
|
103
103
|
);
|
|
104
104
|
}
|
|
105
105
|
}
|
|
@@ -79,7 +79,7 @@ export const STRUCTURED_LOG_MAX_BYTES = 10 * 1024 * 1024;
|
|
|
79
79
|
function warn(message: string, err: unknown): void {
|
|
80
80
|
try {
|
|
81
81
|
console.warn(
|
|
82
|
-
`[structured-log] ${message}: ${err instanceof Error ? err.message : String(err)}
|
|
82
|
+
`[structured-log] ${message}: ${err instanceof Error ? err.message : String(err)}`,
|
|
83
83
|
);
|
|
84
84
|
} catch {
|
|
85
85
|
// console может быть недоступен в урезанном окружении — молча игнорируем.
|
|
@@ -112,7 +112,7 @@ function rotateIfNeeded(): void {
|
|
|
112
112
|
* Не бросает исключений.
|
|
113
113
|
*/
|
|
114
114
|
export function appendStructuredLog(
|
|
115
|
-
record: Omit<StructuredLogRecord, "ts"> & { ts?: string }
|
|
115
|
+
record: Omit<StructuredLogRecord, "ts"> & { ts?: string },
|
|
116
116
|
): boolean {
|
|
117
117
|
try {
|
|
118
118
|
ensureLogDir();
|
|
@@ -156,7 +156,7 @@ function readLines(file: string): string[] {
|
|
|
156
156
|
* `total` считается до применения limit, чтобы клиент знал полный объём.
|
|
157
157
|
*/
|
|
158
158
|
export function readStructuredLogs(
|
|
159
|
-
filter: ReadStructuredLogsFilter = {}
|
|
159
|
+
filter: ReadStructuredLogsFilter = {},
|
|
160
160
|
): ReadStructuredLogsResult {
|
|
161
161
|
const limit = Math.max(1, Math.min(5000, Math.floor(filter.limit ?? 200) || 200));
|
|
162
162
|
const task = filter.task?.trim().toLowerCase();
|
package/src/core/summary.ts
CHANGED
|
@@ -62,7 +62,7 @@ class SummaryParseFailure extends Error {
|
|
|
62
62
|
| "invalid-json"
|
|
63
63
|
| "invalid-schema"
|
|
64
64
|
| "invalid-response",
|
|
65
|
-
message: string
|
|
65
|
+
message: string,
|
|
66
66
|
) {
|
|
67
67
|
super(message);
|
|
68
68
|
}
|
|
@@ -77,13 +77,13 @@ function resolveEndpoint(baseUrl: string): {
|
|
|
77
77
|
protocol: "ollama" | "openai";
|
|
78
78
|
} {
|
|
79
79
|
const base = baseUrl.replace(/\/+$/, "");
|
|
80
|
-
if (
|
|
80
|
+
if (base.endsWith("/v1")) {
|
|
81
81
|
return { url: `${base}/chat/completions`, protocol: "openai" };
|
|
82
82
|
}
|
|
83
83
|
return { url: `${base}/api/chat`, protocol: "ollama" };
|
|
84
84
|
}
|
|
85
85
|
|
|
86
|
-
function buildMessages(input: SummaryInput):
|
|
86
|
+
function buildMessages(input: SummaryInput): { role: string; content: string }[] {
|
|
87
87
|
const payload = {
|
|
88
88
|
task: input.taskName,
|
|
89
89
|
status: input.status,
|
|
@@ -181,7 +181,7 @@ function formatDuration(ms: number): string {
|
|
|
181
181
|
export function truncateSummary(
|
|
182
182
|
input: SummaryInput,
|
|
183
183
|
maxLines: number,
|
|
184
|
-
maxChars: number
|
|
184
|
+
maxChars: number,
|
|
185
185
|
): string[] {
|
|
186
186
|
const lines: string[] = [];
|
|
187
187
|
lines.push(`${input.taskName}: ${input.status}`.slice(0, maxChars));
|
|
@@ -218,7 +218,7 @@ export async function summarizeNotification(
|
|
|
218
218
|
input: SummaryInput,
|
|
219
219
|
settings: NotificationSummarySettings,
|
|
220
220
|
provider: SummaryProvider,
|
|
221
|
-
options: { timeoutMs?: number } = {}
|
|
221
|
+
options: { timeoutMs?: number } = {},
|
|
222
222
|
): Promise<SummaryResult> {
|
|
223
223
|
const startedAt = Date.now();
|
|
224
224
|
const maxLines = settings.maxLines || 3;
|
|
@@ -250,26 +250,26 @@ export async function summarizeNotification(
|
|
|
250
250
|
const body =
|
|
251
251
|
protocol === "openai"
|
|
252
252
|
? {
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
},
|
|
253
|
+
model,
|
|
254
|
+
messages,
|
|
255
|
+
temperature: 0,
|
|
256
|
+
stream: false,
|
|
257
|
+
response_format: {
|
|
258
|
+
type: "json_schema",
|
|
259
|
+
json_schema: {
|
|
260
|
+
name: "notification_summary",
|
|
261
|
+
strict: true,
|
|
262
|
+
schema: SUMMARY_SCHEMA,
|
|
264
263
|
},
|
|
265
|
-
}
|
|
264
|
+
},
|
|
265
|
+
}
|
|
266
266
|
: {
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
267
|
+
model,
|
|
268
|
+
messages,
|
|
269
|
+
stream: false,
|
|
270
|
+
format: SUMMARY_SCHEMA,
|
|
271
|
+
options: { temperature: 0 },
|
|
272
|
+
};
|
|
273
273
|
|
|
274
274
|
const response = await fetch(url, {
|
|
275
275
|
method: "POST",
|
|
@@ -291,7 +291,7 @@ export async function summarizeNotification(
|
|
|
291
291
|
const lines = parseSummary(
|
|
292
292
|
contentFromBody(parsed, protocol),
|
|
293
293
|
maxLines,
|
|
294
|
-
maxChars
|
|
294
|
+
maxChars,
|
|
295
295
|
);
|
|
296
296
|
clearTimeout(timer);
|
|
297
297
|
return {
|
|
@@ -312,7 +312,7 @@ export async function summarizeNotification(
|
|
|
312
312
|
|
|
313
313
|
/** Провайдер из настроек триажа: baseUrl/model используются те же. */
|
|
314
314
|
export function summaryProviderFromTriage(
|
|
315
|
-
triage: TriageSettings | undefined
|
|
315
|
+
triage: TriageSettings | undefined,
|
|
316
316
|
): SummaryProvider {
|
|
317
317
|
return { baseUrl: triage?.baseUrl, model: triage?.model };
|
|
318
318
|
}
|