agent-steward 0.0.5 → 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.
Files changed (191) hide show
  1. package/CHANGELOG.md +176 -1
  2. package/README.md +9 -7
  3. package/ROADMAP-STRATEGY.md +5 -5
  4. package/ROADMAP.md +107 -17
  5. package/dist/cli.js +5 -0
  6. package/dist/core/analytics.d.ts +6 -0
  7. package/dist/core/analytics.d.ts.map +1 -1
  8. package/dist/core/analytics.js +20 -3
  9. package/dist/core/audit.d.ts +6 -0
  10. package/dist/core/audit.d.ts.map +1 -1
  11. package/dist/core/audit.js +24 -0
  12. package/dist/core/budget.d.ts +118 -0
  13. package/dist/core/budget.d.ts.map +1 -0
  14. package/dist/core/budget.js +206 -0
  15. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  16. package/dist/core/cron-to-schtasks.js +38 -0
  17. package/dist/core/dry-run.d.ts +26 -1
  18. package/dist/core/dry-run.d.ts.map +1 -1
  19. package/dist/core/dry-run.js +199 -8
  20. package/dist/core/feedback.d.ts +192 -0
  21. package/dist/core/feedback.d.ts.map +1 -0
  22. package/dist/core/feedback.js +426 -0
  23. package/dist/core/gate-integrity.d.ts +36 -0
  24. package/dist/core/gate-integrity.d.ts.map +1 -1
  25. package/dist/core/gate-integrity.js +144 -1
  26. package/dist/core/local-ai.d.ts.map +1 -1
  27. package/dist/core/local-ai.js +7 -3
  28. package/dist/core/matrix.d.ts +8 -0
  29. package/dist/core/matrix.d.ts.map +1 -1
  30. package/dist/core/matrix.js +57 -2
  31. package/dist/core/mission.d.ts +20 -0
  32. package/dist/core/mission.d.ts.map +1 -1
  33. package/dist/core/mission.js +45 -5
  34. package/dist/core/opencode-models.d.ts +2 -2
  35. package/dist/core/opencode-models.d.ts.map +1 -1
  36. package/dist/core/opencode-models.js +28 -21
  37. package/dist/core/opencode-usage.d.ts +35 -0
  38. package/dist/core/opencode-usage.d.ts.map +1 -0
  39. package/dist/core/opencode-usage.js +132 -0
  40. package/dist/core/pipeline-io.d.ts +1 -1
  41. package/dist/core/pipeline-io.d.ts.map +1 -1
  42. package/dist/core/pipeline-io.js +26 -12
  43. package/dist/core/pipeline-map.d.ts +6 -0
  44. package/dist/core/pipeline-map.d.ts.map +1 -1
  45. package/dist/core/pipeline-map.js +12 -0
  46. package/dist/core/ps-wrapper.d.ts +10 -2
  47. package/dist/core/ps-wrapper.d.ts.map +1 -1
  48. package/dist/core/ps-wrapper.js +176 -5
  49. package/dist/core/record-history.d.ts.map +1 -1
  50. package/dist/core/record-history.js +76 -4
  51. package/dist/core/run-mode.d.ts +12 -0
  52. package/dist/core/run-mode.d.ts.map +1 -0
  53. package/dist/core/run-mode.js +17 -0
  54. package/dist/core/scheduler/logs.d.ts +4 -0
  55. package/dist/core/scheduler/logs.d.ts.map +1 -1
  56. package/dist/core/scheduler/logs.js +25 -1
  57. package/dist/core/secrets.d.ts.map +1 -1
  58. package/dist/core/secrets.js +18 -8
  59. package/dist/core/self-analysis.d.ts +32 -2
  60. package/dist/core/self-analysis.d.ts.map +1 -1
  61. package/dist/core/self-analysis.js +38 -27
  62. package/dist/core/shutdown.d.ts +33 -2
  63. package/dist/core/shutdown.d.ts.map +1 -1
  64. package/dist/core/shutdown.js +58 -2
  65. package/dist/core/structured-log.d.ts +30 -0
  66. package/dist/core/structured-log.d.ts.map +1 -1
  67. package/dist/core/structured-log.js +37 -0
  68. package/dist/core/usage-surface.d.ts +25 -0
  69. package/dist/core/usage-surface.d.ts.map +1 -0
  70. package/dist/core/usage-surface.js +41 -0
  71. package/dist/core/wrappers/bash.d.ts +2 -0
  72. package/dist/core/wrappers/bash.d.ts.map +1 -1
  73. package/dist/core/wrappers/bash.js +58 -6
  74. package/dist/db/history-repo.d.ts +32 -0
  75. package/dist/db/history-repo.d.ts.map +1 -1
  76. package/dist/db/history-repo.js +85 -7
  77. package/dist/db/metrics-repo.d.ts +20 -2
  78. package/dist/db/metrics-repo.d.ts.map +1 -1
  79. package/dist/db/metrics-repo.js +33 -11
  80. package/dist/db/migrate.d.ts.map +1 -1
  81. package/dist/db/migrate.js +37 -17
  82. package/dist/db/recovery.d.ts +3 -1
  83. package/dist/db/recovery.d.ts.map +1 -1
  84. package/dist/db/recovery.js +9 -4
  85. package/dist/db/runs-repo.d.ts.map +1 -1
  86. package/dist/db/runs-repo.js +71 -56
  87. package/dist/db/schema.d.ts +2 -2
  88. package/dist/db/schema.d.ts.map +1 -1
  89. package/dist/db/schema.js +70 -1
  90. package/dist/db/templates-repo.d.ts +2 -2
  91. package/dist/db/templates-repo.d.ts.map +1 -1
  92. package/dist/db/templates-repo.js +5 -3
  93. package/dist/history.d.ts +6 -1
  94. package/dist/history.d.ts.map +1 -1
  95. package/dist/history.js +4 -2
  96. package/dist/hook-output.d.ts +2 -0
  97. package/dist/hook-output.d.ts.map +1 -0
  98. package/dist/hook-output.js +31 -0
  99. package/dist/index.d.ts +247 -53
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +999 -211
  102. package/dist/notifications.d.ts +31 -2
  103. package/dist/notifications.d.ts.map +1 -1
  104. package/dist/notifications.js +132 -13
  105. package/dist/profiles.d.ts.map +1 -1
  106. package/dist/profiles.js +66 -15
  107. package/dist/rpc.d.ts +108 -0
  108. package/dist/rpc.d.ts.map +1 -1
  109. package/dist/rpc.js +28 -0
  110. package/dist/server.d.ts +17 -2
  111. package/dist/server.d.ts.map +1 -1
  112. package/dist/server.js +77 -12
  113. package/dist/settings.d.ts +42 -0
  114. package/dist/settings.d.ts.map +1 -1
  115. package/dist/settings.js +82 -0
  116. package/dist/task-transfer.d.ts +5 -0
  117. package/dist/task-transfer.d.ts.map +1 -1
  118. package/dist/task-transfer.js +48 -3
  119. package/dist/templates.d.ts +2 -2
  120. package/dist/templates.d.ts.map +1 -1
  121. package/dist/templates.js +3 -3
  122. package/dist/types.d.ts +22 -2
  123. package/dist/types.d.ts.map +1 -1
  124. package/dist/workspaces.d.ts.map +1 -1
  125. package/dist/workspaces.js +34 -11
  126. package/docs/ARCHITECTURE.md +49 -12
  127. package/docs/COMPATIBILITY.md +2 -2
  128. package/docs/EXECUTION-LOOP.md +6 -3
  129. package/docs/FEATURES.md +65 -4
  130. package/docs/FEATURES.zh.md +45 -2
  131. package/docs/QA-A2-GUI-TUI.md +205 -0
  132. package/docs/README.ru.md +3 -3
  133. package/docs/README.zh.md +2 -2
  134. package/gui-experimental.cjs +9 -9
  135. package/locales/en.json +42 -3
  136. package/locales/ru.json +42 -3
  137. package/locales/zh.json +42 -3
  138. package/package.json +15 -2
  139. package/scripts/check-eslint-baseline.mjs +139 -0
  140. package/scripts/gen-test-plan-counters.mjs +117 -0
  141. package/scripts/github-ci-fetch.ps1 +37 -0
  142. package/scripts/pl-commit.ps1 +112 -0
  143. package/scripts/qa-a2-commit.ps1 +104 -0
  144. package/scripts/test-home.mjs +26 -2
  145. package/skills/scheduled-job-best-practices/SKILL.md +95 -1
  146. package/skills/scheduled-job-best-practices/references/recipes.md +139 -0
  147. package/src/cli.ts +5 -0
  148. package/src/core/analytics.ts +27 -4
  149. package/src/core/audit.ts +25 -0
  150. package/src/core/budget.ts +340 -0
  151. package/src/core/cron-to-schtasks.ts +42 -0
  152. package/src/core/dry-run.ts +233 -10
  153. package/src/core/feedback.ts +582 -0
  154. package/src/core/gate-integrity.ts +171 -1
  155. package/src/core/local-ai.ts +7 -3
  156. package/src/core/matrix.ts +63 -2
  157. package/src/core/mission.ts +51 -5
  158. package/src/core/opencode-models.ts +30 -21
  159. package/src/core/opencode-usage.ts +182 -0
  160. package/src/core/pipeline-io.ts +28 -11
  161. package/src/core/pipeline-map.ts +19 -0
  162. package/src/core/ps-wrapper.ts +173 -4
  163. package/src/core/record-history.ts +94 -4
  164. package/src/core/run-mode.ts +19 -0
  165. package/src/core/scheduler/logs.ts +32 -1
  166. package/src/core/secrets.ts +18 -11
  167. package/src/core/self-analysis.ts +75 -29
  168. package/src/core/shutdown.ts +90 -4
  169. package/src/core/structured-log.ts +67 -0
  170. package/src/core/usage-surface.ts +70 -0
  171. package/src/core/wrappers/bash.ts +60 -5
  172. package/src/db/history-repo.ts +153 -19
  173. package/src/db/metrics-repo.ts +38 -11
  174. package/src/db/migrate.ts +57 -32
  175. package/src/db/recovery.ts +10 -4
  176. package/src/db/runs-repo.ts +113 -61
  177. package/src/db/schema.ts +70 -1
  178. package/src/db/templates-repo.ts +5 -3
  179. package/src/gui.tsx +261 -5
  180. package/src/history.ts +10 -3
  181. package/src/hook-output.ts +39 -0
  182. package/src/index.ts +1407 -345
  183. package/src/notifications.ts +189 -39
  184. package/src/profiles.ts +72 -16
  185. package/src/rpc.ts +30 -0
  186. package/src/server.ts +107 -23
  187. package/src/settings.ts +120 -0
  188. package/src/task-transfer.ts +59 -6
  189. package/src/templates.ts +3 -3
  190. package/src/types.ts +23 -2
  191. package/src/workspaces.ts +37 -14
