agent-steward 0.0.2 → 0.0.4

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 (263) hide show
  1. package/CHANGELOG.md +45 -2
  2. package/CROSS_PLATFORM.md +11 -9
  3. package/README.md +11 -10
  4. package/ROADMAP-STRATEGY.md +93 -44
  5. package/ROADMAP.md +148 -1017
  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/dlq-api.d.ts +44 -0
  10. package/dist/core/dlq-api.d.ts.map +1 -0
  11. package/dist/core/dlq-api.js +68 -0
  12. package/dist/core/dry-run.d.ts.map +1 -1
  13. package/dist/core/dry-run.js +19 -2
  14. package/dist/core/file-watcher.js +9 -9
  15. package/dist/core/git-trigger.js +4 -4
  16. package/dist/core/lock.d.ts +20 -4
  17. package/dist/core/lock.d.ts.map +1 -1
  18. package/dist/core/lock.js +99 -26
  19. package/dist/core/one-shot.d.ts +31 -5
  20. package/dist/core/one-shot.d.ts.map +1 -1
  21. package/dist/core/one-shot.js +78 -10
  22. package/dist/core/opencode-cli.d.ts +28 -0
  23. package/dist/core/opencode-cli.d.ts.map +1 -0
  24. package/dist/core/opencode-cli.js +74 -0
  25. package/dist/core/opencode-models.d.ts +62 -0
  26. package/dist/core/opencode-models.d.ts.map +1 -0
  27. package/dist/core/opencode-models.js +277 -0
  28. package/dist/core/otel.js +2 -2
  29. package/dist/core/ps-wrapper.d.ts +1 -1
  30. package/dist/core/ps-wrapper.d.ts.map +1 -1
  31. package/dist/core/ps-wrapper.js +66 -36
  32. package/dist/core/record-history.d.ts +15 -0
  33. package/dist/core/record-history.d.ts.map +1 -1
  34. package/dist/core/record-history.js +78 -54
  35. package/dist/core/router/dispatch.d.ts +36 -0
  36. package/dist/core/router/dispatch.d.ts.map +1 -0
  37. package/dist/core/router/dispatch.js +59 -0
  38. package/dist/core/router/escalation.d.ts +47 -0
  39. package/dist/core/router/escalation.d.ts.map +1 -0
  40. package/dist/core/router/escalation.js +87 -0
  41. package/dist/core/router/planner.d.ts +53 -0
  42. package/dist/core/router/planner.d.ts.map +1 -0
  43. package/dist/core/router/planner.js +113 -0
  44. package/dist/core/router/rules.d.ts +46 -0
  45. package/dist/core/router/rules.d.ts.map +1 -0
  46. package/dist/core/router/rules.js +85 -0
  47. package/dist/core/run-panel-api.d.ts +94 -0
  48. package/dist/core/run-panel-api.d.ts.map +1 -0
  49. package/dist/core/run-panel-api.js +169 -0
  50. package/dist/core/schedule-gate.js +5 -1
  51. package/dist/core/schedule-v2.d.ts +36 -2
  52. package/dist/core/schedule-v2.d.ts.map +1 -1
  53. package/dist/core/schedule-v2.js +98 -12
  54. package/dist/core/scheduler/at-fallback.d.ts +95 -0
  55. package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
  56. package/dist/core/scheduler/at-fallback.js +200 -0
  57. package/dist/core/scheduler/linux.d.ts +13 -2
  58. package/dist/core/scheduler/linux.d.ts.map +1 -1
  59. package/dist/core/scheduler/linux.js +67 -13
  60. package/dist/core/scheduler/mac.d.ts +14 -8
  61. package/dist/core/scheduler/mac.d.ts.map +1 -1
  62. package/dist/core/scheduler/mac.js +71 -22
  63. package/dist/core/scheduler/posix.d.ts.map +1 -1
  64. package/dist/core/scheduler/posix.js +37 -2
  65. package/dist/core/scheduler/registry.d.ts +13 -0
  66. package/dist/core/scheduler/registry.d.ts.map +1 -1
  67. package/dist/core/scheduler/registry.js +83 -21
  68. package/dist/core/scheduler/run-now.d.ts +16 -0
  69. package/dist/core/scheduler/run-now.d.ts.map +1 -0
  70. package/dist/core/scheduler/run-now.js +28 -0
  71. package/dist/core/scheduler/windows.d.ts +16 -3
  72. package/dist/core/scheduler/windows.d.ts.map +1 -1
  73. package/dist/core/scheduler/windows.js +249 -96
  74. package/dist/core/secrets.d.ts.map +1 -1
  75. package/dist/core/secrets.js +127 -30
  76. package/dist/core/self-analysis.js +55 -55
  77. package/dist/core/session.d.ts.map +1 -1
  78. package/dist/core/session.js +18 -11
  79. package/dist/core/summary.js +1 -1
  80. package/dist/core/task-name.d.ts +24 -0
  81. package/dist/core/task-name.d.ts.map +1 -0
  82. package/dist/core/task-name.js +40 -0
  83. package/dist/core/triage-chain.js +1 -1
  84. package/dist/core/triage-worker.js +2 -2
  85. package/dist/core/triage.js +1 -1
  86. package/dist/core/wrappers/bash.d.ts.map +1 -1
  87. package/dist/core/wrappers/bash.js +82 -37
  88. package/dist/db/capability-repo.d.ts +83 -0
  89. package/dist/db/capability-repo.d.ts.map +1 -0
  90. package/dist/db/capability-repo.js +182 -0
  91. package/dist/db/history-repo.d.ts +8 -0
  92. package/dist/db/history-repo.d.ts.map +1 -1
  93. package/dist/db/history-repo.js +19 -0
  94. package/dist/db/index.d.ts +6 -0
  95. package/dist/db/index.d.ts.map +1 -1
  96. package/dist/db/index.js +48 -2
  97. package/dist/db/migrate.d.ts.map +1 -1
  98. package/dist/db/migrate.js +3 -1
  99. package/dist/db/run-context.d.ts +103 -0
  100. package/dist/db/run-context.d.ts.map +1 -0
  101. package/dist/db/run-context.js +224 -0
  102. package/dist/db/run-dlq.d.ts +100 -0
  103. package/dist/db/run-dlq.d.ts.map +1 -0
  104. package/dist/db/run-dlq.js +191 -0
  105. package/dist/db/run-journal.d.ts +60 -0
  106. package/dist/db/run-journal.d.ts.map +1 -0
  107. package/dist/db/run-journal.js +143 -0
  108. package/dist/db/run-resume.d.ts +51 -0
  109. package/dist/db/run-resume.d.ts.map +1 -0
  110. package/dist/db/run-resume.js +156 -0
  111. package/dist/db/runs-repo.d.ts +128 -0
  112. package/dist/db/runs-repo.d.ts.map +1 -0
  113. package/dist/db/runs-repo.js +342 -0
  114. package/dist/db/schema.d.ts +16 -2
  115. package/dist/db/schema.d.ts.map +1 -1
  116. package/dist/db/schema.js +342 -35
  117. package/dist/db/settings-repo.d.ts +11 -0
  118. package/dist/db/settings-repo.d.ts.map +1 -1
  119. package/dist/db/settings-repo.js +25 -0
  120. package/dist/db/step-idempotency.d.ts +51 -0
  121. package/dist/db/step-idempotency.d.ts.map +1 -0
  122. package/dist/db/step-idempotency.js +136 -0
  123. package/dist/index.d.ts +5 -5
  124. package/dist/index.d.ts.map +1 -1
  125. package/dist/index.js +168 -40
  126. package/dist/notifications.js +18 -18
  127. package/dist/profiles.d.ts +7 -3
  128. package/dist/profiles.d.ts.map +1 -1
  129. package/dist/profiles.js +85 -7
  130. package/dist/rpc.d.ts +787 -0
  131. package/dist/rpc.d.ts.map +1 -1
  132. package/dist/rpc.js +324 -0
  133. package/dist/server.d.ts +33 -2
  134. package/dist/server.d.ts.map +1 -1
  135. package/dist/server.js +115 -54
  136. package/dist/shared/jobs-view.d.ts.map +1 -1
  137. package/dist/skill.js +1 -1
  138. package/dist/task-transfer.d.ts +1 -1
  139. package/dist/task-transfer.d.ts.map +1 -1
  140. package/dist/task-transfer.js +14 -10
  141. package/dist/types.d.ts +20 -4
  142. package/dist/types.d.ts.map +1 -1
  143. package/dist/types.js +44 -9
  144. package/dist/workspaces.d.ts +25 -3
  145. package/dist/workspaces.d.ts.map +1 -1
  146. package/dist/workspaces.js +44 -9
  147. package/docs/ARCHITECTURE.md +335 -9
  148. package/docs/COMPATIBILITY.md +10 -6
  149. package/docs/CONCEPT.md +183 -91
  150. package/docs/CROSS_PLATFORM.ru.md +11 -9
  151. package/docs/CROSS_PLATFORM.zh.md +11 -9
  152. package/docs/EXECUTION-LOOP.md +196 -0
  153. package/docs/FAQ.md +2 -2
  154. package/docs/FAQ.ru.md +2 -2
  155. package/docs/FAQ.zh.md +2 -2
  156. package/docs/FEATURES.md +5 -4
  157. package/docs/FEATURES.zh.md +5 -4
  158. package/docs/MIGRATION.md +34 -26
  159. package/docs/README.ru.md +27 -8
  160. package/docs/README.zh.md +11 -10
  161. package/docs/SAFETY.md +122 -0
  162. package/docs/SAVINGS.md +29 -0
  163. package/docs/SAVINGS.ru.md +29 -0
  164. package/docs/SAVINGS.zh.md +18 -0
  165. package/docs/V1-V2-COMPATIBILITY-PLAN.md +6 -6
  166. package/gui-experimental.cjs +8 -8
  167. package/index.js +1 -0
  168. package/locales/en.json +68 -0
  169. package/locales/ru.json +68 -0
  170. package/locales/zh.json +68 -0
  171. package/package.json +57 -11
  172. package/scripts/audit-bundle.mjs +215 -0
  173. package/src/core/analytics.ts +2 -2
  174. package/src/core/audit.ts +17 -17
  175. package/src/core/cron-to-schtasks.ts +14 -93
  176. package/src/core/dlq-api.ts +98 -0
  177. package/src/core/dry-run.ts +51 -27
  178. package/src/core/file-watcher.ts +17 -17
  179. package/src/core/git-trigger.ts +9 -9
  180. package/src/core/glob.ts +1 -1
  181. package/src/core/local-ai.ts +2 -2
  182. package/src/core/lock.ts +104 -31
  183. package/src/core/matrix.ts +31 -31
  184. package/src/core/native-notify.ts +2 -2
  185. package/src/core/one-shot.ts +91 -13
  186. package/src/core/opencode-cli.ts +103 -0
  187. package/src/core/opencode-models.ts +315 -0
  188. package/src/core/otel.ts +4 -4
  189. package/src/core/permissions.ts +5 -5
  190. package/src/core/prometheus.ts +17 -17
  191. package/src/core/ps-wrapper.ts +68 -38
  192. package/src/core/record-history.ts +114 -76
  193. package/src/core/retention.ts +3 -3
  194. package/src/core/router/dispatch.ts +94 -0
  195. package/src/core/router/escalation.ts +129 -0
  196. package/src/core/router/planner.ts +166 -0
  197. package/src/core/router/rules.ts +109 -0
  198. package/src/core/run-panel-api.ts +262 -0
  199. package/src/core/savings.ts +1 -1
  200. package/src/core/schedule-gate.ts +17 -13
  201. package/src/core/schedule-v2.ts +138 -29
  202. package/src/core/scheduler/at-fallback.ts +298 -0
  203. package/src/core/scheduler/index.ts +3 -3
  204. package/src/core/scheduler/linux.ts +92 -19
  205. package/src/core/scheduler/logs.ts +1 -1
  206. package/src/core/scheduler/mac.ts +112 -60
  207. package/src/core/scheduler/posix.ts +35 -2
  208. package/src/core/scheduler/registry.ts +109 -26
  209. package/src/core/scheduler/run-now.ts +32 -0
  210. package/src/core/scheduler/windows.ts +295 -125
  211. package/src/core/secrets.ts +139 -39
  212. package/src/core/self-analysis.ts +61 -61
  213. package/src/core/session.ts +26 -13
  214. package/src/core/structured-log.ts +3 -3
  215. package/src/core/summary.ts +25 -25
  216. package/src/core/task-name.ts +67 -0
  217. package/src/core/telegram.ts +16 -16
  218. package/src/core/triage-chain.ts +4 -4
  219. package/src/core/triage-compare.ts +8 -8
  220. package/src/core/triage-rules.ts +4 -4
  221. package/src/core/triage-shadow.ts +7 -7
  222. package/src/core/triage-worker.ts +6 -6
  223. package/src/core/triage.ts +23 -23
  224. package/src/core/watch-paths.ts +1 -1
  225. package/src/core/wrappers/bash.ts +90 -45
  226. package/src/db/capability-repo.ts +285 -0
  227. package/src/db/git-state-repo.ts +1 -1
  228. package/src/db/history-repo.ts +44 -22
  229. package/src/db/index.ts +53 -7
  230. package/src/db/metrics-repo.ts +10 -10
  231. package/src/db/migrate.ts +13 -11
  232. package/src/db/recovery.ts +3 -3
  233. package/src/db/run-context.ts +370 -0
  234. package/src/db/run-dlq.ts +310 -0
  235. package/src/db/run-journal.ts +212 -0
  236. package/src/db/run-resume.ts +256 -0
  237. package/src/db/runs-repo.ts +504 -0
  238. package/src/db/schema.ts +357 -44
  239. package/src/db/settings-repo.ts +33 -2
  240. package/src/db/step-idempotency.ts +185 -0
  241. package/src/db/tasks-repo.ts +10 -10
  242. package/src/db/templates-repo.ts +7 -7
  243. package/src/gui.tsx +516 -1
  244. package/src/history.ts +4 -4
  245. package/src/i18n.ts +7 -7
  246. package/src/index.ts +465 -308
  247. package/src/integrations.ts +6 -6
  248. package/src/notifications.ts +76 -76
  249. package/src/profiles.ts +98 -7
  250. package/src/rpc.ts +347 -1
  251. package/src/schtasks.ts +2 -2
  252. package/src/server.ts +155 -78
  253. package/src/settings.ts +44 -44
  254. package/src/shared/jobs-view.ts +60 -60
  255. package/src/skill.ts +1 -1
  256. package/src/task-transfer.ts +58 -56
  257. package/src/templates.ts +1 -1
  258. package/src/types.ts +54 -10
  259. package/src/workspaces.ts +73 -24
  260. package/dist/core/self-analysis.test.d.ts +0 -2
  261. package/dist/core/self-analysis.test.d.ts.map +0 -1
  262. package/dist/core/self-analysis.test.js +0 -219
  263. package/dist/gui-experimental.cjs +0 -1
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Модели и цены — из самого OpenCode, а не из захардкоженного списка.
3
+ *
4
+ * Что берём и откуда:
5
+ * 1. Список доступных моделей — `opencode models`. Это ровно тот набор,
6
+ * который настроен у пользователя (провайдеры, ключи, локальные модели),
7
+ * а не «все модели мира».
8
+ * 2. Цены — кэш каталога models.dev, который OpenCode держит в
9
+ * `<cache>/opencode/models.json` (`cost.input` / `cost.output`, USD за 1M
10
+ * токенов). В истории токены не разделены на вход/выход, поэтому берём
11
+ * среднее из двух цен.
12
+ *
13
+ * Модуль никогда не бросает: если CLI или кэш недоступны, возвращаются
14
+ * значения по умолчанию, чтобы дашборд продолжал работать без OpenCode.
15
+ *
16
+ * Переключатели (переменные окружения):
17
+ * - OPENCODE_SCHEDULER_MODEL_SOURCE=static — не обращаться к OpenCode вообще
18
+ * (только встроенные значения; используется тестами);
19
+ * - OPENCODE_SCHEDULER_MODELS_CACHE=<путь> — свой файл каталога models.dev.
20
+ */
21
+ import fs from "node:fs";
22
+ import os from "node:os";
23
+ import path from "node:path";
24
+ import { execFileSync } from "node:child_process";
25
+ import { opencodeCommand } from "./opencode-cli.js";
26
+
27
+ /** Цена за 1M токенов модели в каталоге models.dev. */
28
+ export interface ModelCatalogEntry {
29
+ /** Входные токены, USD за 1M. */
30
+ input: number;
31
+ /** Выходные токены, USD за 1M. */
32
+ output: number;
33
+ }
34
+
35
+ /** Сколько what-if моделей показывать максимум. */
36
+ export const MAX_WHAT_IF_MODELS = 5;
37
+
38
+ /**
39
+ * Цены по умолчанию: используются только если модели нет ни в каталоге
40
+ * OpenCode, ни в OPENCODE_SCHEDULER_MODEL_PRICES.
41
+ */
42
+ export const DEFAULT_MODEL_PRICE_PER_MILLION: Record<string, number> = {
43
+ "openai/gpt-4o": 10,
44
+ "openai/gpt-4o-mini": 0.6,
45
+ "deepseek/deepseek-coder": 0.28,
46
+ "anthropic/claude-3-5-sonnet": 9,
47
+ "anthropic/claude-3-5-haiku": 1.2,
48
+ "google/gemini-2.5-pro": 3.5,
49
+ "google/gemini-2.0-flash": 0.3,
50
+ };
51
+
52
+ /** Средняя оценка цены, если модель вообще неизвестна. */
53
+ export const DEFAULT_PRICE_PER_MILLION = 3;
54
+
55
+ /** What-if модели, если OpenCode недоступен и истории ещё нет. */
56
+ export const DEFAULT_WHAT_IF_MODELS = [
57
+ "openai/gpt-4o",
58
+ "deepseek/deepseek-coder",
59
+ ];
60
+
61
+ /** Провайдеры локальных моделей: они не выставляют счёт. */
62
+ const LOCAL_PROVIDERS = new Set([
63
+ "ollama",
64
+ "lmstudio",
65
+ "llamacpp",
66
+ "llama.cpp",
67
+ "vllm",
68
+ "local",
69
+ ]);
70
+
71
+ const CATALOG_TTL_MS = 60_000;
72
+ const CLI_TTL_MS = 10 * 60_000;
73
+ const CLI_TIMEOUT_MS = 20_000;
74
+
75
+ /** Приводит id модели к виду для сравнения (регистр и пробелы не важны). */
76
+ export function normalizeModelId(model: string | undefined): string {
77
+ return (model ?? "").trim().toLowerCase();
78
+ }
79
+
80
+ /** Режим общения с OpenCode: "auto" (по умолчанию) или "static". */
81
+ export function modelSourceMode(): "auto" | "static" {
82
+ const raw = (process.env.OPENCODE_SCHEDULER_MODEL_SOURCE ?? "").trim().toLowerCase();
83
+ return raw === "static" || raw === "off" ? "static" : "auto";
84
+ }
85
+
86
+ /** Разбирает каталог models.dev в карту `provider/model` → цены. */
87
+ export function parseModelsCatalog(raw: string): Map<string, ModelCatalogEntry> {
88
+ const result = new Map<string, ModelCatalogEntry>();
89
+ let parsed: unknown;
90
+ try {
91
+ parsed = JSON.parse(raw);
92
+ } catch {
93
+ return result;
94
+ }
95
+ if (!parsed || typeof parsed !== "object") return result;
96
+
97
+ for (const [providerId, provider] of Object.entries(
98
+ parsed as Record<string, unknown>,
99
+ )) {
100
+ const models = (provider as { models?: unknown } | null)?.models;
101
+ if (!models || typeof models !== "object") continue;
102
+ for (const [modelId, model] of Object.entries(models as Record<string, unknown>)) {
103
+ const cost = (model as { cost?: unknown } | null)?.cost;
104
+ if (!cost || typeof cost !== "object") continue;
105
+ const input = Number((cost as { input?: unknown }).input);
106
+ const output = Number((cost as { output?: unknown }).output);
107
+ if (!Number.isFinite(input) || !Number.isFinite(output)) continue;
108
+ result.set(normalizeModelId(`${providerId}/${modelId}`), { input, output });
109
+ }
110
+ }
111
+ return result;
112
+ }
113
+
114
+ /** Разбирает вывод `opencode models` (по одному id в строке). */
115
+ export function parseModelList(stdout: string): string[] {
116
+ const seen = new Set<string>();
117
+ const models: string[] = [];
118
+ for (const line of stdout.split(/\r?\n/)) {
119
+ const id = line.trim();
120
+ if (!id || /\s/.test(id) || !id.includes("/")) continue;
121
+ const key = normalizeModelId(id);
122
+ if (seen.has(key)) continue;
123
+ seen.add(key);
124
+ models.push(id);
125
+ }
126
+ return models;
127
+ }
128
+
129
+ /** Средняя цена за 1M токенов: история не делит токены на вход и выход. */
130
+ export function blendedPrice(entry: ModelCatalogEntry): number {
131
+ return (entry.input + entry.output) / 2;
132
+ }
133
+
134
+ /** Путь к файлу каталога models.dev, если он есть на диске. */
135
+ export function findModelsCacheFile(): string | null {
136
+ const explicit = process.env.OPENCODE_SCHEDULER_MODELS_CACHE?.trim();
137
+ if (explicit) return fs.existsSync(explicit) ? explicit : null;
138
+
139
+ const home = os.homedir();
140
+ const candidates = [
141
+ path.join(process.env.XDG_CACHE_HOME || path.join(home, ".cache"), "opencode", "models.json"),
142
+ process.env.LOCALAPPDATA ? path.join(process.env.LOCALAPPDATA, "opencode", "models.json") : "",
143
+ process.env.APPDATA ? path.join(process.env.APPDATA, "opencode", "models.json") : "",
144
+ ].filter(Boolean);
145
+
146
+ for (const candidate of candidates) {
147
+ if (fs.existsSync(candidate)) return candidate;
148
+ }
149
+ return null;
150
+ }
151
+
152
+ /** Локальная модель: счёт не выставляется, цена — ноль. */
153
+ function isLocalProvider(model: string): boolean {
154
+ const provider = normalizeModelId(model).split("/")[0] ?? "";
155
+ return LOCAL_PROVIDERS.has(provider);
156
+ }
157
+
158
+ /** Бесплатная модель OpenCode (`...-free`): счёт не выставляется. */
159
+ function isKnownFreeModel(model: string): boolean {
160
+ return /(?:^|\/)[^/]*-free$/i.test(normalizeModelId(model));
161
+ }
162
+
163
+ let catalogCache: {
164
+ file: string;
165
+ mtimeMs: number;
166
+ checkedAt: number;
167
+ data: Map<string, ModelCatalogEntry>;
168
+ } | null = null;
169
+
170
+ /**
171
+ * Каталог цен из кэша OpenCode. Файл читается заново только когда изменился
172
+ * (плюс не чаще раза в минуту), поэтому 6 МБ JSON не парсятся на каждый запрос.
173
+ */
174
+ export function getModelsCatalog(): Map<string, ModelCatalogEntry> {
175
+ if (modelSourceMode() === "static") return new Map();
176
+
177
+ const file = findModelsCacheFile();
178
+ if (!file) return new Map();
179
+
180
+ const now = Date.now();
181
+ if (catalogCache?.file === file && now - catalogCache.checkedAt < CATALOG_TTL_MS) {
182
+ return catalogCache.data;
183
+ }
184
+
185
+ try {
186
+ const stat = fs.statSync(file);
187
+ if (catalogCache?.file === file && catalogCache.mtimeMs === stat.mtimeMs) {
188
+ catalogCache.checkedAt = now;
189
+ return catalogCache.data;
190
+ }
191
+ const data = parseModelsCatalog(fs.readFileSync(file, "utf8"));
192
+ catalogCache = { file, mtimeMs: stat.mtimeMs, checkedAt: now, data };
193
+ return data;
194
+ } catch {
195
+ return catalogCache?.data ?? new Map<string, ModelCatalogEntry>();
196
+ }
197
+ }
198
+
199
+ /** Цена модели за 1M токенов по каталогу OpenCode (null — цены нет). */
200
+ export function catalogPricePerMillion(model: string | undefined): number | null {
201
+ const key = normalizeModelId(model);
202
+ if (!key) return null;
203
+ const entry = getModelsCatalog().get(key);
204
+ if (entry) return blendedPrice(entry);
205
+ // Локальные провайдеры и бесплатные тарифы счёта не выставляют.
206
+ return isLocalProvider(key) || isKnownFreeModel(key) ? 0 : null;
207
+ }
208
+
209
+ let cliCache: { at: number; models: string[] } | null = null;
210
+
211
+ /** Запускает `opencode models` один раз (на Windows — через cmd.exe). */
212
+ function runModelsCli(): string[] {
213
+ try {
214
+ const command = opencodeCommand(["models"]);
215
+ const stdout = execFileSync(command.file, command.args, {
216
+ encoding: "utf8",
217
+ timeout: CLI_TIMEOUT_MS,
218
+ windowsHide: true,
219
+ stdio: ["ignore", "pipe", "ignore"],
220
+ });
221
+ return parseModelList(stdout);
222
+ } catch {
223
+ return [];
224
+ }
225
+ }
226
+
227
+ /** Доступные пользователю модели (`opencode models`), кэш 10 минут. */
228
+ export function listAvailableModels(): string[] {
229
+ if (modelSourceMode() === "static") return [];
230
+ const now = Date.now();
231
+ if (cliCache && now - cliCache.at < CLI_TTL_MS) return cliCache.models;
232
+ const models = runModelsCli();
233
+ cliCache = { at: now, models };
234
+ return models;
235
+ }
236
+
237
+ /** Откуда взялся список what-if моделей. */
238
+ export type WhatIfSource = "history" | "opencode" | "default";
239
+
240
+ export interface WhatIfSelection {
241
+ models: string[];
242
+ source: WhatIfSource;
243
+ }
244
+
245
+ /**
246
+ * Что показывать в What-If.
247
+ *
248
+ * Сначала модели, которые пользователь реально запускал (история), затем — по
249
+ * одной модели на каждую цену из доступных в OpenCode: дешёвая, средняя,
250
+ * дорогая. Так список обозрим и отвечает на вопрос «а сколько было бы на
251
+ * другой модели», а не перечисляет пять бесплатных подряд.
252
+ *
253
+ * `available` и `priceOf` вынесены параметрами, чтобы правило выбора
254
+ * проверялось тестом на фиксированных данных.
255
+ */
256
+ export function selectWhatIfModels(
257
+ preferred: string[],
258
+ available: string[],
259
+ priceOf: (model: string) => number | null = catalogPricePerMillion,
260
+ ): WhatIfSelection {
261
+ const picked: string[] = [];
262
+ const seen = new Set<string>();
263
+
264
+ const push = (model: string): void => {
265
+ const id = (model ?? "").trim();
266
+ const key = normalizeModelId(id);
267
+ if (!key || seen.has(key)) return;
268
+ seen.add(key);
269
+ picked.push(id);
270
+ };
271
+
272
+ const fromHistory: string[] = [];
273
+ for (const model of preferred) {
274
+ if (picked.length >= MAX_WHAT_IF_MODELS) break;
275
+ const before = picked.length;
276
+ push(model);
277
+ if (picked.length > before) fromHistory.push(picked[picked.length - 1]);
278
+ }
279
+
280
+ const candidates = available
281
+ .filter((model) => !seen.has(normalizeModelId(model)))
282
+ .map((model) => ({ model, price: priceOf(model) ?? DEFAULT_PRICE_PER_MILLION }))
283
+ .sort((a, b) => {
284
+ if (a.price !== b.price) return a.price - b.price;
285
+ // При равной цене берём самое короткое имя: списку нужен один пример.
286
+ if (a.model.length !== b.model.length) return a.model.length - b.model.length;
287
+ return a.model.localeCompare(b.model);
288
+ });
289
+
290
+ const prices = new Set<number>();
291
+ for (const item of candidates) {
292
+ if (picked.length >= MAX_WHAT_IF_MODELS) break;
293
+ if (prices.has(item.price)) continue;
294
+ prices.add(item.price);
295
+ push(item.model);
296
+ }
297
+
298
+ if (picked.length === 0) {
299
+ return { models: DEFAULT_WHAT_IF_MODELS.slice(), source: "default" };
300
+ }
301
+
302
+ const source: WhatIfSource = fromHistory.length > 0 ? "history" : "opencode";
303
+ return { models: picked, source };
304
+ }
305
+
306
+ /** What-If по реальным источникам: история + `opencode models` + каталог цен. */
307
+ export function resolveWhatIfModels(preferred: string[] = []): WhatIfSelection {
308
+ return selectWhatIfModels(preferred, listAvailableModels());
309
+ }
310
+
311
+ /** Сбрасывает кэши (нужно тестам). */
312
+ export function resetModelCaches(): void {
313
+ catalogCache = null;
314
+ cliCache = null;
315
+ }
package/src/core/otel.ts CHANGED
@@ -42,7 +42,7 @@ function doubleAttr(key: string, value: number | null | undefined): OtlpAttribut
42
42
  return { key, value: { doubleValue: value } };
