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.
- package/CHANGELOG.md +45 -2
- package/CROSS_PLATFORM.md +11 -9
- package/README.md +11 -10
- package/ROADMAP-STRATEGY.md +93 -44
- package/ROADMAP.md +148 -1017
- package/dist/core/cron-to-schtasks.d.ts +0 -8
- package/dist/core/cron-to-schtasks.d.ts.map +1 -1
- package/dist/core/cron-to-schtasks.js +11 -86
- package/dist/core/dlq-api.d.ts +44 -0
- package/dist/core/dlq-api.d.ts.map +1 -0
- package/dist/core/dlq-api.js +68 -0
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +19 -2
- package/dist/core/file-watcher.js +9 -9
- package/dist/core/git-trigger.js +4 -4
- package/dist/core/lock.d.ts +20 -4
- package/dist/core/lock.d.ts.map +1 -1
- package/dist/core/lock.js +99 -26
- package/dist/core/one-shot.d.ts +31 -5
- package/dist/core/one-shot.d.ts.map +1 -1
- package/dist/core/one-shot.js +78 -10
- package/dist/core/opencode-cli.d.ts +28 -0
- package/dist/core/opencode-cli.d.ts.map +1 -0
- package/dist/core/opencode-cli.js +74 -0
- package/dist/core/opencode-models.d.ts +62 -0
- package/dist/core/opencode-models.d.ts.map +1 -0
- package/dist/core/opencode-models.js +277 -0
- package/dist/core/otel.js +2 -2
- package/dist/core/ps-wrapper.d.ts +1 -1
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +66 -36
- package/dist/core/record-history.d.ts +15 -0
- package/dist/core/record-history.d.ts.map +1 -1
- package/dist/core/record-history.js +78 -54
- package/dist/core/router/dispatch.d.ts +36 -0
- package/dist/core/router/dispatch.d.ts.map +1 -0
- package/dist/core/router/dispatch.js +59 -0
- package/dist/core/router/escalation.d.ts +47 -0
- package/dist/core/router/escalation.d.ts.map +1 -0
- package/dist/core/router/escalation.js +87 -0
- package/dist/core/router/planner.d.ts +53 -0
- package/dist/core/router/planner.d.ts.map +1 -0
- package/dist/core/router/planner.js +113 -0
- package/dist/core/router/rules.d.ts +46 -0
- package/dist/core/router/rules.d.ts.map +1 -0
- package/dist/core/router/rules.js +85 -0
- package/dist/core/run-panel-api.d.ts +94 -0
- package/dist/core/run-panel-api.d.ts.map +1 -0
- package/dist/core/run-panel-api.js +169 -0
- package/dist/core/schedule-gate.js +5 -1
- package/dist/core/schedule-v2.d.ts +36 -2
- package/dist/core/schedule-v2.d.ts.map +1 -1
- package/dist/core/schedule-v2.js +98 -12
- package/dist/core/scheduler/at-fallback.d.ts +95 -0
- package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
- package/dist/core/scheduler/at-fallback.js +200 -0
- package/dist/core/scheduler/linux.d.ts +13 -2
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +67 -13
- package/dist/core/scheduler/mac.d.ts +14 -8
- package/dist/core/scheduler/mac.d.ts.map +1 -1
- package/dist/core/scheduler/mac.js +71 -22
- package/dist/core/scheduler/posix.d.ts.map +1 -1
- package/dist/core/scheduler/posix.js +37 -2
- package/dist/core/scheduler/registry.d.ts +13 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -1
- package/dist/core/scheduler/registry.js +83 -21
- package/dist/core/scheduler/run-now.d.ts +16 -0
- package/dist/core/scheduler/run-now.d.ts.map +1 -0
- package/dist/core/scheduler/run-now.js +28 -0
- package/dist/core/scheduler/windows.d.ts +16 -3
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +249 -96
- package/dist/core/secrets.d.ts.map +1 -1
- package/dist/core/secrets.js +127 -30
- package/dist/core/self-analysis.js +55 -55
- package/dist/core/session.d.ts.map +1 -1
- package/dist/core/session.js +18 -11
- package/dist/core/summary.js +1 -1
- package/dist/core/task-name.d.ts +24 -0
- package/dist/core/task-name.d.ts.map +1 -0
- package/dist/core/task-name.js +40 -0
- package/dist/core/triage-chain.js +1 -1
- package/dist/core/triage-worker.js +2 -2
- package/dist/core/triage.js +1 -1
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +82 -37
- package/dist/db/capability-repo.d.ts +83 -0
- package/dist/db/capability-repo.d.ts.map +1 -0
- package/dist/db/capability-repo.js +182 -0
- package/dist/db/history-repo.d.ts +8 -0
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +19 -0
- package/dist/db/index.d.ts +6 -0
- package/dist/db/index.d.ts.map +1 -1
- package/dist/db/index.js +48 -2
- package/dist/db/migrate.d.ts.map +1 -1
- package/dist/db/migrate.js +3 -1
- package/dist/db/run-context.d.ts +103 -0
- package/dist/db/run-context.d.ts.map +1 -0
- package/dist/db/run-context.js +224 -0
- package/dist/db/run-dlq.d.ts +100 -0
- package/dist/db/run-dlq.d.ts.map +1 -0
- package/dist/db/run-dlq.js +191 -0
- package/dist/db/run-journal.d.ts +60 -0
- package/dist/db/run-journal.d.ts.map +1 -0
- package/dist/db/run-journal.js +143 -0
- package/dist/db/run-resume.d.ts +51 -0
- package/dist/db/run-resume.d.ts.map +1 -0
- package/dist/db/run-resume.js +156 -0
- package/dist/db/runs-repo.d.ts +128 -0
- package/dist/db/runs-repo.d.ts.map +1 -0
- package/dist/db/runs-repo.js +342 -0
- package/dist/db/schema.d.ts +16 -2
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +342 -35
- package/dist/db/settings-repo.d.ts +11 -0
- package/dist/db/settings-repo.d.ts.map +1 -1
- package/dist/db/settings-repo.js +25 -0
- package/dist/db/step-idempotency.d.ts +51 -0
- package/dist/db/step-idempotency.d.ts.map +1 -0
- package/dist/db/step-idempotency.js +136 -0
- package/dist/index.d.ts +5 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +168 -40
- package/dist/notifications.js +18 -18
- package/dist/profiles.d.ts +7 -3
- package/dist/profiles.d.ts.map +1 -1
- package/dist/profiles.js +85 -7
- package/dist/rpc.d.ts +787 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +324 -0
- package/dist/server.d.ts +33 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +115 -54
- package/dist/shared/jobs-view.d.ts.map +1 -1
- package/dist/skill.js +1 -1
- package/dist/task-transfer.d.ts +1 -1
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +14 -10
- package/dist/types.d.ts +20 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +44 -9
- package/dist/workspaces.d.ts +25 -3
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +44 -9
- package/docs/ARCHITECTURE.md +335 -9
- package/docs/COMPATIBILITY.md +10 -6
- package/docs/CONCEPT.md +183 -91
- package/docs/CROSS_PLATFORM.ru.md +11 -9
- package/docs/CROSS_PLATFORM.zh.md +11 -9
- package/docs/EXECUTION-LOOP.md +196 -0
- package/docs/FAQ.md +2 -2
- package/docs/FAQ.ru.md +2 -2
- package/docs/FAQ.zh.md +2 -2
- package/docs/FEATURES.md +5 -4
- package/docs/FEATURES.zh.md +5 -4
- package/docs/MIGRATION.md +34 -26
- package/docs/README.ru.md +27 -8
- package/docs/README.zh.md +11 -10
- package/docs/SAFETY.md +122 -0
- package/docs/SAVINGS.md +29 -0
- package/docs/SAVINGS.ru.md +29 -0
- package/docs/SAVINGS.zh.md +18 -0
- package/docs/V1-V2-COMPATIBILITY-PLAN.md +6 -6
- package/gui-experimental.cjs +8 -8
- package/index.js +1 -0
- package/locales/en.json +68 -0
- package/locales/ru.json +68 -0
- package/locales/zh.json +68 -0
- package/package.json +57 -11
- package/scripts/audit-bundle.mjs +215 -0
- package/src/core/analytics.ts +2 -2
- package/src/core/audit.ts +17 -17
- package/src/core/cron-to-schtasks.ts +14 -93
- package/src/core/dlq-api.ts +98 -0
- package/src/core/dry-run.ts +51 -27
- package/src/core/file-watcher.ts +17 -17
- package/src/core/git-trigger.ts +9 -9
- package/src/core/glob.ts +1 -1
- package/src/core/local-ai.ts +2 -2
- package/src/core/lock.ts +104 -31
- package/src/core/matrix.ts +31 -31
- package/src/core/native-notify.ts +2 -2
- package/src/core/one-shot.ts +91 -13
- package/src/core/opencode-cli.ts +103 -0
- package/src/core/opencode-models.ts +315 -0
- package/src/core/otel.ts +4 -4
- package/src/core/permissions.ts +5 -5
- package/src/core/prometheus.ts +17 -17
- package/src/core/ps-wrapper.ts +68 -38
- package/src/core/record-history.ts +114 -76
- package/src/core/retention.ts +3 -3
- package/src/core/router/dispatch.ts +94 -0
- package/src/core/router/escalation.ts +129 -0
- package/src/core/router/planner.ts +166 -0
- package/src/core/router/rules.ts +109 -0
- package/src/core/run-panel-api.ts +262 -0
- package/src/core/savings.ts +1 -1
- package/src/core/schedule-gate.ts +17 -13
- package/src/core/schedule-v2.ts +138 -29
- package/src/core/scheduler/at-fallback.ts +298 -0
- package/src/core/scheduler/index.ts +3 -3
- package/src/core/scheduler/linux.ts +92 -19
- package/src/core/scheduler/logs.ts +1 -1
- package/src/core/scheduler/mac.ts +112 -60
- package/src/core/scheduler/posix.ts +35 -2
- package/src/core/scheduler/registry.ts +109 -26
- package/src/core/scheduler/run-now.ts +32 -0
- package/src/core/scheduler/windows.ts +295 -125
- package/src/core/secrets.ts +139 -39
- package/src/core/self-analysis.ts +61 -61
- package/src/core/session.ts +26 -13
- package/src/core/structured-log.ts +3 -3
- package/src/core/summary.ts +25 -25
- package/src/core/task-name.ts +67 -0
- package/src/core/telegram.ts +16 -16
- package/src/core/triage-chain.ts +4 -4
- package/src/core/triage-compare.ts +8 -8
- package/src/core/triage-rules.ts +4 -4
- package/src/core/triage-shadow.ts +7 -7
- package/src/core/triage-worker.ts +6 -6
- package/src/core/triage.ts +23 -23
- package/src/core/watch-paths.ts +1 -1
- package/src/core/wrappers/bash.ts +90 -45
- package/src/db/capability-repo.ts +285 -0
- package/src/db/git-state-repo.ts +1 -1
- package/src/db/history-repo.ts +44 -22
- package/src/db/index.ts +53 -7
- package/src/db/metrics-repo.ts +10 -10
- package/src/db/migrate.ts +13 -11
- package/src/db/recovery.ts +3 -3
- package/src/db/run-context.ts +370 -0
- package/src/db/run-dlq.ts +310 -0
- package/src/db/run-journal.ts +212 -0
- package/src/db/run-resume.ts +256 -0
- package/src/db/runs-repo.ts +504 -0
- package/src/db/schema.ts +357 -44
- package/src/db/settings-repo.ts +33 -2
- package/src/db/step-idempotency.ts +185 -0
- package/src/db/tasks-repo.ts +10 -10
- package/src/db/templates-repo.ts +7 -7
- package/src/gui.tsx +516 -1
- package/src/history.ts +4 -4
- package/src/i18n.ts +7 -7
- package/src/index.ts +465 -308
- package/src/integrations.ts +6 -6
- package/src/notifications.ts +76 -76
- package/src/profiles.ts +98 -7
- package/src/rpc.ts +347 -1
- package/src/schtasks.ts +2 -2
- package/src/server.ts +155 -78
- package/src/settings.ts +44 -44
- package/src/shared/jobs-view.ts +60 -60
- package/src/skill.ts +1 -1
- package/src/task-transfer.ts +58 -56
- package/src/templates.ts +1 -1
- package/src/types.ts +54 -10
- package/src/workspaces.ts +73 -24
- package/dist/core/self-analysis.test.d.ts +0 -2
- package/dist/core/self-analysis.test.d.ts.map +0 -1
- package/dist/core/self-analysis.test.js +0 -219
- package/dist/gui-experimental.cjs +0 -1
|
@@ -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:
|
|
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", "
|
|
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: "
|
|
119
|
+
name: "agent-steward",
|
|
120
120
|
version,
|
|
121
121
|
},
|
|
122
122
|
spans,
|
package/src/core/permissions.ts
CHANGED
|
@@ -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
|
|
package/src/core/prometheus.ts
CHANGED
|
@@ -53,7 +53,7 @@ function metric(
|
|
|
53
53
|
name: string,
|
|
54
54
|
type: "counter" | "gauge" | "histogram",
|
|
55
55
|
help: string,
|
|
56
|
-
samples:
|
|
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:
|
|
129
|
-
const errorSamples:
|
|
130
|
-
const tokenSamples:
|
|
131
|
-
const costSamples:
|
|
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) {
|