@@ -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
- /** Статус завершения задачи, который приходит из record-history. */
34
- export type NotificationStatus = "success" | "error" | "timeout" | string;
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: any) {
274
- if (err?.name === "AbortError") {
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: any) {
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: any) {
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
- interface EmbeddingRecord {
695
+ /** Строка `notification_embeddings`, достаточная для поиска похожего вектора. */
696
+ interface EmbeddingRow {
615
697
  key: string;
616
- task_name: string;
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, а не словарь сообщения. */
@@ -691,7 +767,7 @@ export function tokenize(text: string): string[] {
691
767
  */
692
768
  export function textToVector(text: string): number[] {
693
769
  const tokens = tokenize(text);
694
- const vec: number[] = new Array(EMBEDDING_DIMENSION).fill(0);
770
+ const vec: number[] = new Array<number>(EMBEDDING_DIMENSION).fill(0);
695
771
  if (tokens.length === 0) return vec;
696
772
 
697
773
  const counts = new Map<string, number>();
@@ -729,6 +805,26 @@ function cosineSimilarity(a: number[], b: number[]): number {
729
805
  return dot / denom;
730
806
  }
731
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
+
732
828
  /**
733
829
  * Проверяет, есть ли в БД вектор, достаточно похожий на text.
734
830
  * Сравниваются только векторы той же задачи и того же статуса: иначе успех
@@ -751,24 +847,18 @@ function embeddingExists(
751
847
  "WHERE task_name = ? AND status = ? AND created_at >= ? " +
752
848
  "ORDER BY created_at DESC LIMIT 500",
753
849
  )
754
- .all(taskName, status, since) as {
755
- key: string;
756
- embedding_json: string;
757
- }[];
850
+ .all(taskName, status, since) as EmbeddingRow[];
758
851
  const vec = textToVector(message);
759
852
  let bestKey = "";
760
853
  let bestSim = 0;
761
854
  for (const row of rows) {
762
- try {
763
- const emb: number[] = JSON.parse(row.embedding_json);
764
- if (!Array.isArray(emb) || emb.length !== vec.length) continue;
765
- const sim = cosineSimilarity(vec, emb);
766
- if (sim > bestSim) {
767
- bestSim = sim;
768
- bestKey = row.key;
769
- }
770
- } catch {
771
- // пропускаем битую запись
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;
772
862
  }
773
863
  }
774
864
  if (bestSim >= threshold) return { found: true, key: bestKey };
@@ -868,7 +958,7 @@ export async function notifyTaskCompletion(
868
958
  );
869
959
  // Injected scheduler может быть асинхронным — не оставляем rejection.
870
960
  if (job && typeof (job as PromiseLike<unknown>).then === "function") {
871
- void Promise.resolve(job).catch((err: any) => {
961
+ void Promise.resolve(job).catch((err: unknown) => {
872
962
  console.error(
873
963
  `[agent-steward] Ошибка фонового триажа: ${
874
964
  err instanceof Error ? err.message : String(err)
@@ -876,7 +966,7 @@ export async function notifyTaskCompletion(
876
966
  );
877
967
  });
878
968
  }
879
- } catch (err: any) {
969
+ } catch (err: unknown) {
880
970
  console.error(
881
971
  `[agent-steward] Не удалось запустить фоновый триаж: ${
882
972
  err instanceof Error ? err.message : String(err)
@@ -983,7 +1073,7 @@ export async function notifyTaskCompletion(
983
1073
  }
984
1074
  }
985
1075
  await deliver(config, finalMessage);
986
- } catch (err: any) {
1076
+ } catch (err: unknown) {
987
1077
  // Уведомление не должно ломать запись истории и саму задачу.
988
1078
  console.error(
989
1079
  `[agent-steward] Ошибка подготовки уведомления: ${
@@ -1018,7 +1108,7 @@ export async function notifyMatrixCompletion(
1018
1108
  }
1019
1109
 
1020
1110
  await deliver(config, formatMatrixMessage(info));
1021
- } catch (err: any) {
1111
+ } catch (err: unknown) {
1022
1112
  console.error(
1023
1113
  `[agent-steward] Ошибка уведомления о матрице: ${
1024
1114
  err instanceof Error ? err.message : String(err)
@@ -1093,7 +1183,7 @@ export async function notifyStuckMatrix(stuck: StuckMatrixClone): Promise<boolea
1093
1183
  if (!config.matrix?.enabled) return false;
1094
1184
  if (!isTaskAllowed(stuck.parentName, config.filters)) return false;
1095
1185
  return await deliver(config, formatStuckMatrixMessage(stuck));
1096
- } catch (err: any) {
1186
+ } catch (err: unknown) {
1097
1187
  console.error(
1098
1188
  `[agent-steward] Ошибка уведомления о зависшей матрице: ${
1099
1189
  err instanceof Error ? err.message : String(err)
@@ -1268,7 +1358,7 @@ export async function sendDigestNow(
1268
1358
  });
1269
1359
  }
1270
1360
  return { success: true, message: t("notify.ok.digestSent") };
1271
- } catch (err: any) {
1361
+ } catch (err: unknown) {
1272
1362
  return {
1273
1363
  success: false,
1274
1364
  message: err instanceof Error ? err.message : String(err),
@@ -1292,7 +1382,7 @@ export async function maybeSendDigest(now: Date = new Date()): Promise<boolean>
1292
1382
  }
1293
1383
  console.error(`[agent-steward] Дайджест не отправлен: ${result.message}`);
1294
1384
  return false;
1295
- } catch (err: any) {
1385
+ } catch (err: unknown) {
1296
1386
  console.error(
1297
1387
  `[agent-steward] Ошибка дайджеста: ${
1298
1388
  err instanceof Error ? err.message : String(err)
@@ -1367,10 +1457,70 @@ export async function sendTestNotification(
1367
1457
  success: failed.length === 0 && sent.length > 0,
1368
1458
  message: parts.join(" ") || t("notify.error.testNotSent"),
1369
1459
  };
1370
- } catch (err: any) {
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) {
1371
1520
  return {
1372
1521
  success: false,
1373
1522
  message: err instanceof Error ? err.message : String(err),
1523
+ results: [],
1374
1524
  };
1375
1525
  }
1376
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 raw = fs.readFileSync(profileMetaFile(name), "utf8");
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
- const port = Number(parsed?.port);
204
- return {
205
- name: profileName,
206
- port: Number.isFinite(port) && port >= 1 && port <= 65535 ? Math.floor(port) : 0,
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,6 @@ export function listProfiles(): ProfileInfo[] {
253
319
  });
254
320
  }
255
321
 
256
- /**
257
- * Порты, зарезервированные за профилем default: основной (PREFERRED_PORT
258
- * в server.ts) и запасной. У default может не быть profile.json, поэтому
259
- * в listProfiles() его порт — null, и раньше аллокатор выдавал 3782 второму
260
- * профилю: два дашборда дрались за один порт.
261
- */
262
- const DEFAULT_PROFILE_PORTS = new Set([3782, 4782]);
263
- const FIRST_PROFILE_PORT = 3783;
264
- const LAST_PORT = 65535;
265
-
266
322
  /**
267
323
  * Свободный порт для нового профиля (B4.2).
268
324
  *
package/src/rpc.ts CHANGED
@@ -676,6 +676,30 @@ const AuditSettingsSchema = {
676
676
  required: ["enabled", "retentionDays", "maxRecords"],
677
677
  } as const;
678
678
 
679
+ /** Бюджеты день/неделя (Экономика v2, E-1.1). */
680
+ const BudgetSettingsSchema = {
681
+ type: "object" as const,
682
+ properties: {
683
+ enabled: { type: "boolean" },
684
+ dailyUsd: { type: "number" },
685
+ weeklyUsd: { type: "number" },
686
+ },
687
+ required: ["enabled", "dailyUsd", "weeklyUsd"],
688
+ } as const;
689
+
690
+ /** Деталь 3.8: настройки обратной связи с автором. */
691
+ const FeedbackSettingsSchema = {
692
+ type: "object" as const,
693
+ properties: {
694
+ enabled: { type: "boolean" },
695
+ endpoint: { type: "string" },
696
+ includeLogs: { type: "boolean" },
697
+ contactEmail: { type: "string" },
698
+ maxPerHour: { type: "number" },
699
+ },
700
+ required: ["enabled", "endpoint", "includeLogs", "contactEmail", "maxPerHour"],
701
+ } as const;
702
+
679
703
  /** Политика прав фоновых задач (Спринт 32). */
680
704
  const PermissionSettingsSchema = {
681
705
  type: "object" as const,
@@ -699,6 +723,8 @@ const GetSettingsOutput = {
699
723
  history: HistorySettingsSchema,
700
724
  audit: AuditSettingsSchema,
701
725
  permissions: PermissionSettingsSchema,
726
+ budgets: BudgetSettingsSchema,
727
+ feedback: FeedbackSettingsSchema,
702
728
  },
703
729
  required: ["maxConcurrent", "locale", "winterMode", "notifications"],
704
730
  } as const;
@@ -715,6 +741,8 @@ const SaveSettingsInput = {
715
741
  history: HistorySettingsSchema,
716
742
  audit: AuditSettingsSchema,
717
743
  permissions: PermissionSettingsSchema,
744
+ budgets: BudgetSettingsSchema,
745
+ feedback: FeedbackSettingsSchema,
718
746
  },
719
747
  additionalProperties: false,
720
748
  } as const;
@@ -731,6 +759,8 @@ const SaveSettingsOutput = {
731
759
  history: HistorySettingsSchema,
732
760
  audit: AuditSettingsSchema,
733
761
  permissions: PermissionSettingsSchema,
762
+ budgets: BudgetSettingsSchema,
763
+ feedback: FeedbackSettingsSchema,
734
764
  },
735
765
  required: ["success", "maxConcurrent", "locale", "winterMode", "notifications"],
736
766
  } as const;