agent-steward 0.0.4 → 0.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +309 -2
- package/CROSS_PLATFORM.md +19 -0
- package/README.md +55 -8
- package/ROADMAP-STRATEGY.md +22 -19
- package/ROADMAP.md +230 -159
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +356 -0
- package/dist/core/analytics.d.ts +6 -0
- package/dist/core/analytics.d.ts.map +1 -1
- package/dist/core/analytics.js +20 -3
- package/dist/core/audit.d.ts +6 -0
- package/dist/core/audit.d.ts.map +1 -1
- package/dist/core/audit.js +24 -0
- package/dist/core/budget.d.ts +118 -0
- package/dist/core/budget.d.ts.map +1 -0
- package/dist/core/budget.js +206 -0
- package/dist/core/cron-to-schtasks.d.ts.map +1 -1
- package/dist/core/cron-to-schtasks.js +38 -0
- package/dist/core/dry-run.d.ts +26 -1
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +199 -8
- package/dist/core/execution.d.ts +203 -0
- package/dist/core/execution.d.ts.map +1 -0
- package/dist/core/execution.js +309 -0
- package/dist/core/feedback.d.ts +192 -0
- package/dist/core/feedback.d.ts.map +1 -0
- package/dist/core/feedback.js +426 -0
- package/dist/core/gate-integrity.d.ts +71 -0
- package/dist/core/gate-integrity.d.ts.map +1 -0
- package/dist/core/gate-integrity.js +275 -0
- package/dist/core/git-trigger.d.ts.map +1 -1
- package/dist/core/git-trigger.js +14 -2
- package/dist/core/guard-run.d.ts +4 -0
- package/dist/core/guard-run.d.ts.map +1 -0
- package/dist/core/guard-run.js +101 -0
- package/dist/core/guard.d.ts +52 -0
- package/dist/core/guard.d.ts.map +1 -0
- package/dist/core/guard.js +362 -0
- package/dist/core/local-ai.d.ts.map +1 -1
- package/dist/core/local-ai.js +7 -3
- package/dist/core/lock.d.ts +41 -0
- package/dist/core/lock.d.ts.map +1 -1
- package/dist/core/lock.js +141 -29
- package/dist/core/matrix.d.ts +8 -0
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +132 -17
- package/dist/core/mission.d.ts +103 -0
- package/dist/core/mission.d.ts.map +1 -0
- package/dist/core/mission.js +374 -0
- package/dist/core/opencode-models.d.ts +2 -2
- package/dist/core/opencode-models.d.ts.map +1 -1
- package/dist/core/opencode-models.js +28 -21
- package/dist/core/opencode-usage.d.ts +35 -0
- package/dist/core/opencode-usage.d.ts.map +1 -0
- package/dist/core/opencode-usage.js +132 -0
- package/dist/core/pipeline-apply.d.ts +38 -0
- package/dist/core/pipeline-apply.d.ts.map +1 -0
- package/dist/core/pipeline-apply.js +117 -0
- package/dist/core/pipeline-io.d.ts +13 -0
- package/dist/core/pipeline-io.d.ts.map +1 -0
- package/dist/core/pipeline-io.js +78 -0
- package/dist/core/pipeline-map.d.ts +52 -0
- package/dist/core/pipeline-map.d.ts.map +1 -0
- package/dist/core/pipeline-map.js +208 -0
- package/dist/core/pipeline-spec.d.ts +109 -0
- package/dist/core/pipeline-spec.d.ts.map +1 -0
- package/dist/core/pipeline-spec.js +554 -0
- package/dist/core/ps-wrapper.d.ts +27 -2
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +424 -65
- package/dist/core/record-history.d.ts.map +1 -1
- package/dist/core/record-history.js +206 -33
- package/dist/core/router/rules.d.ts.map +1 -1
- package/dist/core/router/rules.js +6 -0
- package/dist/core/run-mode.d.ts +12 -0
- package/dist/core/run-mode.d.ts.map +1 -0
- package/dist/core/run-mode.js +17 -0
- package/dist/core/scheduler/linux.d.ts +8 -1
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +34 -9
- package/dist/core/scheduler/logs.d.ts +4 -0
- package/dist/core/scheduler/logs.d.ts.map +1 -1
- package/dist/core/scheduler/logs.js +25 -1
- package/dist/core/scheduler/mac.d.ts +44 -2
- package/dist/core/scheduler/mac.d.ts.map +1 -1
- package/dist/core/scheduler/mac.js +126 -15
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +15 -12
- package/dist/core/secrets.d.ts.map +1 -1
- package/dist/core/secrets.js +18 -8
- package/dist/core/self-analysis.d.ts +32 -2
- package/dist/core/self-analysis.d.ts.map +1 -1
- package/dist/core/self-analysis.js +38 -27
- package/dist/core/shutdown.d.ts +33 -2
- package/dist/core/shutdown.d.ts.map +1 -1
- package/dist/core/shutdown.js +58 -2
- package/dist/core/structured-log.d.ts +37 -1
- package/dist/core/structured-log.d.ts.map +1 -1
- package/dist/core/structured-log.js +37 -0
- package/dist/core/usage-surface.d.ts +25 -0
- package/dist/core/usage-surface.d.ts.map +1 -0
- package/dist/core/usage-surface.js +41 -0
- package/dist/core/worktree-run.d.ts +4 -0
- package/dist/core/worktree-run.d.ts.map +1 -0
- package/dist/core/worktree-run.js +164 -0
- package/dist/core/worktree.d.ts +115 -0
- package/dist/core/worktree.d.ts.map +1 -0
- package/dist/core/worktree.js +462 -0
- package/dist/core/wrappers/bash.d.ts +19 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +230 -27
- package/dist/db/capability-repo.d.ts +43 -2
- package/dist/db/capability-repo.d.ts.map +1 -1
- package/dist/db/capability-repo.js +96 -11
- package/dist/db/history-repo.d.ts +70 -5
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +170 -29
- package/dist/db/metrics-repo.d.ts +20 -2
- package/dist/db/metrics-repo.d.ts.map +1 -1
- package/dist/db/metrics-repo.js +35 -13
- package/dist/db/migrate.d.ts.map +1 -1
- package/dist/db/migrate.js +37 -17
- package/dist/db/recovery.d.ts +3 -1
- package/dist/db/recovery.d.ts.map +1 -1
- package/dist/db/recovery.js +11 -5
- package/dist/db/run-journal.d.ts +33 -5
- package/dist/db/run-journal.d.ts.map +1 -1
- package/dist/db/run-journal.js +78 -14
- package/dist/db/run-resume.d.ts +5 -0
- package/dist/db/run-resume.d.ts.map +1 -1
- package/dist/db/run-resume.js +9 -2
- package/dist/db/runs-repo.d.ts +19 -2
- package/dist/db/runs-repo.d.ts.map +1 -1
- package/dist/db/runs-repo.js +91 -60
- package/dist/db/schema.d.ts +2 -2
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +132 -2
- package/dist/db/templates-repo.d.ts +2 -2
- package/dist/db/templates-repo.d.ts.map +1 -1
- package/dist/db/templates-repo.js +5 -3
- package/dist/history.d.ts +7 -2
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +4 -2
- package/dist/hook-output.d.ts +2 -0
- package/dist/hook-output.d.ts.map +1 -0
- package/dist/hook-output.js +31 -0
- package/dist/i18n.d.ts +5 -0
- package/dist/i18n.d.ts.map +1 -1
- package/dist/i18n.js +11 -4
- package/dist/index.d.ts +375 -47
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1344 -192
- package/dist/notifications.d.ts +53 -2
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +168 -21
- package/dist/profiles.d.ts.map +1 -1
- package/dist/profiles.js +82 -10
- package/dist/rpc.d.ts +354 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +145 -0
- package/dist/server.d.ts +32 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +154 -30
- package/dist/settings.d.ts +44 -2
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +85 -3
- package/dist/shared/jobs-view.d.ts +1 -1
- package/dist/shared/jobs-view.d.ts.map +1 -1
- package/dist/shared/jobs-view.js +2 -0
- package/dist/task-transfer.d.ts +21 -0
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +64 -3
- package/dist/templates.d.ts +2 -2
- package/dist/templates.d.ts.map +1 -1
- package/dist/templates.js +3 -3
- package/dist/types.d.ts +22 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +34 -11
- package/docs/ARCHITECTURE.md +319 -66
- package/docs/COMPATIBILITY.md +2 -2
- package/docs/CONCEPT.md +18 -4
- package/docs/CROSS_PLATFORM.ru.md +20 -0
- package/docs/CROSS_PLATFORM.zh.md +18 -0
- package/docs/EXECUTION-LOOP.md +28 -10
- package/docs/FEATURES.md +129 -7
- package/docs/FEATURES.zh.md +97 -6
- package/docs/MIGRATION.md +2 -2
- package/docs/PIPELINE.md +293 -0
- package/docs/QA-A2-GUI-TUI.md +205 -0
- package/docs/README.ru.md +43 -4
- package/docs/README.zh.md +44 -4
- package/docs/SAFETY.md +23 -3
- package/gui-experimental.cjs +9 -8
- package/locales/en.json +58 -3
- package/locales/ru.json +58 -3
- package/locales/zh.json +58 -3
- package/opencode.pipeline.yaml +35 -0
- package/package.json +36 -4
- package/scripts/check-eslint-baseline.mjs +139 -0
- package/scripts/gen-test-plan-counters.mjs +117 -0
- package/scripts/github-ci-fetch.ps1 +37 -0
- package/scripts/pl-commit.ps1 +112 -0
- package/scripts/qa-a2-commit.ps1 +104 -0
- package/scripts/test-home.mjs +107 -0
- package/skills/scheduled-job-best-practices/SKILL.md +95 -1
- package/skills/scheduled-job-best-practices/references/recipes.md +139 -0
- package/src/cli.ts +417 -0
- package/src/core/analytics.ts +27 -4
- package/src/core/audit.ts +25 -0
- package/src/core/budget.ts +340 -0
- package/src/core/cron-to-schtasks.ts +42 -0
- package/src/core/dry-run.ts +235 -12
- package/src/core/execution.ts +538 -0
- package/src/core/feedback.ts +582 -0
- package/src/core/file-watcher.ts +2 -2
- package/src/core/gate-integrity.ts +330 -0
- package/src/core/git-trigger.ts +18 -5
- package/src/core/guard-run.ts +119 -0
- package/src/core/guard.ts +431 -0
- package/src/core/local-ai.ts +7 -3
- package/src/core/lock.ts +178 -37
- package/src/core/matrix.ts +158 -52
- package/src/core/mission.ts +531 -0
- package/src/core/native-notify.ts +1 -1
- package/src/core/opencode-models.ts +30 -21
- package/src/core/opencode-usage.ts +182 -0
- package/src/core/pipeline-apply.ts +158 -0
- package/src/core/pipeline-io.ts +96 -0
- package/src/core/pipeline-map.ts +283 -0
- package/src/core/pipeline-spec.ts +775 -0
- package/src/core/ps-wrapper.ts +435 -66
- package/src/core/record-history.ts +258 -81
- package/src/core/router/rules.ts +6 -0
- package/src/core/run-mode.ts +19 -0
- package/src/core/schedule-gate.ts +1 -1
- package/src/core/scheduler/at-fallback.ts +1 -1
- package/src/core/scheduler/linux.ts +40 -11
- package/src/core/scheduler/logs.ts +34 -3
- package/src/core/scheduler/mac.ts +174 -14
- package/src/core/scheduler/registry.ts +2 -2
- package/src/core/scheduler/windows.ts +19 -15
- package/src/core/secrets.ts +26 -19
- package/src/core/self-analysis.ts +75 -29
- package/src/core/shutdown.ts +90 -4
- package/src/core/structured-log.ts +89 -5
- package/src/core/telegram.ts +2 -2
- package/src/core/triage-worker.ts +7 -7
- package/src/core/triage.ts +2 -2
- package/src/core/usage-surface.ts +70 -0
- package/src/core/worktree-run.ts +199 -0
- package/src/core/worktree.ts +600 -0
- package/src/core/wrappers/bash.ts +248 -26
- package/src/db/capability-repo.ts +127 -10
- package/src/db/history-repo.ts +281 -40
- package/src/db/metrics-repo.ts +40 -13
- package/src/db/migrate.ts +57 -32
- package/src/db/recovery.ts +12 -5
- package/src/db/run-journal.ts +100 -13
- package/src/db/run-resume.ts +17 -1
- package/src/db/runs-repo.ts +147 -65
- package/src/db/schema.ts +134 -2
- package/src/db/templates-repo.ts +5 -3
- package/src/gui.tsx +438 -18
- package/src/history.ts +11 -4
- package/src/hook-output.ts +39 -0
- package/src/i18n.ts +12 -4
- package/src/index.ts +1902 -320
- package/src/notifications.ts +227 -47
- package/src/profiles.ts +88 -10
- package/src/rpc.ts +158 -0
- package/src/server.ts +201 -41
- package/src/settings.ts +125 -5
- package/src/shared/jobs-view.ts +3 -1
- package/src/task-transfer.ts +90 -6
- package/src/templates.ts +3 -3
- package/src/types.ts +23 -2
- package/src/workspaces.ts +37 -14
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PL-38 / QV-11.2: подсчёт токенов и стоимости из собственной БД OpenCode.
|
|
3
|
+
*
|
|
4
|
+
* Обёртки задач не печатают `Tokens:`/`Usage:` в лог — для провайдеров
|
|
5
|
+
* hy4-flash-free и ollama OpenCode вообще не выводит эту строку. Истина о
|
|
6
|
+
* расходе лежит в `opencode.db` (таблица `message`, поле `data` с JSON
|
|
7
|
+
* ассистентских сообщений). Читаем БД только на чтение и никогда не падаем,
|
|
8
|
+
* если файла нет, он занят или формат изменился.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import fs from "node:fs";
|
|
12
|
+
import os from "node:os";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
import { createRequire } from "node:module";
|
|
15
|
+
|
|
16
|
+
export interface OpenCodeUsage {
|
|
17
|
+
tokens: number;
|
|
18
|
+
costUsd: number;
|
|
19
|
+
messages: number;
|
|
20
|
+
providers: Record<string, number>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface CollectOpenCodeUsageOptions {
|
|
24
|
+
/** Нижняя граница окна, epoch ms. */
|
|
25
|
+
since: number;
|
|
26
|
+
/** Верхняя граница окна, epoch ms. */
|
|
27
|
+
until: number;
|
|
28
|
+
/** Явный путь к БД (тесты и переменная OPENCODE_USAGE_DB). */
|
|
29
|
+
dbPath?: string;
|
|
30
|
+
/** Рабочая директория задачи — фильтр по `path.cwd` сообщения. */
|
|
31
|
+
cwd?: string;
|
|
32
|
+
env?: NodeJS.ProcessEnv;
|
|
33
|
+
platform?: NodeJS.Platform;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const nodeRequire = createRequire(import.meta.url);
|
|
37
|
+
|
|
38
|
+
interface SqliteDatabase {
|
|
39
|
+
prepare(sql: string): { all(...params: unknown[]): unknown[] };
|
|
40
|
+
close(): void;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function loadDatabaseSync(): new (
|
|
44
|
+
location: string,
|
|
45
|
+
options?: Record<string, unknown>
|
|
46
|
+
) => SqliteDatabase {
|
|
47
|
+
const mod = nodeRequire("node:sqlite") as { DatabaseSync: new (
|
|
48
|
+
location: string,
|
|
49
|
+
options?: Record<string, unknown>
|
|
50
|
+
) => SqliteDatabase };
|
|
51
|
+
return mod.DatabaseSync;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Кандидаты путей к БД OpenCode в порядке приоритета. */
|
|
55
|
+
export function findOpenCodeDb(
|
|
56
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
57
|
+
platform: NodeJS.Platform = process.platform,
|
|
58
|
+
): string | null {
|
|
59
|
+
const explicit = env.OPENCODE_USAGE_DB?.trim();
|
|
60
|
+
if (explicit) return path.resolve(explicit);
|
|
61
|
+
|
|
62
|
+
// env имеют приоритет над os.homedir(): тот кэширует путь при старте Node,
|
|
63
|
+
// из-за чего тесты с изолированным HOME видели реальную БД пользователя.
|
|
64
|
+
const home = env.USERPROFILE?.trim() || env.HOME?.trim() || os.homedir();
|
|
65
|
+
const candidates =
|
|
66
|
+
platform === "win32" && env.APPDATA
|
|
67
|
+
? [
|
|
68
|
+
path.join(env.APPDATA, "opencode", "opencode.db"),
|
|
69
|
+
path.join(home, ".local", "share", "opencode", "opencode.db"),
|
|
70
|
+
]
|
|
71
|
+
: [
|
|
72
|
+
path.join(home, ".local", "share", "opencode", "opencode.db"),
|
|
73
|
+
path.join(home, ".config", "opencode", "opencode.db"),
|
|
74
|
+
];
|
|
75
|
+
|
|
76
|
+
return candidates.find((candidate) => fs.existsSync(candidate)) ?? null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function asFiniteNumber(value: unknown): number {
|
|
80
|
+
const num = Number(value);
|
|
81
|
+
return Number.isFinite(num) ? num : 0;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function parseMessageData(raw: unknown): {
|
|
85
|
+
tokens: number;
|
|
86
|
+
costUsd: number;
|
|
87
|
+
provider: string;
|
|
88
|
+
cwd: string;
|
|
89
|
+
} | null {
|
|
90
|
+
if (typeof raw !== "string") return null;
|
|
91
|
+
let data: Record<string, unknown>;
|
|
92
|
+
try {
|
|
93
|
+
const parsed: unknown = JSON.parse(raw);
|
|
94
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
95
|
+
data = parsed as Record<string, unknown>;
|
|
96
|
+
} catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
if (data.role !== "assistant") return null;
|
|
100
|
+
|
|
101
|
+
const tokensRaw = data.tokens;
|
|
102
|
+
let tokens = 0;
|
|
103
|
+
if (tokensRaw && typeof tokensRaw === "object" && !Array.isArray(tokensRaw)) {
|
|
104
|
+
const tokensObj = tokensRaw as Record<string, unknown>;
|
|
105
|
+
// OpenCode иногда пишет только total, иногда input/output/reasoning.
|
|
106
|
+
const cache = tokensObj.cache && typeof tokensObj.cache === "object"
|
|
107
|
+
? (tokensObj.cache as Record<string, unknown>)
|
|
108
|
+
: {};
|
|
109
|
+
tokens =
|
|
110
|
+
asFiniteNumber(tokensObj.total) ||
|
|
111
|
+
asFiniteNumber(tokensObj.input) +
|
|
112
|
+
asFiniteNumber(tokensObj.output) +
|
|
113
|
+
asFiniteNumber(tokensObj.reasoning) +
|
|
114
|
+
asFiniteNumber(cache.read) +
|
|
115
|
+
asFiniteNumber(cache.write);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const messagePath = data.path && typeof data.path === "object" && !Array.isArray(data.path)
|
|
119
|
+
? (data.path as Record<string, unknown>)
|
|
120
|
+
: {};
|
|
121
|
+
|
|
122
|
+
return {
|
|
123
|
+
tokens,
|
|
124
|
+
costUsd: asFiniteNumber(data.cost),
|
|
125
|
+
provider: typeof data.providerID === "string" ? data.providerID : "unknown",
|
|
126
|
+
cwd: typeof messagePath.cwd === "string" ? messagePath.cwd : "",
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Суммирует usage ассистентских сообщений за окно времени.
|
|
132
|
+
* Возвращает null, если БД недоступна (не искать токены в логах впустую).
|
|
133
|
+
*/
|
|
134
|
+
export function collectOpenCodeUsage(
|
|
135
|
+
options: CollectOpenCodeUsageOptions,
|
|
136
|
+
): OpenCodeUsage | null {
|
|
137
|
+
const dbPath = options.dbPath ?? findOpenCodeDb(options.env, options.platform);
|
|
138
|
+
if (!dbPath || !fs.existsSync(dbPath)) return null;
|
|
139
|
+
|
|
140
|
+
const since = Math.min(options.since, options.until);
|
|
141
|
+
const until = Math.max(options.since, options.until);
|
|
142
|
+
let db: SqliteDatabase | null = null;
|
|
143
|
+
try {
|
|
144
|
+
const DatabaseSync = loadDatabaseSync();
|
|
145
|
+
db = new DatabaseSync(dbPath, { readOnly: true });
|
|
146
|
+
const rows = db
|
|
147
|
+
.prepare(
|
|
148
|
+
"SELECT data FROM message WHERE time_created >= ? AND time_created <= ? AND json_extract(data, '$.role') = 'assistant'",
|
|
149
|
+
)
|
|
150
|
+
.all(since, until);
|
|
151
|
+
|
|
152
|
+
const result: OpenCodeUsage = { tokens: 0, costUsd: 0, messages: 0, providers: {} };
|
|
153
|
+
const wantedCwd = options.cwd?.trim().toLowerCase();
|
|
154
|
+
for (const row of rows) {
|
|
155
|
+
const raw = (row as { data?: unknown }).data;
|
|
156
|
+
const message = parseMessageData(raw);
|
|
157
|
+
if (!message) continue;
|
|
158
|
+
if (
|
|
159
|
+
wantedCwd &&
|
|
160
|
+
message.cwd &&
|
|
161
|
+
message.cwd.replace(/\\/g, "/").toLowerCase() !== wantedCwd.replace(/\\/g, "/").toLowerCase()
|
|
162
|
+
) {
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
result.tokens += message.tokens;
|
|
166
|
+
result.costUsd += message.costUsd;
|
|
167
|
+
result.messages += 1;
|
|
168
|
+
result.providers[message.provider] =
|
|
169
|
+
(result.providers[message.provider] ?? 0) + message.tokens;
|
|
170
|
+
}
|
|
171
|
+
return result;
|
|
172
|
+
} catch {
|
|
173
|
+
// БД занята/заблокирована/старой схемы — это диагностика, не отказ задачи.
|
|
174
|
+
return null;
|
|
175
|
+
} finally {
|
|
176
|
+
try {
|
|
177
|
+
db?.close();
|
|
178
|
+
} catch {
|
|
179
|
+
// ignore
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import type { TaskDefinition } from "../task-transfer.js";
|
|
2
|
+
import type { PipelineSpec } from "./pipeline-spec.js";
|
|
3
|
+
import { pipelineSpecToTasks } from "./pipeline-map.js";
|
|
4
|
+
|
|
5
|
+
export interface PipelineApplyPlan {
|
|
6
|
+
/** Задачи, которых ещё нет в БД. */
|
|
7
|
+
creates: TaskDefinition[];
|
|
8
|
+
/** Задачи с изменённым определением. */
|
|
9
|
+
updates: { task: TaskDefinition; previous: TaskDefinition }[];
|
|
10
|
+
/** Задачи, определение не изменилось. */
|
|
11
|
+
unchanged: TaskDefinition[];
|
|
12
|
+
/** Задачи этого pipeline, которых больше нет в YAML (не удаляются автоматически). */
|
|
13
|
+
stale: TaskDefinition[];
|
|
14
|
+
warnings: string[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface PipelineApplyResult {
|
|
18
|
+
created: number;
|
|
19
|
+
updated: number;
|
|
20
|
+
unchanged: number;
|
|
21
|
+
stale: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface PipelineApplyHandlers {
|
|
25
|
+
create(task: TaskDefinition): Promise<void> | void;
|
|
26
|
+
update(task: TaskDefinition): Promise<void> | void;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const SIGNATURE_FIELDS = [
|
|
30
|
+
"name",
|
|
31
|
+
"schedule",
|
|
32
|
+
"prompt",
|
|
33
|
+
"triggerType",
|
|
34
|
+
"dependsOn",
|
|
35
|
+
"model",
|
|
36
|
+
"priority",
|
|
37
|
+
"timeoutSeconds",
|
|
38
|
+
"workingDirectory",
|
|
39
|
+
"workspaceId",
|
|
40
|
+
"retryCount",
|
|
41
|
+
"retryDelay",
|
|
42
|
+
"qualityGate",
|
|
43
|
+
"beforeScript",
|
|
44
|
+
"afterScript",
|
|
45
|
+
"guards",
|
|
46
|
+
"allowedTools",
|
|
47
|
+
"deniedTools",
|
|
48
|
+
"matrix",
|
|
49
|
+
"timezone",
|
|
50
|
+
"notBefore",
|
|
51
|
+
"notAfter",
|
|
52
|
+
"activeDays",
|
|
53
|
+
"windowPolicy",
|
|
54
|
+
"runAt",
|
|
55
|
+
"pipelineName",
|
|
56
|
+
"pipelineStepId",
|
|
57
|
+
] as const;
|
|
58
|
+
|
|
59
|
+
function normalizeValue(value: unknown): unknown {
|
|
60
|
+
if (Array.isArray(value)) return value.map(normalizeValue);
|
|
61
|
+
if (value && typeof value === "object") {
|
|
62
|
+
const source = value as Record<string, unknown>;
|
|
63
|
+
const result: Record<string, unknown> = {};
|
|
64
|
+
for (const key of Object.keys(source).sort()) {
|
|
65
|
+
if (source[key] !== undefined) result[key] = normalizeValue(source[key]);
|
|
66
|
+
}
|
|
67
|
+
return result;
|
|
68
|
+
}
|
|
69
|
+
return value;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Стабильная подпись значимых полей задачи — для сравнения create/update/unchanged. */
|
|
73
|
+
export function pipelineTaskSignature(task: TaskDefinition): string {
|
|
74
|
+
const picked: Record<string, unknown> = {};
|
|
75
|
+
const source = task as unknown as Record<string, unknown>;
|
|
76
|
+
for (const field of SIGNATURE_FIELDS) {
|
|
77
|
+
if (source[field] !== undefined) picked[field] = normalizeValue(source[field]);
|
|
78
|
+
}
|
|
79
|
+
return JSON.stringify(picked);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function samePipeline(task: TaskDefinition, pipelineName: string): boolean {
|
|
83
|
+
return (
|
|
84
|
+
typeof task.pipelineName === "string" &&
|
|
85
|
+
task.pipelineName.toLowerCase() === pipelineName.toLowerCase()
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Чистый diff: сравнивает желаемые задачи pipeline с существующими.
|
|
91
|
+
* Задачи без маркеров pipelineName/pipelineStepId не трогаются никогда.
|
|
92
|
+
*/
|
|
93
|
+
export function planPipelineApply(
|
|
94
|
+
spec: PipelineSpec,
|
|
95
|
+
existing: TaskDefinition[],
|
|
96
|
+
options: { resolveWorkspaceId?: (value: string) => string | undefined } = {},
|
|
97
|
+
): PipelineApplyPlan {
|
|
98
|
+
const mapped = pipelineSpecToTasks(spec, options);
|
|
99
|
+
const create: TaskDefinition[] = [];
|
|
100
|
+
const updates: { task: TaskDefinition; previous: TaskDefinition }[] = [];
|
|
101
|
+
const unchanged: TaskDefinition[] = [];
|
|
102
|
+
|
|
103
|
+
const byStep = new Map<string, TaskDefinition>();
|
|
104
|
+
for (const task of existing) {
|
|
105
|
+
if (!samePipeline(task, spec.name)) continue;
|
|
106
|
+
const stepId = task.pipelineStepId;
|
|
107
|
+
if (typeof stepId !== "string" || !stepId) continue;
|
|
108
|
+
byStep.set(stepId.toLowerCase(), task);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
for (const task of mapped.tasks) {
|
|
112
|
+
const previous = byStep.get((task.pipelineStepId ?? "").toLowerCase());
|
|
113
|
+
if (!previous) {
|
|
114
|
+
create.push(task);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (pipelineTaskSignature(previous) === pipelineTaskSignature(task)) {
|
|
118
|
+
unchanged.push(task);
|
|
119
|
+
} else {
|
|
120
|
+
updates.push({ task, previous });
|
|
121
|
+
}
|
|
122
|
+
byStep.delete((task.pipelineStepId ?? "").toLowerCase());
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const stale = [...byStep.values()];
|
|
126
|
+
const warnings = [...mapped.warnings];
|
|
127
|
+
if (stale.length > 0) {
|
|
128
|
+
warnings.push(
|
|
129
|
+
`В YAML больше нет шагов: ${stale.map((task) => task.name).join(", ")}. ` +
|
|
130
|
+
"Они не удалены автоматически — удалите вручную или верните шаг.",
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return { creates: create, updates, unchanged, stale, warnings };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Применяет план через переданные обработчики (БД/планировщик) и считает итог. */
|
|
138
|
+
export async function executePipelineApply(
|
|
139
|
+
plan: PipelineApplyPlan,
|
|
140
|
+
handlers: PipelineApplyHandlers,
|
|
141
|
+
): Promise<PipelineApplyResult> {
|
|
142
|
+
let created = 0;
|
|
143
|
+
for (const task of plan.creates) {
|
|
144
|
+
await handlers.create(task);
|
|
145
|
+
created += 1;
|
|
146
|
+
}
|
|
147
|
+
let updated = 0;
|
|
148
|
+
for (const entry of plan.updates) {
|
|
149
|
+
await handlers.update(entry.task);
|
|
150
|
+
updated += 1;
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
created,
|
|
154
|
+
updated,
|
|
155
|
+
unchanged: plan.unchanged.length,
|
|
156
|
+
stale: plan.stale.length,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { isAbsolute, resolve } from "node:path";
|
|
3
|
+
import { parseDocument } from "yaml";
|
|
4
|
+
import {
|
|
5
|
+
validatePipelineSpec,
|
|
6
|
+
type PipelineIssue,
|
|
7
|
+
type PipelineSpec,
|
|
8
|
+
type PipelineValidationResult,
|
|
9
|
+
} from "./pipeline-spec.js";
|
|
10
|
+
|
|
11
|
+
/** Результат разбора YAML: спека возвращается только при успешной валидации. */
|
|
12
|
+
export interface PipelineParseResult extends PipelineValidationResult {
|
|
13
|
+
spec?: PipelineSpec;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const MAX_YAML_BYTES = 1024 * 1024;
|
|
17
|
+
const MAX_ALIAS_COUNT = 100;
|
|
18
|
+
|
|
19
|
+
function issueMessage(err: unknown): string {
|
|
20
|
+
return err instanceof Error ? err.message : String(err);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Разбирает YAML-текст в `PipelineSpec` и сразу валидирует его.
|
|
25
|
+
* Функция не бросает: синтаксические и смысловые ошибки возвращаются в `errors`.
|
|
26
|
+
*/
|
|
27
|
+
export function parsePipelineYaml(source: string): PipelineParseResult {
|
|
28
|
+
const errors: PipelineIssue[] = [];
|
|
29
|
+
const warnings: PipelineIssue[] = [];
|
|
30
|
+
|
|
31
|
+
if (source.length > MAX_YAML_BYTES) {
|
|
32
|
+
return {
|
|
33
|
+
ok: false,
|
|
34
|
+
errors: [{ path: "$", message: `YAML больше ${MAX_YAML_BYTES} байт` }],
|
|
35
|
+
warnings,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
let data: unknown;
|
|
40
|
+
try {
|
|
41
|
+
const doc = parseDocument(source, {
|
|
42
|
+
prettyErrors: true,
|
|
43
|
+
uniqueKeys: true,
|
|
44
|
+
strict: true,
|
|
45
|
+
});
|
|
46
|
+
if (doc.errors.length > 0) {
|
|
47
|
+
for (const err of doc.errors) {
|
|
48
|
+
errors.push({ path: "$", message: err.message });
|
|
49
|
+
}
|
|
50
|
+
return { ok: false, errors, warnings };
|
|
51
|
+
}
|
|
52
|
+
data = doc.toJS({ maxAliasCount: MAX_ALIAS_COUNT });
|
|
53
|
+
} catch (err) {
|
|
54
|
+
return {
|
|
55
|
+
ok: false,
|
|
56
|
+
errors: [{ path: "$", message: issueMessage(err) }],
|
|
57
|
+
warnings,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const result = validatePipelineSpec(data);
|
|
62
|
+
if (!result.ok) return result;
|
|
63
|
+
|
|
64
|
+
return { ...result, spec: data as PipelineSpec };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Читает YAML-файл и валидирует его. Ошибки ввода-вывода также попадают в `errors`. */
|
|
68
|
+
export async function loadPipelineFile(
|
|
69
|
+
filePath: string,
|
|
70
|
+
baseDir?: string,
|
|
71
|
+
): Promise<PipelineParseResult> {
|
|
72
|
+
// PL-34: cwd процесса-хоста OpenCode может не совпадать с каталогом задачи.
|
|
73
|
+
// Пробуем явный baseDir, затем cwd и подсказки окружения.
|
|
74
|
+
const roots = [
|
|
75
|
+
baseDir?.trim(),
|
|
76
|
+
process.cwd(),
|
|
77
|
+
process.env.OPENCODE_PROJECT_DIR,
|
|
78
|
+
process.env.INIT_CWD,
|
|
79
|
+
].filter((root): root is string => Boolean(root));
|
|
80
|
+
const candidates = isAbsolute(filePath)
|
|
81
|
+
? [filePath]
|
|
82
|
+
: roots.map((root) => resolve(root, filePath));
|
|
83
|
+
let lastError: unknown;
|
|
84
|
+
for (const candidate of [...new Set(candidates)]) {
|
|
85
|
+
try {
|
|
86
|
+
return parsePipelineYaml(await readFile(candidate, "utf8"));
|
|
87
|
+
} catch (err) {
|
|
88
|
+
lastError = err;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
ok: false,
|
|
93
|
+
errors: [{ path: filePath, message: `Не удалось прочитать файл: ${issueMessage(lastError)}` }],
|
|
94
|
+
warnings: [],
|
|
95
|
+
};
|
|
96
|
+
}
|