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.
Files changed (180) hide show
  1. package/CHANGELOG.md +25 -2
  2. package/CROSS_PLATFORM.md +11 -9
  3. package/README.md +9 -8
  4. package/ROADMAP-STRATEGY.md +93 -44
  5. package/ROADMAP.md +114 -999
  6. package/dist/core/cron-to-schtasks.d.ts +0 -8
  7. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  8. package/dist/core/cron-to-schtasks.js +11 -86
  9. package/dist/core/dry-run.js +1 -1
  10. package/dist/core/file-watcher.js +9 -9
  11. package/dist/core/git-trigger.js +4 -4
  12. package/dist/core/lock.js +2 -4
  13. package/dist/core/one-shot.d.ts +27 -5
  14. package/dist/core/one-shot.d.ts.map +1 -1
  15. package/dist/core/one-shot.js +53 -10
  16. package/dist/core/otel.js +2 -2
  17. package/dist/core/ps-wrapper.d.ts +1 -1
  18. package/dist/core/ps-wrapper.d.ts.map +1 -1
  19. package/dist/core/ps-wrapper.js +55 -35
  20. package/dist/core/record-history.js +22 -22
  21. package/dist/core/schedule-v2.d.ts +2 -2
  22. package/dist/core/schedule-v2.d.ts.map +1 -1
  23. package/dist/core/schedule-v2.js +7 -7
  24. package/dist/core/scheduler/at-fallback.d.ts +42 -0
  25. package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
  26. package/dist/core/scheduler/at-fallback.js +70 -0
  27. package/dist/core/scheduler/linux.d.ts +3 -1
  28. package/dist/core/scheduler/linux.d.ts.map +1 -1
  29. package/dist/core/scheduler/linux.js +43 -7
  30. package/dist/core/scheduler/mac.d.ts +14 -8
  31. package/dist/core/scheduler/mac.d.ts.map +1 -1
  32. package/dist/core/scheduler/mac.js +71 -22
  33. package/dist/core/scheduler/posix.d.ts.map +1 -1
  34. package/dist/core/scheduler/posix.js +12 -1
  35. package/dist/core/scheduler/registry.d.ts +2 -0
  36. package/dist/core/scheduler/registry.d.ts.map +1 -1
  37. package/dist/core/scheduler/windows.d.ts +16 -3
  38. package/dist/core/scheduler/windows.d.ts.map +1 -1
  39. package/dist/core/scheduler/windows.js +249 -96
  40. package/dist/core/secrets.js +2 -2
  41. package/dist/core/self-analysis.js +55 -55
  42. package/dist/core/summary.js +1 -1
  43. package/dist/core/triage-chain.js +1 -1
  44. package/dist/core/triage-worker.js +2 -2
  45. package/dist/core/triage.js +1 -1
  46. package/dist/core/wrappers/bash.js +33 -33
  47. package/dist/db/index.d.ts +2 -0
  48. package/dist/db/index.d.ts.map +1 -1
  49. package/dist/db/index.js +9 -1
  50. package/dist/db/run-journal.d.ts +60 -0
  51. package/dist/db/run-journal.d.ts.map +1 -0
  52. package/dist/db/run-journal.js +143 -0
  53. package/dist/db/run-resume.d.ts +48 -0
  54. package/dist/db/run-resume.d.ts.map +1 -0
  55. package/dist/db/run-resume.js +137 -0
  56. package/dist/db/runs-repo.d.ts +120 -0
  57. package/dist/db/runs-repo.d.ts.map +1 -0
  58. package/dist/db/runs-repo.js +319 -0
  59. package/dist/db/schema.d.ts +16 -2
  60. package/dist/db/schema.d.ts.map +1 -1
  61. package/dist/db/schema.js +190 -35
  62. package/dist/index.d.ts +1 -1
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +66 -36
  65. package/dist/notifications.js +18 -18
  66. package/dist/profiles.d.ts +7 -3
  67. package/dist/profiles.d.ts.map +1 -1
  68. package/dist/profiles.js +85 -7
  69. package/dist/rpc.d.ts +109 -0
  70. package/dist/rpc.d.ts.map +1 -1
  71. package/dist/rpc.js +89 -0
  72. package/dist/server.d.ts +2 -2
  73. package/dist/server.d.ts.map +1 -1
  74. package/dist/server.js +20 -19
  75. package/dist/shared/jobs-view.d.ts.map +1 -1
  76. package/dist/skill.js +1 -1
  77. package/dist/task-transfer.d.ts +1 -1
  78. package/dist/task-transfer.d.ts.map +1 -1
  79. package/dist/task-transfer.js +14 -10
  80. package/dist/types.d.ts +20 -4
  81. package/dist/types.d.ts.map +1 -1
  82. package/dist/types.js +37 -9
  83. package/dist/workspaces.js +1 -1
  84. package/docs/ARCHITECTURE.md +110 -8
  85. package/docs/COMPATIBILITY.md +10 -6
  86. package/docs/CONCEPT.md +15 -3
  87. package/docs/CROSS_PLATFORM.ru.md +11 -9
  88. package/docs/CROSS_PLATFORM.zh.md +11 -9
  89. package/docs/FAQ.md +2 -2
  90. package/docs/FAQ.ru.md +2 -2
  91. package/docs/FAQ.zh.md +2 -2
  92. package/docs/FEATURES.md +5 -4
  93. package/docs/FEATURES.zh.md +5 -4
  94. package/docs/MIGRATION.md +34 -26
  95. package/docs/README.ru.md +26 -7
  96. package/docs/README.zh.md +9 -8
  97. package/docs/V1-V2-COMPATIBILITY-PLAN.md +6 -6
  98. package/gui-experimental.cjs +8 -8
  99. package/index.js +1 -0
  100. package/locales/en.json +1 -0
  101. package/locales/ru.json +1 -0
  102. package/locales/zh.json +1 -0
  103. package/package.json +31 -10
  104. package/src/core/analytics.ts +2 -2
  105. package/src/core/audit.ts +17 -17
  106. package/src/core/cron-to-schtasks.ts +14 -93
  107. package/src/core/dry-run.ts +26 -26
  108. package/src/core/file-watcher.ts +17 -17
  109. package/src/core/git-trigger.ts +9 -9
  110. package/src/core/glob.ts +1 -1
  111. package/src/core/local-ai.ts +2 -2
  112. package/src/core/lock.ts +9 -9
  113. package/src/core/matrix.ts +31 -31
  114. package/src/core/native-notify.ts +2 -2
  115. package/src/core/one-shot.ts +63 -13
  116. package/src/core/otel.ts +4 -4
  117. package/src/core/permissions.ts +5 -5
  118. package/src/core/prometheus.ts +17 -17
  119. package/src/core/ps-wrapper.ts +57 -37
  120. package/src/core/record-history.ts +40 -40
  121. package/src/core/retention.ts +3 -3
  122. package/src/core/savings.ts +1 -1
  123. package/src/core/schedule-gate.ts +12 -12
  124. package/src/core/schedule-v2.ts +24 -24
  125. package/src/core/scheduler/at-fallback.ts +113 -0
  126. package/src/core/scheduler/index.ts +3 -3
  127. package/src/core/scheduler/linux.ts +64 -13
  128. package/src/core/scheduler/logs.ts +1 -1
  129. package/src/core/scheduler/mac.ts +112 -60
  130. package/src/core/scheduler/posix.ts +15 -1
  131. package/src/core/scheduler/registry.ts +6 -4
  132. package/src/core/scheduler/windows.ts +295 -125
  133. package/src/core/secrets.ts +13 -13
  134. package/src/core/self-analysis.ts +61 -61
  135. package/src/core/session.ts +3 -3
  136. package/src/core/structured-log.ts +3 -3
  137. package/src/core/summary.ts +25 -25
  138. package/src/core/telegram.ts +16 -16
  139. package/src/core/triage-chain.ts +4 -4
  140. package/src/core/triage-compare.ts +8 -8
  141. package/src/core/triage-rules.ts +4 -4
  142. package/src/core/triage-shadow.ts +7 -7
  143. package/src/core/triage-worker.ts +6 -6
  144. package/src/core/triage.ts +23 -23
  145. package/src/core/watch-paths.ts +1 -1
  146. package/src/core/wrappers/bash.ts +41 -41
  147. package/src/db/git-state-repo.ts +1 -1
  148. package/src/db/history-repo.ts +22 -22
  149. package/src/db/index.ts +16 -6
  150. package/src/db/metrics-repo.ts +10 -10
  151. package/src/db/migrate.ts +10 -10
  152. package/src/db/recovery.ts +3 -3
  153. package/src/db/run-journal.ts +212 -0
  154. package/src/db/run-resume.ts +220 -0
  155. package/src/db/runs-repo.ts +481 -0
  156. package/src/db/schema.ts +205 -44
  157. package/src/db/settings-repo.ts +2 -2
  158. package/src/db/tasks-repo.ts +10 -10
  159. package/src/db/templates-repo.ts +7 -7
  160. package/src/gui.tsx +1 -1
  161. package/src/history.ts +4 -4
  162. package/src/i18n.ts +7 -7
  163. package/src/index.ts +341 -304
  164. package/src/integrations.ts +6 -6
  165. package/src/notifications.ts +76 -76
  166. package/src/profiles.ts +98 -7
  167. package/src/rpc.ts +96 -1
  168. package/src/schtasks.ts +2 -2
  169. package/src/server.ts +43 -42
  170. package/src/settings.ts +44 -44
  171. package/src/shared/jobs-view.ts +60 -60
  172. package/src/skill.ts +1 -1
  173. package/src/task-transfer.ts +58 -56
  174. package/src/templates.ts +1 -1
  175. package/src/types.ts +45 -10
  176. package/src/workspaces.ts +16 -16
  177. package/dist/core/self-analysis.test.d.ts +0 -2
  178. package/dist/core/self-analysis.test.d.ts.map +0 -1
  179. package/dist/core/self-analysis.test.js +0 -219
  180. package/dist/gui-experimental.cjs +0 -1