43
43
  }
44
44
 
45
- function compact(attrs: Array<OtlpAttribute | null>): OtlpAttribute[] {
45
+ function compact(attrs: (OtlpAttribute | null)[]): OtlpAttribute[] {
46
46
  return attrs.filter((attr): attr is OtlpAttribute => attr != null);
47
47
  }
48
48
 
@@ -58,7 +58,7 @@ function hashIds(record: StoredHistoryRecord): { traceId: string; spanId: string
58
58
  .createHash("sha256")
59
59
  .update(
60
60
  `${record.taskName}|${record.startedAt}|${record.id ?? 0}`,
61
- "utf8"
61
+ "utf8",
62
62
  )
63
63
  .digest("hex");
64
64
  return { traceId: digest.slice(0, 32), spanId: digest.slice(32, 48) };
@@ -107,7 +107,7 @@ export function buildOtlpExport(records: StoredHistoryRecord[]): Record<string,
107
107
  {
108
108
  resource: {
109
109
  attributes: compact([
110
- stringAttr("service.name", "opencode-windows-scheduler"),
110
+ stringAttr("service.name", "agent-steward"),
111
111
  stringAttr("service.version", version),
112
112
  stringAttr("scheduler.profile", getProfileName()),
113
113
  stringAttr("scheduler.backend", getSchedulerTitle()),
@@ -116,7 +116,7 @@ export function buildOtlpExport(records: StoredHistoryRecord[]): Record<string,
116
116
  scopeSpans: [
117
117
  {
118
118
  scope: {
119
- name: "opencode-windows-scheduler",
119
+ name: "agent-steward",
120
120
  version,
121
121
  },
122
122
  spans,
@@ -93,7 +93,7 @@ export interface EffectivePermissions {
93
93
  /** Приводит произвольное значение к известной политике. */
94
94
  export function normalizePolicy(
95
95
  value: unknown,
96
- fallback: PermissionPolicy = DEFAULT_PERMISSION_POLICY
96
+ fallback: PermissionPolicy = DEFAULT_PERMISSION_POLICY,
97
97
  ): PermissionPolicy {
98
98
  return typeof value === "string" &&
99
99
  (PERMISSION_POLICIES as readonly string[]).includes(value)
@@ -103,14 +103,14 @@ export function normalizePolicy(
103
103
 
104
104
  /** Нормализует список инструментов: trim, lower-case, без пустых и дублей. */
105
105
  export function normalizeToolList(
106
- value: readonly string[] | null | undefined
106
+ value: readonly string[] | null | undefined,
107
107
  ): string[] {
108
108
  return Array.from(
109
109
  new Set(
110
110
  (value ?? [])
111
111
  .map((tool) => String(tool).trim().toLowerCase())
112
- .filter(Boolean)
113
- )
112
+ .filter(Boolean),
113
+ ),
114
114
  );
115
115
  }
116
116
 
@@ -186,7 +186,7 @@ export function buildOpencodeConfig(input: PermissionInput = {}): string {
186
186
  permissions: effective.permissions,
187
187
  },
188
188
  null,
189
- 2
189
+ 2,
190
190
  );
191
191
  }
192
192
 
@@ -53,7 +53,7 @@ function metric(
53
53
  name: string,
54
54
  type: "counter" | "gauge" | "histogram",
55
55
  help: string,
56
- samples: Array<{ labels?: Record<string, string | number>; value: number }>
56
+ samples: { labels?: Record<string, string | number>; value: number }[],
57
57
  ): void {
58
58
  lines.push(`# HELP ${name} ${help}`);
59
59
  lines.push(`# TYPE ${name} ${type}`);
@@ -115,20 +115,20 @@ export function renderPrometheusMetrics(): string {
115
115
  "opencode_scheduler_queue_depth",
116
116
  "gauge",
117
117
  "Количество незавершённых запусков (глубина очереди).",
118
- [{ value: queueDepth }]
118
+ [{ value: queueDepth }],
119
119
  );
120
120
  metric(
121
121
  lines,
122
122
  "opencode_scheduler_history_records",
123
123
  "gauge",
124
124
  "Количество записей в истории запусков.",
125
- [{ value: historyRecords }]
125
+ [{ value: historyRecords }],
126
126
  );
127
127
 
128
- const runSamples: Array<{ labels: Record<string, string | number>; value: number }> = [];
129
- const errorSamples: Array<{ labels: Record<string, string | number>; value: number }> = [];
130
- const tokenSamples: Array<{ labels: Record<string, string | number>; value: number }> = [];
131
- const costSamples: Array<{ labels: Record<string, string | number>; value: number }> = [];
128
+ const runSamples: { labels: Record<string, string | number>; value: number }[] = [];
129
+ const errorSamples: { labels: Record<string, string | number>; value: number }[] = [];
130
+ const tokenSamples: { labels: Record<string, string | number>; value: number }[] = [];
131
+ const costSamples: { labels: Record<string, string | number>; value: number }[] = [];
132
132
  for (const row of metrics) {
133
133
  runSamples.push({
134
134
  labels: { task: row.taskName, status: "success" },
@@ -151,32 +151,32 @@ export function renderPrometheusMetrics(): string {
151
151
  "opencode_scheduler_runs_total",
152
152
  "counter",
153
153
  "Количество завершённых запусков по задачам и статусам.",
154
- runSamples
154
+ runSamples,
155
155
  );
156
156
  metric(
157
157
  lines,
158
158
  "opencode_scheduler_errors_total",
159
159
  "counter",
160
160
  "Количество ошибок и таймаутов по задачам (partial не входит).",
161
- errorSamples
161
+ errorSamples,
162
162
  );
163
163
  metric(
164
164
  lines,
165
165
  "opencode_scheduler_tokens_total",
166
166
  "counter",
167
167
  "Суммарное количество токенов по задачам.",
168
- tokenSamples
168
+ tokenSamples,
169
169
  );
170
170
  metric(
171
171
  lines,
172
172
  "opencode_scheduler_cost_usd_total",
173
173
  "counter",
174
174
  "Суммарная стоимость запусков в USD по задачам.",
175
- costSamples
175
+ costSamples,
176
176
  );
177
177
 
178
178
  lines.push(
179
- "# HELP opencode_scheduler_run_duration_seconds Длительность запусков в секундах."
179
+ "# HELP opencode_scheduler_run_duration_seconds Длительность запусков в секундах.",
180
180
  );
181
181
  lines.push("# TYPE opencode_scheduler_run_duration_seconds histogram");
182
182
  const taskNames = Array.from(durations.keys()).sort((a, b) => a.localeCompare(b));
@@ -189,19 +189,19 @@ export function renderPrometheusMetrics(): string {
189
189
  `opencode_scheduler_run_duration_seconds_bucket${labels({
190
190
  task,
191
191
  le: DURATION_BUCKETS_SECONDS[i],
192
- })} ${cumulative}`
192
+ })} ${cumulative}`,
193
193
  );
194
194
  }
195
195
  lines.push(
196
- `opencode_scheduler_run_duration_seconds_bucket${labels({ task, le: "+Inf" })} ${stats.count}`
196
+ `opencode_scheduler_run_duration_seconds_bucket${labels({ task, le: "+Inf" })} ${stats.count}`,
197
197
  );
198
198
  lines.push(
199
199
  `opencode_scheduler_run_duration_seconds_sum${labels({ task })} ${formatNumber(
200
- stats.sumSeconds
201
- )}`
200
+ stats.sumSeconds,
201
+ )}`,
202
202
  );
203
203
  lines.push(
204
- `opencode_scheduler_run_duration_seconds_count${labels({ task })} ${stats.count}`
204
+ `opencode_scheduler_run_duration_seconds_count${labels({ task })} ${stats.count}`,
205
205
  );
206
206
  }
207
207
  if (taskNames.length === 0) {