agent-steward 0.0.4 → 0.0.6
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 +309 -2
- package/CROSS_PLATFORM.md +19 -0
- package/README.md +55 -8
- package/ROADMAP-STRATEGY.md +22 -19
- package/ROADMAP.md +230 -159
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +356 -0
- package/dist/core/analytics.d.ts +6 -0
- package/dist/core/analytics.d.ts.map +1 -1
- package/dist/core/analytics.js +20 -3
- package/dist/core/audit.d.ts +6 -0
- package/dist/core/audit.d.ts.map +1 -1
- package/dist/core/audit.js +24 -0
- package/dist/core/budget.d.ts +118 -0
- package/dist/core/budget.d.ts.map +1 -0
- package/dist/core/budget.js +206 -0
- package/dist/core/cron-to-schtasks.d.ts.map +1 -1
- package/dist/core/cron-to-schtasks.js +38 -0
- package/dist/core/dry-run.d.ts +26 -1
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +199 -8
- package/dist/core/execution.d.ts +203 -0
- package/dist/core/execution.d.ts.map +1 -0
- package/dist/core/execution.js +309 -0
- package/dist/core/feedback.d.ts +192 -0
- package/dist/core/feedback.d.ts.map +1 -0
- package/dist/core/feedback.js +426 -0
- package/dist/core/gate-integrity.d.ts +71 -0
- package/dist/core/gate-integrity.d.ts.map +1 -0
- package/dist/core/gate-integrity.js +275 -0
- package/dist/core/git-trigger.d.ts.map +1 -1
- package/dist/core/git-trigger.js +14 -2
- package/dist/core/guard-run.d.ts +4 -0
- package/dist/core/guard-run.d.ts.map +1 -0
- package/dist/core/guard-run.js +101 -0
- package/dist/core/guard.d.ts +52 -0
- package/dist/core/guard.d.ts.map +1 -0
- package/dist/core/guard.js +362 -0
- package/dist/core/local-ai.d.ts.map +1 -1
- package/dist/core/local-ai.js +7 -3
- package/dist/core/lock.d.ts +41 -0
- package/dist/core/lock.d.ts.map +1 -1
- package/dist/core/lock.js +141 -29
- package/dist/core/matrix.d.ts +8 -0
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +132 -17
- package/dist/core/mission.d.ts +103 -0
- package/dist/core/mission.d.ts.map +1 -0
- package/dist/core/mission.js +374 -0
- package/dist/core/opencode-models.d.ts +2 -2
- package/dist/core/opencode-models.d.ts.map +1 -1
- package/dist/core/opencode-models.js +28 -21
- package/dist/core/opencode-usage.d.ts +35 -0
- package/dist/core/opencode-usage.d.ts.map +1 -0
- package/dist/core/opencode-usage.js +132 -0
- package/dist/core/pipeline-apply.d.ts +38 -0
- package/dist/core/pipeline-apply.d.ts.map +1 -0
- package/dist/core/pipeline-apply.js +117 -0
- package/dist/core/pipeline-io.d.ts +13 -0
- package/dist/core/pipeline-io.d.ts.map +1 -0
- package/dist/core/pipeline-io.js +78 -0
- package/dist/core/pipeline-map.d.ts +52 -0
- package/dist/core/pipeline-map.d.ts.map +1 -0
- package/dist/core/pipeline-map.js +208 -0
- package/dist/core/pipeline-spec.d.ts +109 -0
- package/dist/core/pipeline-spec.d.ts.map +1 -0
- package/dist/core/pipeline-spec.js +554 -0
- package/dist/core/ps-wrapper.d.ts +27 -2
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +424 -65
- package/dist/core/record-history.d.ts.map +1 -1
- package/dist/core/record-history.js +206 -33
- package/dist/core/router/rules.d.ts.map +1 -1
- package/dist/core/router/rules.js +6 -0
- package/dist/core/run-mode.d.ts +12 -0
- package/dist/core/run-mode.d.ts.map +1 -0
- package/dist/core/run-mode.js +17 -0
- package/dist/core/scheduler/linux.d.ts +8 -1
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +34 -9
- package/dist/core/scheduler/logs.d.ts +4 -0
- package/dist/core/scheduler/logs.d.ts.map +1 -1
- package/dist/core/scheduler/logs.js +25 -1
- package/dist/core/scheduler/mac.d.ts +44 -2
- package/dist/core/scheduler/mac.d.ts.map +1 -1
- package/dist/core/scheduler/mac.js +126 -15
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +15 -12
- package/dist/core/secrets.d.ts.map +1 -1
- package/dist/core/secrets.js +18 -8
- package/dist/core/self-analysis.d.ts +32 -2
- package/dist/core/self-analysis.d.ts.map +1 -1
- package/dist/core/self-analysis.js +38 -27
- package/dist/core/shutdown.d.ts +33 -2
- package/dist/core/shutdown.d.ts.map +1 -1
- package/dist/core/shutdown.js +58 -2
- package/dist/core/structured-log.d.ts +37 -1
- package/dist/core/structured-log.d.ts.map +1 -1
- package/dist/core/structured-log.js +37 -0
- package/dist/core/usage-surface.d.ts +25 -0
- package/dist/core/usage-surface.d.ts.map +1 -0
- package/dist/core/usage-surface.js +41 -0
- package/dist/core/worktree-run.d.ts +4 -0
- package/dist/core/worktree-run.d.ts.map +1 -0
- package/dist/core/worktree-run.js +164 -0
- package/dist/core/worktree.d.ts +115 -0
- package/dist/core/worktree.d.ts.map +1 -0
- package/dist/core/worktree.js +462 -0
- package/dist/core/wrappers/bash.d.ts +19 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +230 -27
- package/dist/db/capability-repo.d.ts +43 -2
- package/dist/db/capability-repo.d.ts.map +1 -1
- package/dist/db/capability-repo.js +96 -11
- package/dist/db/history-repo.d.ts +70 -5
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +170 -29
- package/dist/db/metrics-repo.d.ts +20 -2
- package/dist/db/metrics-repo.d.ts.map +1 -1
- package/dist/db/metrics-repo.js +35 -13
- package/dist/db/migrate.d.ts.map +1 -1
- package/dist/db/migrate.js +37 -17
- package/dist/db/recovery.d.ts +3 -1
- package/dist/db/recovery.d.ts.map +1 -1
- package/dist/db/recovery.js +11 -5
- package/dist/db/run-journal.d.ts +33 -5
- package/dist/db/run-journal.d.ts.map +1 -1
- package/dist/db/run-journal.js +78 -14
- package/dist/db/run-resume.d.ts +5 -0
- package/dist/db/run-resume.d.ts.map +1 -1
- package/dist/db/run-resume.js +9 -2
- package/dist/db/runs-repo.d.ts +19 -2
- package/dist/db/runs-repo.d.ts.map +1 -1
- package/dist/db/runs-repo.js +91 -60
- package/dist/db/schema.d.ts +2 -2
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +132 -2
- package/dist/db/templates-repo.d.ts +2 -2
- package/dist/db/templates-repo.d.ts.map +1 -1
- package/dist/db/templates-repo.js +5 -3
- package/dist/history.d.ts +7 -2
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +4 -2
- package/dist/hook-output.d.ts +2 -0
- package/dist/hook-output.d.ts.map +1 -0
- package/dist/hook-output.js +31 -0
- package/dist/i18n.d.ts +5 -0
- package/dist/i18n.d.ts.map +1 -1
- package/dist/i18n.js +11 -4
- package/dist/index.d.ts +375 -47
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1344 -192
- package/dist/notifications.d.ts +53 -2
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +168 -21
- package/dist/profiles.d.ts.map +1 -1
- package/dist/profiles.js +82 -10
- package/dist/rpc.d.ts +354 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +145 -0
- package/dist/server.d.ts +32 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +154 -30
- package/dist/settings.d.ts +44 -2
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +85 -3
- package/dist/shared/jobs-view.d.ts +1 -1
- package/dist/shared/jobs-view.d.ts.map +1 -1
- package/dist/shared/jobs-view.js +2 -0
- package/dist/task-transfer.d.ts +21 -0
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +64 -3
- package/dist/templates.d.ts +2 -2
- package/dist/templates.d.ts.map +1 -1
- package/dist/templates.js +3 -3
- package/dist/types.d.ts +22 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +34 -11
- package/docs/ARCHITECTURE.md +319 -66
- package/docs/COMPATIBILITY.md +2 -2
- package/docs/CONCEPT.md +18 -4
- package/docs/CROSS_PLATFORM.ru.md +20 -0
- package/docs/CROSS_PLATFORM.zh.md +18 -0
- package/docs/EXECUTION-LOOP.md +28 -10
- package/docs/FEATURES.md +129 -7
- package/docs/FEATURES.zh.md +97 -6
- package/docs/MIGRATION.md +2 -2
- package/docs/PIPELINE.md +293 -0
- package/docs/QA-A2-GUI-TUI.md +205 -0
- package/docs/README.ru.md +43 -4
- package/docs/README.zh.md +44 -4
- package/docs/SAFETY.md +23 -3
- package/gui-experimental.cjs +9 -8
- package/locales/en.json +58 -3
- package/locales/ru.json +58 -3
- package/locales/zh.json +58 -3
- package/opencode.pipeline.yaml +35 -0
- package/package.json +36 -4
- package/scripts/check-eslint-baseline.mjs +139 -0
- package/scripts/gen-test-plan-counters.mjs +117 -0
- package/scripts/github-ci-fetch.ps1 +37 -0
- package/scripts/pl-commit.ps1 +112 -0
- package/scripts/qa-a2-commit.ps1 +104 -0
- package/scripts/test-home.mjs +107 -0
- package/skills/scheduled-job-best-practices/SKILL.md +95 -1
- package/skills/scheduled-job-best-practices/references/recipes.md +139 -0
- package/src/cli.ts +417 -0
- package/src/core/analytics.ts +27 -4
- package/src/core/audit.ts +25 -0
- package/src/core/budget.ts +340 -0
- package/src/core/cron-to-schtasks.ts +42 -0
- package/src/core/dry-run.ts +235 -12
- package/src/core/execution.ts +538 -0
- package/src/core/feedback.ts +582 -0
- package/src/core/file-watcher.ts +2 -2
- package/src/core/gate-integrity.ts +330 -0
- package/src/core/git-trigger.ts +18 -5
- package/src/core/guard-run.ts +119 -0
- package/src/core/guard.ts +431 -0
- package/src/core/local-ai.ts +7 -3
- package/src/core/lock.ts +178 -37
- package/src/core/matrix.ts +158 -52
- package/src/core/mission.ts +531 -0
- package/src/core/native-notify.ts +1 -1
- package/src/core/opencode-models.ts +30 -21
- package/src/core/opencode-usage.ts +182 -0
- package/src/core/pipeline-apply.ts +158 -0
- package/src/core/pipeline-io.ts +96 -0
- package/src/core/pipeline-map.ts +283 -0
- package/src/core/pipeline-spec.ts +775 -0
- package/src/core/ps-wrapper.ts +435 -66
- package/src/core/record-history.ts +258 -81
- package/src/core/router/rules.ts +6 -0
- package/src/core/run-mode.ts +19 -0
- package/src/core/schedule-gate.ts +1 -1
- package/src/core/scheduler/at-fallback.ts +1 -1
- package/src/core/scheduler/linux.ts +40 -11
- package/src/core/scheduler/logs.ts +34 -3
- package/src/core/scheduler/mac.ts +174 -14
- package/src/core/scheduler/registry.ts +2 -2
- package/src/core/scheduler/windows.ts +19 -15
- package/src/core/secrets.ts +26 -19
- package/src/core/self-analysis.ts +75 -29
- package/src/core/shutdown.ts +90 -4
- package/src/core/structured-log.ts +89 -5
- package/src/core/telegram.ts +2 -2
- package/src/core/triage-worker.ts +7 -7
- package/src/core/triage.ts +2 -2
- package/src/core/usage-surface.ts +70 -0
- package/src/core/worktree-run.ts +199 -0
- package/src/core/worktree.ts +600 -0
- package/src/core/wrappers/bash.ts +248 -26
- package/src/db/capability-repo.ts +127 -10
- package/src/db/history-repo.ts +281 -40
- package/src/db/metrics-repo.ts +40 -13
- package/src/db/migrate.ts +57 -32
- package/src/db/recovery.ts +12 -5
- package/src/db/run-journal.ts +100 -13
- package/src/db/run-resume.ts +17 -1
- package/src/db/runs-repo.ts +147 -65
- package/src/db/schema.ts +134 -2
- package/src/db/templates-repo.ts +5 -3
- package/src/gui.tsx +438 -18
- package/src/history.ts +11 -4
- package/src/hook-output.ts +39 -0
- package/src/i18n.ts +12 -4
- package/src/index.ts +1902 -320
- package/src/notifications.ts +227 -47
- package/src/profiles.ts +88 -10
- package/src/rpc.ts +158 -0
- package/src/server.ts +201 -41
- package/src/settings.ts +125 -5
- package/src/shared/jobs-view.ts +3 -1
- package/src/task-transfer.ts +90 -6
- package/src/templates.ts +3 -3
- package/src/types.ts +23 -2
- package/src/workspaces.ts +37 -14
package/src/notifications.ts
CHANGED
|
@@ -9,13 +9,16 @@ import {
|
|
|
9
9
|
isShadowActive,
|
|
10
10
|
type TriageSettings,
|
|
11
11
|
type NotificationDedupSettings,
|
|
12
|
-
type NotificationEmbeddingSettings,
|
|
13
12
|
} from "./settings.js";
|
|
14
13
|
import {
|
|
15
14
|
buildAnalytics,
|
|
16
15
|
type AnalyticsRecord,
|
|
17
16
|
type ErrorAnalyticsRow,
|
|
18
17
|
} from "./core/analytics.js";
|
|
18
|
+
import {
|
|
19
|
+
formatBudgetAlertMessage,
|
|
20
|
+
type BudgetGateDecision,
|
|
21
|
+
} from "./core/budget.js";
|
|
19
22
|
import { getHistory } from "./db/history-repo.js";
|
|
20
23
|
import { getDb, withTransaction } from "./db/index.js";
|
|
21
24
|
import { sendTelegramMessage } from "./core/telegram.js";
|
|
@@ -30,8 +33,15 @@ import {
|
|
|
30
33
|
import type { TriageInput } from "./core/triage.js";
|
|
31
34
|
import { t } from "./i18n.js";
|
|
32
35
|
|
|
33
|
-
/**
|
|
34
|
-
|
|
36
|
+
/**
|
|
37
|
+
* Статус завершения задачи, который приходит из record-history.
|
|
38
|
+
*
|
|
39
|
+
* Три известных значения оставлены для автодополнения, `(string & {})`
|
|
40
|
+
* сохраняет возможность прийти произвольному статусу из внешней истории
|
|
41
|
+
* (иначе @typescript-eslint/no-redundant-type-constituents считает literals
|
|
42
|
+
* перекрытыми `string`). Поведение и пейлоады не меняются — это только тип.
|
|
43
|
+
*/
|
|
44
|
+
export type NotificationStatus = "success" | "error" | "timeout" | (string & {});
|
|
35
45
|
|
|
36
46
|
/** Содержимое уведомления. */
|
|
37
47
|
export interface NotificationPayload {
|
|
@@ -246,6 +256,19 @@ function validateWebhookUrl(url: string): URL {
|
|
|
246
256
|
return parsed;
|
|
247
257
|
}
|
|
248
258
|
|
|
259
|
+
/**
|
|
260
|
+
* Type guard для AbortError от fetch (DOMException): проверяем свойство `name`
|
|
261
|
+
* на границе внешнего API, не расширяя значение до `any`.
|
|
262
|
+
*/
|
|
263
|
+
function isAbortError(err: unknown): boolean {
|
|
264
|
+
return (
|
|
265
|
+
typeof err === "object" &&
|
|
266
|
+
err !== null &&
|
|
267
|
+
"name" in err &&
|
|
268
|
+
err.name === "AbortError"
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
|
|
249
272
|
/** Одна попытка POST. Бросает WebhookError с признаком retryable. */
|
|
250
273
|
async function postOnce(
|
|
251
274
|
parsed: URL,
|
|
@@ -270,8 +293,8 @@ async function postOnce(
|
|
|
270
293
|
retryable,
|
|
271
294
|
);
|
|
272
295
|
}
|
|
273
|
-
} catch (err:
|
|
274
|
-
if (err
|
|
296
|
+
} catch (err: unknown) {
|
|
297
|
+
if (isAbortError(err)) {
|
|
275
298
|
throw new WebhookError(
|
|
276
299
|
t("notify.error.webhookTimeout", { seconds: timeoutMs / 1000 }),
|
|
277
300
|
true,
|
|
@@ -419,7 +442,7 @@ async function deliverDetailed(
|
|
|
419
442
|
await sendWebhook(webhook.url, message, webhookOptionsFrom(config));
|
|
420
443
|
console.log("[agent-steward] Уведомление отправлено в webhook.");
|
|
421
444
|
results.push({ channel: "webhook", ok: true });
|
|
422
|
-
} catch (err:
|
|
445
|
+
} catch (err: unknown) {
|
|
423
446
|
const text = err instanceof Error ? err.message : String(err);
|
|
424
447
|
console.error(`[agent-steward] Webhook: ${text}`);
|
|
425
448
|
results.push({ channel: "webhook", ok: false, error: text });
|
|
@@ -445,7 +468,7 @@ async function deliverDetailed(
|
|
|
445
468
|
});
|
|
446
469
|
console.log("[agent-steward] Уведомление отправлено в Telegram.");
|
|
447
470
|
results.push({ channel: "telegram", ok: true });
|
|
448
|
-
} catch (err:
|
|
471
|
+
} catch (err: unknown) {
|
|
449
472
|
const text = err instanceof Error ? err.message : String(err);
|
|
450
473
|
console.error(`[agent-steward] Telegram: ${text}`);
|
|
451
474
|
results.push({ channel: "telegram", ok: false, error: text });
|
|
@@ -478,6 +501,49 @@ async function deliver(config: NotificationSettings, message: string): Promise<b
|
|
|
478
501
|
return results.some((item) => item.ok);
|
|
479
502
|
}
|
|
480
503
|
|
|
504
|
+
/** E-1.3: окно дедупа бюджетного алерта — не чаще одного раза в сутки. */
|
|
505
|
+
const BUDGET_ALERT_WINDOW_MINUTES = 24 * 60;
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* E-1.3: уведомление о превышении бюджета во все включённые каналы.
|
|
509
|
+
*
|
|
510
|
+
* Повторяющиеся алерты с той же причиной подавляются в течение 24 часов
|
|
511
|
+
* через общую таблицу `notification_dedup`. Ошибки доставки и БД только
|
|
512
|
+
* логируются: уведомление не должно ломать запуск задачи (fail-open).
|
|
513
|
+
*
|
|
514
|
+
* @returns true, если хотя бы один канал успешно доставил алерт.
|
|
515
|
+
*/
|
|
516
|
+
export async function notifyBudgetExceeded(
|
|
517
|
+
decision: BudgetGateDecision,
|
|
518
|
+
): Promise<boolean> {
|
|
519
|
+
if (decision.allowed) return false;
|
|
520
|
+
try {
|
|
521
|
+
const settings = await loadSettings();
|
|
522
|
+
const config = settings.notifications;
|
|
523
|
+
if (!config?.enabled) return false;
|
|
524
|
+
|
|
525
|
+
const dedup: NotificationDedupSettings = {
|
|
526
|
+
enabled: true,
|
|
527
|
+
windowMinutes: BUDGET_ALERT_WINDOW_MINUTES,
|
|
528
|
+
suppressDuplicates: true,
|
|
529
|
+
importantStatuses: [],
|
|
530
|
+
maxCount: 1,
|
|
531
|
+
};
|
|
532
|
+
const db = getDb();
|
|
533
|
+
const key = dedupKey("budget", decision.reason);
|
|
534
|
+
const { isDuplicate } = withTransaction(() =>
|
|
535
|
+
dedupReadOrCreate(db, key, "budget", decision.reason, dedup),
|
|
536
|
+
);
|
|
537
|
+
if (isDuplicate) return false;
|
|
538
|
+
|
|
539
|
+
return await deliver(config, formatBudgetAlertMessage(decision));
|
|
540
|
+
} catch (err) {
|
|
541
|
+
const text = err instanceof Error ? err.message : String(err);
|
|
542
|
+
console.error(`[agent-steward] Бюджетный алерт не отправлен: ${text}`);
|
|
543
|
+
return false;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
481
547
|
/**
|
|
482
548
|
* Уведомляет о завершении задачи во все включённые каналы.
|
|
483
549
|
*
|
|
@@ -505,6 +571,21 @@ export interface DedupRecord {
|
|
|
505
571
|
windowMinutes: number;
|
|
506
572
|
}
|
|
507
573
|
|
|
574
|
+
/**
|
|
575
|
+
* Строка таблицы `notification_dedup` в snake_case (как её возвращает
|
|
576
|
+
* `node:sqlite`). Граница БД: `SqliteStatement.get()` типизирован как `any`
|
|
577
|
+
* в src/db/index.ts, поэтому сужаем до доменного интерфейса сразу на чтении.
|
|
578
|
+
*/
|
|
579
|
+
interface DedupRow {
|
|
580
|
+
key: string;
|
|
581
|
+
task_name: string;
|
|
582
|
+
status: string;
|
|
583
|
+
count: number;
|
|
584
|
+
first_at: string;
|
|
585
|
+
last_at: string;
|
|
586
|
+
window_minutes: number | null;
|
|
587
|
+
}
|
|
588
|
+
|
|
508
589
|
/** Ключ дедупа: комбинация задачи и статуса. */
|
|
509
590
|
function dedupKey(taskName: string, status: string): string {
|
|
510
591
|
return (taskName + "|" + status).toLowerCase();
|
|
@@ -524,7 +605,7 @@ function dedupReadOrCreate(
|
|
|
524
605
|
const now = new Date().toISOString();
|
|
525
606
|
const row = db
|
|
526
607
|
.prepare("SELECT * FROM notification_dedup WHERE key = ?")
|
|
527
|
-
.get(key);
|
|
608
|
+
.get(key) as DedupRow | undefined;
|
|
528
609
|
|
|
529
610
|
if (!row) {
|
|
530
611
|
db.prepare(
|
|
@@ -611,15 +692,10 @@ function messageWithDedupCount(message: string, count: number): string {
|
|
|
611
692
|
* В будущем можно заменить на nomic-embed-text-v2-moe или другую модель.
|
|
612
693
|
*/
|
|
613
694
|
|
|
614
|
-
|
|
695
|
+
/** Строка `notification_embeddings`, достаточная для поиска похожего вектора. */
|
|
696
|
+
interface EmbeddingRow {
|
|
615
697
|
key: string;
|
|
616
|
-
|
|
617
|
-
status: string;
|
|
618
|
-
message_text: string;
|
|
619
|
-
embedding: number[];
|
|
620
|
-
dimension: number;
|
|
621
|
-
created_at: string;
|
|
622
|
-
window_minutes: number;
|
|
698
|
+
embedding_json: string;
|
|
623
699
|
}
|
|
624
700
|
|
|
625
701
|
/** Размерность вектора фиксирована: feature hashing, а не словарь сообщения. */
|
|
@@ -639,13 +715,43 @@ function embeddingKey(taskName: string, status: string): string {
|
|
|
639
715
|
return `emb:${(taskName + "|" + status).toLowerCase()}`;
|
|
640
716
|
}
|
|
641
717
|
|
|
642
|
-
/**
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
718
|
+
/**
|
|
719
|
+
* CJK-символы: хирагана, катакана, хань, совместимые идеограммы, хангыль.
|
|
720
|
+
* Регэксп без `g`, проверяется посимвольно.
|
|
721
|
+
*/
|
|
722
|
+
const CJK_CHAR_RE = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uac00-\ud7af]/;
|
|
723
|
+
|
|
724
|
+
/** Латиница, кириллица, цифры и диакритика — как раньше, но без вырезания CJK. */
|
|
725
|
+
const TOKEN_CHUNK_RE =
|
|
726
|
+
/[a-z\u00c0-\u024f\u0400-\u04ff0-9]+|[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uac00-\ud7af]+/g;
|
|
727
|
+
|
|
728
|
+
/**
|
|
729
|
+
* Простой токенизатор: слова, цифры, нижний регистр.
|
|
730
|
+
*
|
|
731
|
+
* B14: CJK-блоки больше не вырезаются. Иероглифы не разделены пробелами,
|
|
732
|
+
* поэтому слово режется на перекрывающиеся биграммы («任务失败» → «任务»,
|
|
733
|
+
* «务失», «失败»); одиночный иероглиф остаётся униграммой. Это даёт
|
|
734
|
+
* ненулевой вектор для `zh`/`ja`/`ko` и работает без словарей и
|
|
735
|
+
* `Intl.Segmenter`, одинаково на всех платформах.
|
|
736
|
+
*/
|
|
737
|
+
export function tokenize(text: string): string[] {
|
|
738
|
+
const tokens: string[] = [];
|
|
739
|
+
for (const match of text.toLowerCase().matchAll(TOKEN_CHUNK_RE)) {
|
|
740
|
+
const chunk = match[0];
|
|
741
|
+
if (CJK_CHAR_RE.test(chunk[0])) {
|
|
742
|
+
const chars = Array.from(chunk);
|
|
743
|
+
if (chars.length === 1) {
|
|
744
|
+
tokens.push(chars[0]);
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
for (let i = 0; i < chars.length - 1; i++) {
|
|
748
|
+
tokens.push(chars[i] + chars[i + 1]);
|
|
749
|
+
}
|
|
750
|
+
} else {
|
|
751
|
+
tokens.push(chunk);
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
return tokens;
|
|
649
755
|
}
|
|
650
756
|
|
|
651
757
|
/**
|
|
@@ -659,9 +765,9 @@ function tokenize(text: string): string[] {
|
|
|
659
765
|
* Вес — 1 + log(tf), L2-нормализация; знак из старшего бита хеша снижает
|
|
660
766
|
* влияние коллизий.
|
|
661
767
|
*/
|
|
662
|
-
function textToVector(text: string): number[] {
|
|
768
|
+
export function textToVector(text: string): number[] {
|
|
663
769
|
const tokens = tokenize(text);
|
|
664
|
-
const vec: number[] = new Array(EMBEDDING_DIMENSION).fill(0);
|
|
770
|
+
const vec: number[] = new Array<number>(EMBEDDING_DIMENSION).fill(0);
|
|
665
771
|
if (tokens.length === 0) return vec;
|
|
666
772
|
|
|
667
773
|
const counts = new Map<string, number>();
|
|
@@ -699,6 +805,26 @@ function cosineSimilarity(a: number[], b: number[]): number {
|
|
|
699
805
|
return dot / denom;
|
|
700
806
|
}
|
|
701
807
|
|
|
808
|
+
/**
|
|
809
|
+
* Безопасный разбор JSON-вектора из БД — граница внешних данных.
|
|
810
|
+
* Возвращает null для битых/нечисловых записей вместо `any` из JSON.parse.
|
|
811
|
+
*/
|
|
812
|
+
function parseNumberArray(json: string): number[] | null {
|
|
813
|
+
let value: unknown;
|
|
814
|
+
try {
|
|
815
|
+
value = JSON.parse(json);
|
|
816
|
+
} catch {
|
|
817
|
+
return null;
|
|
818
|
+
}
|
|
819
|
+
if (!Array.isArray(value)) return null;
|
|
820
|
+
const result: number[] = [];
|
|
821
|
+
for (const item of value) {
|
|
822
|
+
if (typeof item !== "number") return null;
|
|
823
|
+
result.push(item);
|
|
824
|
+
}
|
|
825
|
+
return result;
|
|
826
|
+
}
|
|
827
|
+
|
|
702
828
|
/**
|
|
703
829
|
* Проверяет, есть ли в БД вектор, достаточно похожий на text.
|
|
704
830
|
* Сравниваются только векторы той же задачи и того же статуса: иначе успех
|
|
@@ -721,24 +847,18 @@ function embeddingExists(
|
|
|
721
847
|
"WHERE task_name = ? AND status = ? AND created_at >= ? " +
|
|
722
848
|
"ORDER BY created_at DESC LIMIT 500",
|
|
723
849
|
)
|
|
724
|
-
.all(taskName, status, since) as
|
|
725
|
-
key: string;
|
|
726
|
-
embedding_json: string;
|
|
727
|
-
}[];
|
|
850
|
+
.all(taskName, status, since) as EmbeddingRow[];
|
|
728
851
|
const vec = textToVector(message);
|
|
729
852
|
let bestKey = "";
|
|
730
853
|
let bestSim = 0;
|
|
731
854
|
for (const row of rows) {
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
}
|
|
740
|
-
} catch {
|
|
741
|
-
// пропускаем битую запись
|
|
855
|
+
const emb = parseNumberArray(row.embedding_json);
|
|
856
|
+
if (emb === null) continue;
|
|
857
|
+
if (emb.length !== vec.length) continue;
|
|
858
|
+
const sim = cosineSimilarity(vec, emb);
|
|
859
|
+
if (sim > bestSim) {
|
|
860
|
+
bestSim = sim;
|
|
861
|
+
bestKey = row.key;
|
|
742
862
|
}
|
|
743
863
|
}
|
|
744
864
|
if (bestSim >= threshold) return { found: true, key: bestKey };
|
|
@@ -838,7 +958,7 @@ export async function notifyTaskCompletion(
|
|
|
838
958
|
);
|
|
839
959
|
// Injected scheduler может быть асинхронным — не оставляем rejection.
|
|
840
960
|
if (job && typeof (job as PromiseLike<unknown>).then === "function") {
|
|
841
|
-
void Promise.resolve(job).catch((err:
|
|
961
|
+
void Promise.resolve(job).catch((err: unknown) => {
|
|
842
962
|
console.error(
|
|
843
963
|
`[agent-steward] Ошибка фонового триажа: ${
|
|
844
964
|
err instanceof Error ? err.message : String(err)
|
|
@@ -846,7 +966,7 @@ export async function notifyTaskCompletion(
|
|
|
846
966
|
);
|
|
847
967
|
});
|
|
848
968
|
}
|
|
849
|
-
} catch (err:
|
|
969
|
+
} catch (err: unknown) {
|
|
850
970
|
console.error(
|
|
851
971
|
`[agent-steward] Не удалось запустить фоновый триаж: ${
|
|
852
972
|
err instanceof Error ? err.message : String(err)
|
|
@@ -953,7 +1073,7 @@ export async function notifyTaskCompletion(
|
|
|
953
1073
|
}
|
|
954
1074
|
}
|
|
955
1075
|
await deliver(config, finalMessage);
|
|
956
|
-
} catch (err:
|
|
1076
|
+
} catch (err: unknown) {
|
|
957
1077
|
// Уведомление не должно ломать запись истории и саму задачу.
|
|
958
1078
|
console.error(
|
|
959
1079
|
`[agent-steward] Ошибка подготовки уведомления: ${
|
|
@@ -988,7 +1108,7 @@ export async function notifyMatrixCompletion(
|
|
|
988
1108
|
}
|
|
989
1109
|
|
|
990
1110
|
await deliver(config, formatMatrixMessage(info));
|
|
991
|
-
} catch (err:
|
|
1111
|
+
} catch (err: unknown) {
|
|
992
1112
|
console.error(
|
|
993
1113
|
`[agent-steward] Ошибка уведомления о матрице: ${
|
|
994
1114
|
err instanceof Error ? err.message : String(err)
|
|
@@ -1063,7 +1183,7 @@ export async function notifyStuckMatrix(stuck: StuckMatrixClone): Promise<boolea
|
|
|
1063
1183
|
if (!config.matrix?.enabled) return false;
|
|
1064
1184
|
if (!isTaskAllowed(stuck.parentName, config.filters)) return false;
|
|
1065
1185
|
return await deliver(config, formatStuckMatrixMessage(stuck));
|
|
1066
|
-
} catch (err:
|
|
1186
|
+
} catch (err: unknown) {
|
|
1067
1187
|
console.error(
|
|
1068
1188
|
`[agent-steward] Ошибка уведомления о зависшей матрице: ${
|
|
1069
1189
|
err instanceof Error ? err.message : String(err)
|
|
@@ -1238,7 +1358,7 @@ export async function sendDigestNow(
|
|
|
1238
1358
|
});
|
|
1239
1359
|
}
|
|
1240
1360
|
return { success: true, message: t("notify.ok.digestSent") };
|
|
1241
|
-
} catch (err:
|
|
1361
|
+
} catch (err: unknown) {
|
|
1242
1362
|
return {
|
|
1243
1363
|
success: false,
|
|
1244
1364
|
message: err instanceof Error ? err.message : String(err),
|
|
@@ -1262,7 +1382,7 @@ export async function maybeSendDigest(now: Date = new Date()): Promise<boolean>
|
|
|
1262
1382
|
}
|
|
1263
1383
|
console.error(`[agent-steward] Дайджест не отправлен: ${result.message}`);
|
|
1264
1384
|
return false;
|
|
1265
|
-
} catch (err:
|
|
1385
|
+
} catch (err: unknown) {
|
|
1266
1386
|
console.error(
|
|
1267
1387
|
`[agent-steward] Ошибка дайджеста: ${
|
|
1268
1388
|
err instanceof Error ? err.message : String(err)
|
|
@@ -1337,10 +1457,70 @@ export async function sendTestNotification(
|
|
|
1337
1457
|
success: failed.length === 0 && sent.length > 0,
|
|
1338
1458
|
message: parts.join(" ") || t("notify.error.testNotSent"),
|
|
1339
1459
|
};
|
|
1340
|
-
} catch (err:
|
|
1460
|
+
} catch (err: unknown) {
|
|
1461
|
+
return {
|
|
1462
|
+
success: false,
|
|
1463
|
+
message: err instanceof Error ? err.message : String(err),
|
|
1464
|
+
};
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
/**
|
|
1469
|
+
* Отправляет отчёт о баге во все включённые каналы (webhook/telegram/native).
|
|
1470
|
+
* Используется агент-инструментом `report_bug`: пользователь плагина описывает
|
|
1471
|
+
* проблему через агент-чат, а отчёт с логами и аналитикой уходит разработчику
|
|
1472
|
+
* (владельцу настроенного бота/вебхука).
|
|
1473
|
+
*/
|
|
1474
|
+
export async function sendBugReport(
|
|
1475
|
+
report: string,
|
|
1476
|
+
channel: "all" | NotificationChannel = "all",
|
|
1477
|
+
): Promise<{
|
|
1478
|
+
success: boolean;
|
|
1479
|
+
message: string;
|
|
1480
|
+
results: ChannelDeliveryResult[];
|
|
1481
|
+
}> {
|
|
1482
|
+
try {
|
|
1483
|
+
const settings = await loadSettings();
|
|
1484
|
+
const config = settings.notifications;
|
|
1485
|
+
if (!config?.enabled) {
|
|
1486
|
+
return {
|
|
1487
|
+
success: false,
|
|
1488
|
+
message: t("notify.error.testDisabled"),
|
|
1489
|
+
results: [],
|
|
1490
|
+
};
|
|
1491
|
+
}
|
|
1492
|
+
|
|
1493
|
+
const enabled: NotificationChannel[] = [];
|
|
1494
|
+
if (config.webhook?.enabled && config.webhook.url.trim()) enabled.push("webhook");
|
|
1495
|
+
if (config.telegram?.enabled) enabled.push("telegram");
|
|
1496
|
+
if (config.native?.enabled) enabled.push("native");
|
|
1497
|
+
if (enabled.length === 0) {
|
|
1498
|
+
return {
|
|
1499
|
+
success: false,
|
|
1500
|
+
message: t("notify.error.testNoChannels"),
|
|
1501
|
+
results: [],
|
|
1502
|
+
};
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
const results = await deliverDetailed(
|
|
1506
|
+
config,
|
|
1507
|
+
report,
|
|
1508
|
+
channel === "all" ? undefined : channel,
|
|
1509
|
+
);
|
|
1510
|
+
const sent = results.filter((item) => item.ok).map((item) => item.channel);
|
|
1511
|
+
const failed = results.filter((item) => !item.ok);
|
|
1512
|
+
return {
|
|
1513
|
+
success: failed.length === 0 && sent.length > 0,
|
|
1514
|
+
message: sent.length > 0
|
|
1515
|
+
? `Отправлено в каналы: ${sent.join(", ")}`
|
|
1516
|
+
: t("notify.error.testNotSent"),
|
|
1517
|
+
results,
|
|
1518
|
+
};
|
|
1519
|
+
} catch (err: unknown) {
|
|
1341
1520
|
return {
|
|
1342
1521
|
success: false,
|
|
1343
1522
|
message: err instanceof Error ? err.message : String(err),
|
|
1523
|
+
results: [],
|
|
1344
1524
|
};
|
|
1345
1525
|
}
|
|
1346
1526
|
}
|
package/src/profiles.ts
CHANGED
|
@@ -194,17 +194,83 @@ function profileMetaFile(name: string): string {
|
|
|
194
194
|
return path.join(getProfileDir(name), "profile.json");
|
|
195
195
|
}
|
|
196
196
|
|
|
197
|
+
/**
|
|
198
|
+
* Порты, зарезервированные за профилем default: основной (PREFERRED_PORT
|
|
199
|
+
* в server.ts) и запасной. У default может не быть profile.json, поэтому
|
|
200
|
+
* в listProfiles() его порт — null, и раньше аллокатор выдавал 3782 второму
|
|
201
|
+
* профилю: два дашборда дрались за один порт.
|
|
202
|
+
*/
|
|
203
|
+
const DEFAULT_PROFILE_PORTS = new Set([3782, 4782]);
|
|
204
|
+
const FIRST_PROFILE_PORT = 3783;
|
|
205
|
+
const LAST_PORT = 65535;
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Свободный порт для профиля без вызова listProfiles()/readProfileMeta()
|
|
209
|
+
* (иначе рекурсия: allocateProfilePort -> listProfiles -> readProfileMeta).
|
|
210
|
+
* Сканирует profile.json всех профилей напрямую с файловой системы.
|
|
211
|
+
* Возвращает null, если свободных портов не осталось.
|
|
212
|
+
*/
|
|
213
|
+
function findFreeProfilePort(): number | null {
|
|
214
|
+
const used = new Set<number>(DEFAULT_PROFILE_PORTS);
|
|
215
|
+
const fromEnv = Number(process.env.OPENCODE_SCHEDULER_PORT);
|
|
216
|
+
if (Number.isFinite(fromEnv) && fromEnv >= 1 && fromEnv <= LAST_PORT) {
|
|
217
|
+
used.add(Math.floor(fromEnv));
|
|
218
|
+
}
|
|
219
|
+
const profilesRoot = path.join(getBasePluginDir(), "profiles");
|
|
220
|
+
let entries: fs.Dirent[] = [];
|
|
221
|
+
try {
|
|
222
|
+
entries = fs.readdirSync(profilesRoot, { withFileTypes: true });
|
|
223
|
+
} catch {
|
|
224
|
+
// profiles/ ещё нет — учитываем только зарезервированные и env.
|
|
225
|
+
}
|
|
226
|
+
for (const entry of entries) {
|
|
227
|
+
if (!entry.isDirectory()) continue;
|
|
228
|
+
try {
|
|
229
|
+
const raw = fs.readFileSync(
|
|
230
|
+
path.join(profilesRoot, entry.name, "profile.json"),
|
|
231
|
+
"utf8",
|
|
232
|
+
);
|
|
233
|
+
const parsed = JSON.parse(raw) as Partial<ProfileMeta>;
|
|
234
|
+
const port = Number(parsed?.port);
|
|
235
|
+
if (Number.isFinite(port) && port >= 1 && port <= LAST_PORT) {
|
|
236
|
+
used.add(Math.floor(port));
|
|
237
|
+
}
|
|
238
|
+
} catch {
|
|
239
|
+
// Битый/отсутствующий profile.json — игнорируем.
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
for (let port = FIRST_PROFILE_PORT; port <= LAST_PORT; port += 1) {
|
|
243
|
+
if (!used.has(port)) return port;
|
|
244
|
+
}
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
|
|
197
248
|
/** Читает profile.json профиля (или null, если файла нет/он битый). */
|
|
198
249
|
export function readProfileMeta(name: string): ProfileMeta | null {
|
|
199
250
|
try {
|
|
200
|
-
const
|
|
251
|
+
const file = profileMetaFile(name);
|
|
252
|
+
const raw = fs.readFileSync(file, "utf8");
|
|
201
253
|
const parsed = JSON.parse(raw) as Partial<ProfileMeta>;
|
|
202
254
|
const profileName = sanitizeProfileName(parsed?.name ?? name);
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
255
|
+
let port = Number(parsed?.port);
|
|
256
|
+
port = Number.isFinite(port) && port >= 1 && port <= LAST_PORT ? Math.floor(port) : 0;
|
|
257
|
+
|
|
258
|
+
// B4.3 (QA #3): профили, созданные до B4.2, могли получить порт default
|
|
259
|
+
// (3782/4782). Он зарезервирован — два дашборда дрались бы за один порт.
|
|
260
|
+
// Мигрируем такой профиль на свободный порт и перезаписываем profile.json.
|
|
261
|
+
// Идемпотентно: после первой миграции порт уже не из DEFAULT_PROFILE_PORTS.
|
|
262
|
+
if (name !== DEFAULT_PROFILE && port > 0 && DEFAULT_PROFILE_PORTS.has(port)) {
|
|
263
|
+
const free = findFreeProfilePort();
|
|
264
|
+
if (free === null) return { name: profileName, port: 0 };
|
|
265
|
+
fs.writeFileSync(
|
|
266
|
+
file,
|
|
267
|
+
JSON.stringify({ ...parsed, name: profileName, port: free }, null, 2),
|
|
268
|
+
"utf8",
|
|
269
|
+
);
|
|
270
|
+
port = free;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
return { name: profileName, port };
|
|
208
274
|
} catch {
|
|
209
275
|
return null;
|
|
210
276
|
}
|
|
@@ -253,16 +319,28 @@ export function listProfiles(): ProfileInfo[] {
|
|
|
253
319
|
});
|
|
254
320
|
}
|
|
255
321
|
|
|
256
|
-
/**
|
|
322
|
+
/**
|
|
323
|
+
* Свободный порт для нового профиля (B4.2).
|
|
324
|
+
*
|
|
325
|
+
* Исключает зарезервированные порты default, порты из profile.json всех
|
|
326
|
+
* профилей и порт, заданный через OPENCODE_SCHEDULER_PORT. Сканирует диапазон
|
|
327
|
+
* от 3783 до 65535 и берёт первый не занятый — прежняя формула
|
|
328
|
+
* `3782 + used.size` могла выдать уже занятый порт (например, при
|
|
329
|
+
* зарезервированном 3783 и одном профиле).
|
|
330
|
+
*/
|
|
257
331
|
function allocateProfilePort(): number {
|
|
258
|
-
const used = new Set<number>();
|
|
332
|
+
const used = new Set<number>(DEFAULT_PROFILE_PORTS);
|
|
259
333
|
for (const profile of listProfiles()) {
|
|
260
334
|
if (profile.port) used.add(profile.port);
|
|
261
335
|
}
|
|
262
|
-
|
|
336
|
+
const fromEnv = Number(process.env.OPENCODE_SCHEDULER_PORT);
|
|
337
|
+
if (Number.isFinite(fromEnv) && fromEnv >= 1 && fromEnv <= LAST_PORT) {
|
|
338
|
+
used.add(Math.floor(fromEnv));
|
|
339
|
+
}
|
|
340
|
+
for (let port = FIRST_PROFILE_PORT; port <= LAST_PORT; port += 1) {
|
|
263
341
|
if (!used.has(port)) return port;
|
|
264
342
|
}
|
|
265
|
-
|
|
343
|
+
throw new Error("Не удалось выделить порт профилю: свободных портов не осталось.");
|
|
266
344
|
}
|
|
267
345
|
|
|
268
346
|
/**
|