package/src/profiles.ts CHANGED
@@ -32,22 +32,113 @@ export interface ProfileInfo {
32
32
  /**
33
33
  * Базовая директория плагина (до профилей).
34
34
  *
35
- * Windows: %APPDATA%\opencode\windows-scheduler.
36
- * macOS/Linux: $XDG_CONFIG_HOME/opencode/windows-scheduler или
37
- * ~/.config/opencode/windows-scheduler.
35
+ * Windows: %APPDATA%\opencode\agent-steward.
36
+ * macOS/Linux: $XDG_CONFIG_HOME/opencode/agent-steward или
37
+ * ~/.config/opencode/agent-steward.
38
38
  * OPENCODE_SCHEDULER_HOME переопределяет всё (тесты, кастомные установки).
39
+ *
40
+ * При первом запуске после переименования данные из исторической
41
+ * .../opencode/windows-scheduler копируются в новую директорию (legacy
42
+ * остаётся на месте как резервная копия).
39
43
  */
40
44
  export function getBasePluginDir(): string {
41
45
  const custom = process.env.OPENCODE_SCHEDULER_HOME?.trim();
42
46
  if (custom) return path.resolve(custom);
43
47
 
48
+ const root = path.join(pluginConfigRoot(), "opencode");
49
+ const target = path.join(root, "agent-steward");
50
+ const legacy = path.join(root, "windows-scheduler");
51
+
52
+ if (fs.existsSync(target) || !fs.existsSync(legacy)) return target;
53
+
54
+ try {
55
+ migrateLegacyBaseDir(legacy, target);
56
+ return target;
57
+ } catch (error) {
58
+ // Не теряем доступ к данным: продолжаем работать в старой директории.
59
+ console.error(
60
+ `[agent-steward] Не удалось перенести данные из "${legacy}" в "${target}": ${
61
+ error instanceof Error ? error.message : String(error)
62
+ }. Использую старую директорию.`,
63
+ );
64
+ return legacy;
65
+ }
66
+ }
67
+
68
+ /** Корень конфигурации пользователя (без .../opencode). */
69
+ function pluginConfigRoot(): string {
44
70
  if (process.platform === "win32") {
45
- const base = process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming");
46
- return path.join(base, "opencode", "windows-scheduler");
71
+ return process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming");
47
72
  }
73
+ return process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
74
+ }
75
+
76
+ const MIGRATION_MARKER = ".migrated-from-windows-scheduler";
77
+
78
+ /** Расширения текстовых файлов, в которых могут быть абсолютные пути. */
79
+ const PATH_REWRITE_EXTENSIONS = new Set([
80
+ ".json",
81
+ ".cmd",
82
+ ".sh",
83
+ ".bash",
84
+ ".ps1",
85
+ ".txt",
86
+ ]);
87
+
88
+ /**
89
+ * Копирует legacy-директорию в новую и переписывает в текстовых файлах
90
+ * абсолютные пути старой директории на новую. Копия делается во временную
91
+ * директорию и переименовывается атомарно, чтобы не оставить половину данных.
92
+ */
93
+ function migrateLegacyBaseDir(legacy: string, target: string): void {
94
+ const temp = `${target}.migrating-${process.pid}`;
95
+ fs.rmSync(temp, { recursive: true, force: true });
96
+ fs.cpSync(legacy, temp, { recursive: true });
97
+
98
+ rewriteAbsolutePaths(temp, legacy, target);
99
+ fs.writeFileSync(
100
+ path.join(temp, MIGRATION_MARKER),
101
+ `${new Date().toISOString()}\n`,
102
+ "utf8",
103
+ );
104
+
105
+ try {
106
+ fs.renameSync(temp, target);
107
+ } catch (error) {
108
+ fs.rmSync(temp, { recursive: true, force: true });
109
+ // Параллельный процесс мог успеть создать target — это не ошибка.
110
+ if (fs.existsSync(target)) return;
111
+ throw error;
112
+ }
113
+ }
114
+
115
+ function rewriteAbsolutePaths(root: string, from: string, to: string): void {
116
+ const variants = [
117
+ from,
118
+ from.replace(/\\/g, "/"),
119
+ from.replace(/\\/g, "\\\\"),
120
+ ].filter((value, index, all) => value && all.indexOf(value) === index);
121
+
122
+ const walk = (dir: string): void => {
123
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
124
+ const full = path.join(dir, entry.name);
125
+ if (entry.isDirectory()) {
126
+ walk(full);
127
+ continue;
128
+ }
129
+ if (!PATH_REWRITE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) {
130
+ continue;
131
+ }
132
+ const text = fs.readFileSync(full, "utf8");
133
+ let next = text;
134
+ for (const variant of variants) {
135
+ next = next.split(variant).join(variant.includes("\\\\") ? to.replace(/\\/g, "\\\\") : variant.includes("/") ? to.replace(/\\/g, "/") : to);
136
+ }
137
+ if (next !== text) fs.writeFileSync(full, next, "utf8");
138
+ }
139
+ };
48
140
 
49
- const configHome = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
50
- return path.join(configHome, "opencode", "windows-scheduler");
141
+ walk(root);
51
142
  }
52
143
 
53
144
  /** Нормализует имя профиля: нижний регистр, только [a-z0-9_-]. */
package/src/rpc.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Rpc } from "@opencode/plugin/rpc"
1
+ import { Rpc } from "@opencode/plugin/rpc";
2
2
 
3
3
  /**
4
4
  * Общее определение RPC-контракта между серверной частью плагина (src/index.ts)
@@ -928,6 +928,85 @@ const CompareTriageOutput = {
928
928
  additionalProperties: false,
929
929
  } as const;
930
930
 
931
+ /** Отчёт shadow-режима триажа для GUI. */
932
+ const GetShadowReportInput = {
933
+ type: "object" as const,
934
+ properties: {},
935
+ additionalProperties: false,
936
+ } as const;
937
+
938
+ const GetShadowReportOutput = {
939
+ type: "object" as const,
940
+ properties: {
941
+ success: { type: "boolean" },
942
+ active: { type: "boolean" },
943
+ startedAt: { type: ["string", "null"] },
944
+ days: { type: "number" },
945
+ total: { type: "number" },
946
+ skips: { type: "number" },
947
+ wouldSuppress: { type: "number" },
948
+ bySource: { type: "object" },
949
+ persisted: { type: "boolean" },
950
+ truncated: { type: "boolean" },
951
+ decisions: { type: "array", items: { type: "object" } },
952
+ },
953
+ required: [
954
+ "success",
955
+ "active",
956
+ "startedAt",
957
+ "days",
958
+ "total",
959
+ "skips",
960
+ "wouldSuppress",
961
+ "bySource",
962
+ "persisted",
963
+ "truncated",
964
+ "decisions",
965
+ ],
966
+ additionalProperties: false,
967
+ } as const;
968
+
969
+ /** Сброс shadow-журнала триажа для GUI. */
970
+ const ResetShadowReportInput = {
971
+ type: "object" as const,
972
+ properties: {},
973
+ additionalProperties: false,
974
+ } as const;
975
+
976
+ const ResetShadowReportOutput = {
977
+ type: "object" as const,
978
+ properties: {
979
+ success: { type: "boolean" },
980
+ },
981
+ required: ["success"],
982
+ additionalProperties: false,
983
+ } as const;
984
+
985
+ /** Проверка связи с локальной моделью триажа (GUI). */
986
+ const TestLocalAiInput = {
987
+ type: "object" as const,
988
+ properties: {
989
+ mode: { type: "string" },
990
+ baseUrl: { type: "string" },
991
+ model: { type: "string" },
992
+ timeoutMs: { type: "number" },
993
+ fallback: { type: "string" },
994
+ confidenceThreshold: { type: "number" },
995
+ },
996
+ additionalProperties: false,
997
+ } as const;
998
+
999
+ const TestLocalAiOutput = {
1000
+ type: "object" as const,
1001
+ properties: {
1002
+ success: { type: "boolean" },
1003
+ localAi: { type: "object" },
1004
+ result: { type: "object" },
1005
+ },
1006
+ required: ["success", "localAi", "result"],
1007
+ additionalProperties: false,
1008
+ } as const;
1009
+
931
1010
  const TemplateItem = {
932
1011
  type: "object" as const,
933
1012
  properties: {
@@ -1538,6 +1617,10 @@ const DeleteProfileOutput = {
1538
1617
  } as const;
1539
1618
 
1540
1619
  export const SchedulerRpc = Rpc.define({
1620
+ // ВАЖНО: id RPC-канала совпадает с id плагина и должен оставаться
1621
+ // "opencode-windows-scheduler". GUI OpenCode строит URL
1622
+ // /api/rpc/<plugin-id>/<method>; если id разойдётся, все вызовы
1623
+ // вернут 400 "RPC is unavailable: opencode-windows-scheduler".
1541
1624
  id: "opencode-windows-scheduler",
1542
1625
  methods: {
1543
1626
  get_tasks: { input: GetTasksInput, output: GetTasksOutput },
@@ -1602,6 +1685,18 @@ export const SchedulerRpc = Rpc.define({
1602
1685
  input: CompareTriageInput,
1603
1686
  output: CompareTriageOutput,
1604
1687
  },
1688
+ get_shadow_report: {
1689
+ input: GetShadowReportInput,
1690
+ output: GetShadowReportOutput,
1691
+ },
1692
+ reset_shadow_report: {
1693
+ input: ResetShadowReportInput,
1694
+ output: ResetShadowReportOutput,
1695
+ },
1696
+ test_local_ai: {
1697
+ input: TestLocalAiInput,
1698
+ output: TestLocalAiOutput,
1699
+ },
1605
1700
  },
1606
1701
  events: {},
1607
1702
  });
package/src/schtasks.ts CHANGED
@@ -28,7 +28,7 @@ const backend = new WindowsScheduler();
28
28
  export async function createTask(
29
29
  name: string,
30
30
  trCommand: string,
31
- scheduleFlags: string[]
31
+ scheduleFlags: string[],
32
32
  ): Promise<void> {
33
33
  const args = [
34
34
  "/create",
@@ -44,7 +44,7 @@ export async function createTask(
44
44
  throw new SchtasksError(
45
45
  `Не удалось создать задачу "${name}": ${result.stderr || result.stdout}`,
46
46
  result.code,
47
- result.stderr
47
+ result.stderr,
48
48
  );
49
49
  }
50
50
  }
package/src/server.ts CHANGED
@@ -60,7 +60,7 @@ function normalizeProcessName(name: string): string {
60
60
 
61
61
  /** Маркер-заголовок: по нему узнаём «свой» дашборд, уже слушающий порт. */
62
62
  const DASHBOARD_HEADER = "x-plugin-dashboard";
63
- const DASHBOARD_MARKER = "opencode-windows-scheduler";
63
+ const DASHBOARD_MARKER = "agent-steward";
64
64
 
65
65
  /** Переопределение портов (используется в тестах; по умолчанию 3782/4782). */
66
66
  export interface DashboardPorts {
@@ -72,7 +72,7 @@ export interface DashboardPorts {
72
72
  export interface DashboardDeps {
73
73
  /** Список задач плагина (тот же вид, что отдаёт get_tasks / list_tasks). */
74
74
  getTasks: () => Promise<
75
- Array<{
75
+ {
76
76
  name: string;
77
77
  schedule: string;
78
78
  status: string;
@@ -122,7 +122,7 @@ export interface DashboardDeps {
122
122
  status: string;
123
123
  message: string;
124
124
  } | null;
125
- }>
125
+ }[]
126
126
  >;
127
127
  /** Немедленный запуск задачи (schtasks /run через обёртку плагина). */
128
128
  runTask: (name: string) => Promise<{ alreadyRunning?: boolean }>;
@@ -189,13 +189,13 @@ function estimateCost(tokens: number, model: string | undefined): number {
189
189
  * Возвращает данные для GET /api/models-analysis и блока дашборда.
190
190
  */
191
191
  function aggregateModels(
192
- history: Array<{
192
+ history: {
193
193
  status: string;
194
194
  durationMs: number;
195
195
  tokens?: number;
196
196
  costUsd?: number;
197
197
  model?: string;
198
- }>
198
+ }[],
199
199
  ) {
200
200
  const map = new Map<
201
201
  string,
@@ -352,7 +352,7 @@ export function needsDashboardSourceCheck(pathname: string): boolean {
352
352
  */
353
353
  export async function startDashboardServer(
354
354
  deps: DashboardDeps,
355
- ports?: DashboardPorts
355
+ ports?: DashboardPorts,
356
356
  ): Promise<{ port: number } | null> {
357
357
  if (running) return { port: running.port };
358
358
  if (starting) return starting;
@@ -371,14 +371,14 @@ export async function startDashboardServer(
371
371
  const server = await listenOn(port, deps);
372
372
  const actualPort = resolveServerPort(server, port);
373
373
  running = { server, port: actualPort };
374
- console.log(`[windows-scheduler] Веб-дашборд запущен: http://localhost:${actualPort}`);
374
+ console.log(`[agent-steward] Веб-дашборд запущен: http://localhost:${actualPort}`);
375
375
  return { port: actualPort };
376
376
  } catch (err: any) {
377
377
  if (err?.code !== "EADDRINUSE") {
378
378
  console.error(
379
- `[windows-scheduler] Не удалось запустить дашборд на порту ${port}: ${
379
+ `[agent-steward] Не удалось запустить дашборд на порту ${port}: ${
380
380
  err instanceof Error ? err.message : String(err)
381
- }`
381
+ }`,
382
382
  );
383
383
  return null;
384
384
  }
@@ -387,7 +387,7 @@ export async function startDashboardServer(
387
387
  // в том же процессе/сессии), переиспользуем его, а не вешаем второй порт.
388
388
  if (port !== 0 && (await isOwnDashboardOn(port))) {
389
389
  console.log(
390
- `[windows-scheduler] Дашборд уже запущен на http://localhost:${port} — переиспользуем его.`
390
+ `[agent-steward] Дашборд уже запущен на http://localhost:${port} — переиспользуем его.`,
391
391
  );
392
392
  return { port };
393
393
  }
@@ -402,7 +402,7 @@ export async function startDashboardServer(
402
402
  try {
403
403
  const server = await listenOn(port, deps);
404
404
  running = { server, port };
405
- console.log(`[windows-scheduler] Веб-дашборд запущен: http://localhost:${port}`);
405
+ console.log(`[agent-steward] Веб-дашборд запущен: http://localhost:${port}`);
406
406
  return { port };
407
407
  } catch {
408
408
  // Не вышло — идём к следующему порту.
@@ -413,7 +413,7 @@ export async function startDashboardServer(
413
413
  }
414
414
  }
415
415
  console.error(
416
- `[windows-scheduler] Не удалось подобрать свободный порт — веб-дашборд не запущен.`
416
+ "[agent-steward] Не удалось подобрать свободный порт — веб-дашборд не запущен.",
417
417
  );
418
418
  return null;
419
419
  })();
@@ -447,19 +447,20 @@ async function tryFreeZombiePort(port: number): Promise<boolean> {
447
447
  const normName = normalizeProcessName(info.name.toLowerCase());
448
448
  if (!ZOMBIE_IMAGE_NAMES.has(normName)) {
449
449
  console.warn(
450
- `[windows-scheduler] Порт ${port} занят процессом ${info.name} (PID ${pid}) — не трогаем, пробуем другой порт.`
450
+ `[agent-steward] Порт ${port} занят процессом ${info.name} (PID ${pid}) — не трогаем, пробуем другой порт.`,
451
451
  );
452
452
  continue;
453
453
  }
454
454
 
455
455
  const cmd = (info.commandLine || "").toLowerCase();
456
456
  const looksLikeOurs =
457
- cmd.includes("opencode-windows-scheduler") ||
457
+ cmd.includes("agent-steward") ||
458
+ cmd.includes("opencode-windows-scheduler") || // legacy name — старые зомби-процессы
458
459
  cmd.includes("dist/server") ||
459
460
  cmd.includes("dist\\server");
460
461
  if (!looksLikeOurs) {
461
462
  console.warn(
462
- `[windows-scheduler] Порт ${port} занят node/bun (PID ${pid}), но это не процесс плагина — не трогаем.`
463
+ `[agent-steward] Порт ${port} занят node/bun (PID ${pid}), но это не процесс плагина — не трогаем.`,
463
464
  );
464
465
  continue;
465
466
  }
@@ -471,14 +472,14 @@ async function tryFreeZombiePort(port: number): Promise<boolean> {
471
472
  process.kill(pid, "SIGKILL");
472
473
  }
473
474
  console.log(
474
- `[windows-scheduler] Снят зомби-процесс ${info.name} (PID ${pid}), державший порт ${port}.`
475
+ `[agent-steward] Снят зомби-процесс ${info.name} (PID ${pid}), державший порт ${port}.`,
475
476
  );
476
477
  killed = true;
477
478
  } catch (err: any) {
478
479
  console.warn(
479
- `[windows-scheduler] Не удалось снять процесс PID ${pid}: ${
480
+ `[agent-steward] Не удалось снять процесс PID ${pid}: ${
480
481
  err instanceof Error ? err.message : String(err)
481
- }`
482
+ }`,
482
483
  );
483
484
  }
484
485
  }
@@ -535,7 +536,7 @@ async function findListeningPidsPosix(port: number): Promise<number[]> {
535
536
  const { stdout } = await execFileAsync(
536
537
  "lsof",
537
538
  ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"],
538
- { windowsHide: true }
539
+ { windowsHide: true },
539
540
  );
540
541
  const pids = stdout
541
542
  .split(/\s+/)
@@ -573,7 +574,7 @@ async function getProcessInfo(pid: number): Promise<{ name: string; commandLine:
573
574
 
574
575
  /** Имя процесса и командная строка через CIM (Windows PowerShell). */
575
576
  async function getProcessInfoWindows(
576
- pid: number
577
+ pid: number,
577
578
  ): Promise<{ name: string; commandLine: string } | null> {
578
579
  try {
579
580
  const script =
@@ -583,7 +584,7 @@ async function getProcessInfoWindows(
583
584
  const { stdout } = await execFileAsync(
584
585
  "powershell.exe",
585
586
  ["-NoProfile", "-NonInteractive", "-Command", script],
586
- { windowsHide: true }
587
+ { windowsHide: true },
587
588
  );
588
589
  const line = stdout.trim();
589
590
  if (!line) return null;
@@ -597,7 +598,7 @@ async function getProcessInfoWindows(
597
598
 
598
599
  /** Имя процесса и командная строка через ps (macOS/Linux). */
599
600
  async function getProcessInfoPosix(
600
- pid: number
601
+ pid: number,
601
602
  ): Promise<{ name: string; commandLine: string } | null> {
602
603
  try {
603
604
  // NOTE: на Linux у Node главный поток помечен как "MainThread", поэтому
@@ -676,7 +677,7 @@ function listenOn(port: number, deps: DashboardDeps): Promise<http.Server> {
676
677
  async function handleRequest(
677
678
  req: http.IncomingMessage,
678
679
  res: http.ServerResponse,
679
- deps: DashboardDeps
680
+ deps: DashboardDeps,
680
681
  ): Promise<void> {
681
682
  try {
682
683
  let url: URL;
@@ -710,8 +711,8 @@ async function handleRequest(
710
711
  pathname === "/api/health" ||
711
712
  pathname === "/api/logs" ||
712
713
  pathname === "/metrics" ||
713
- /^\/api\/dry-run\//.test(pathname) ||
714
- /^\/api\/matrix\//.test(pathname);
714
+ pathname.startsWith("/api/dry-run/") ||
715
+ pathname.startsWith("/api/matrix/");
715
716
  if (knownGet && req.method !== "GET") {
716
717
  sendJson(res, 405, { error: t("server.methodNotAllowed") });
717
718
  return;
@@ -797,7 +798,7 @@ async function handleRequest(
797
798
  200,
798
799
  "application/x-ndjson; charset=utf-8",
799
800
  body ? `${body}\n` : "",
800
- `logs-${stamp}.jsonl`
801
+ `logs-${stamp}.jsonl`,
801
802
  );
802
803
  return;
803
804
  }
@@ -910,7 +911,7 @@ async function handleRequest(
910
911
  }
911
912
  if (statusFilter) {
912
913
  records = records.filter(
913
- (record) => String(record.status).toLowerCase() === statusFilter
914
+ (record) => String(record.status).toLowerCase() === statusFilter,
914
915
  );
915
916
  }
916
917
  const total = records.length;
@@ -928,11 +929,11 @@ async function handleRequest(
928
929
  if (req.method === "GET" && pathname === "/api/analytics") {
929
930
  const days = Math.min(
930
931
  365,
931
- Math.max(1, Math.floor(Number(url.searchParams.get("days")) || 14))
932
+ Math.max(1, Math.floor(Number(url.searchParams.get("days")) || 14)),
932
933
  );
933
934
  const topLimit = Math.max(
934
935
  1,
935
- Math.floor(Number(url.searchParams.get("top")) || 10)
936
+ Math.floor(Number(url.searchParams.get("top")) || 10),
936
937
  );
937
938
  const records = getHistory(null, 20000);
938
939
  const tasks = await deps.getTasks();
@@ -965,7 +966,7 @@ async function handleRequest(
965
966
  200,
966
967
  "application/json; charset=utf-8",
967
968
  JSON.stringify(buildOtlpExport(records), null, 2),
968
- `history-${stamp}.otlp.json`
969
+ `history-${stamp}.otlp.json`,
969
970
  );
970
971
  } else if (format === "json") {
971
972
  sendAttachment(
@@ -973,7 +974,7 @@ async function handleRequest(
973
974
  200,
974
975
  "application/json; charset=utf-8",
975
976
  JSON.stringify({ exportedAt: new Date().toISOString(), records }, null, 2),
976
- `history-${stamp}.json`
977
+ `history-${stamp}.json`,
977
978
  );
978
979
  } else {
979
980
  sendAttachment(
@@ -981,7 +982,7 @@ async function handleRequest(
981
982
  200,
982
983
  "text/csv; charset=utf-8",
983
984
  historyToCsv(records),
984
- `history-${stamp}.csv`
985
+ `history-${stamp}.csv`,
985
986
  );
986
987
  }
987
988
  return;
@@ -1021,7 +1022,7 @@ async function handleRequest(
1021
1022
  200,
1022
1023
  "application/octet-stream",
1023
1024
  data,
1024
- `scheduler-${stamp}.db`
1025
+ `scheduler-${stamp}.db`,
1025
1026
  );
1026
1027
  } catch (err: any) {
1027
1028
  sendJson(res, 500, {
@@ -1053,7 +1054,7 @@ async function handleRequest(
1053
1054
  }
1054
1055
 
1055
1056
  // Входящий webhook-триггер (Спринт 22): POST /api/hooks/:task?token=…
1056
- const hookMatch = req.method === "POST" && pathname.match(/^\/api\/hooks\/(.+)$/);
1057
+ const hookMatch = req.method === "POST" && (/^\/api\/hooks\/(.+)$/.exec(pathname));
1057
1058
  if (hookMatch) {
1058
1059
  const taskName = hookMatch[1].replace(/\/+$/, "").trim();
1059
1060
  const remote = req.socket.remoteAddress ?? null;
@@ -1066,7 +1067,7 @@ async function handleRequest(
1066
1067
  httpStatus: number,
1067
1068
  status: "accepted" | "rejected",
1068
1069
  reason?: string,
1069
- payloadBytes = declaredBytes
1070
+ payloadBytes = declaredBytes,
1070
1071
  ) => {
1071
1072
  appendStructuredLog({
1072
1073
  event: "hook.received",
@@ -1166,7 +1167,7 @@ async function handleRequest(
1166
1167
  }
1167
1168
 
1168
1169
  // Запуск задачи: POST /api/run/:name (имя URL-кодируется на клиенте).
1169
- const runMatch = req.method === "POST" && pathname.match(/^\/api\/run\/(.+)$/);
1170
+ const runMatch = req.method === "POST" && (/^\/api\/run\/(.+)$/.exec(pathname));
1170
1171
  if (runMatch) {
1171
1172
  const name = runMatch[1].replace(/\/+$/, "");
1172
1173
  if (!name) {
@@ -1201,7 +1202,7 @@ async function handleRequest(
1201
1202
 
1202
1203
  // Lifecycle матриц (Спринт 16): отмена выполняющейся матрицы.
1203
1204
  const cancelMatrixMatch =
1204
- req.method === "POST" && pathname.match(/^\/api\/cancel-matrix\/(.+)$/);
1205
+ req.method === "POST" && (/^\/api\/cancel-matrix\/(.+)$/.exec(pathname));
1205
1206
  if (cancelMatrixMatch) {
1206
1207
  const name = decodeURIComponent(cancelMatrixMatch[1]).replace(/\/+$/, "");
1207
1208
  if (!name) {
@@ -1272,7 +1273,7 @@ async function handleRequest(
1272
1273
  }
1273
1274
 
1274
1275
  // Удаление задачи: POST /api/delete/:name (кнопка «Удалить» в таблице).
1275
- const deleteMatch = req.method === "POST" && pathname.match(/^\/api\/delete\/(.+)$/);
1276
+ const deleteMatch = req.method === "POST" && (/^\/api\/delete\/(.+)$/.exec(pathname));
1276
1277
  if (deleteMatch) {
1277
1278
  const name = deleteMatch[1].replace(/\/+$/, "");
1278
1279
  if (!name) {
@@ -1304,7 +1305,7 @@ async function handleRequest(
1304
1305
  sendJson(res, 404, { error: t("server.notFound") });
1305
1306
  } catch (err: any) {
1306
1307
  const message = err instanceof Error ? err.message : String(err);
1307
- console.error(`[windows-scheduler] Ошибка обработки запроса ${req.url}: ${message}`);
1308
+ console.error(`[agent-steward] Ошибка обработки запроса ${req.url}: ${message}`);
1308
1309
  if (res.headersSent) {
1309
1310
  res.destroy();
1310
1311
  return;
@@ -1352,7 +1353,7 @@ function sendBuffer(
1352
1353
  status: number,
1353
1354
  contentType: string,
1354
1355
  body: Buffer,
1355
- filename: string
1356
+ filename: string,
1356
1357
  ): void {
1357
1358
  if (res.headersSent) {
1358
1359
  res.end();
@@ -1375,7 +1376,7 @@ function sendAttachment(
1375
1376
  status: number,
1376
1377
  contentType: string,
1377
1378
  body: string,
1378
- filename: string
1379
+ filename: string,
1379
1380
  ): void {
1380
1381
  if (res.headersSent) {
1381
1382
  res.end();
@@ -1786,7 +1787,7 @@ function renderPage(): string {
1786
1787
  ' | Content-Type: ' + (ct || '(пусто)') +
1787
1788
  '\\nПервые 2000 символов ответа:\\n' + text.slice(0, 2000)
1788
1789
  );
1789
- if (marker !== 'opencode-windows-scheduler') {
1790
+ if (marker !== 'agent-steward' && marker !== 'opencode-windows-scheduler') {
1790
1791
  console.error(
1791
1792
  'Ответ пришёл не от дашборда плагина: нет заголовка x-plugin-dashboard. ' +
1792
1793
  'Похоже, на этом порту работает другой сервис.'