opencode-windows-scheduler 1.2.3 → 1.4.0

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 (58) hide show
  1. package/CHANGELOG.md +61 -2
  2. package/README.md +21 -4
  3. package/ROADMAP-STRATEGY.md +61 -159
  4. package/ROADMAP.md +60 -98
  5. package/dist/core/audit.d.ts +68 -0
  6. package/dist/core/audit.d.ts.map +1 -0
  7. package/dist/core/audit.js +206 -0
  8. package/dist/core/native-notify.d.ts +36 -0
  9. package/dist/core/native-notify.d.ts.map +1 -0
  10. package/dist/core/native-notify.js +110 -0
  11. package/dist/core/record-history.js +4 -4
  12. package/dist/core/secrets.d.ts +57 -0
  13. package/dist/core/secrets.d.ts.map +1 -0
  14. package/dist/core/secrets.js +331 -0
  15. package/dist/core/structured-log.d.ts.map +1 -1
  16. package/dist/core/structured-log.js +9 -0
  17. package/dist/core/telegram.d.ts +45 -0
  18. package/dist/core/telegram.d.ts.map +1 -0
  19. package/dist/core/telegram.js +160 -0
  20. package/dist/db/schema.d.ts +1 -1
  21. package/dist/db/schema.d.ts.map +1 -1
  22. package/dist/db/schema.js +15 -0
  23. package/dist/index.d.ts +30 -4
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +349 -22
  26. package/dist/notifications.d.ts +26 -6
  27. package/dist/notifications.d.ts.map +1 -1
  28. package/dist/notifications.js +191 -34
  29. package/dist/rpc.d.ts +400 -0
  30. package/dist/rpc.d.ts.map +1 -1
  31. package/dist/rpc.js +146 -0
  32. package/dist/server.d.ts.map +1 -1
  33. package/dist/server.js +67 -0
  34. package/dist/settings.d.ts +63 -2
  35. package/dist/settings.d.ts.map +1 -1
  36. package/dist/settings.js +126 -2
  37. package/dist/workspaces.d.ts +8 -2
  38. package/dist/workspaces.d.ts.map +1 -1
  39. package/dist/workspaces.js +21 -4
  40. package/docs/ARCHITECTURE.md +16 -6
  41. package/docs/FEATURES.md +57 -12
  42. package/docs/README.ru.md +23 -4
  43. package/gui-experimental.cjs +4 -4
  44. package/package.json +5 -2
  45. package/src/core/audit.ts +291 -0
  46. package/src/core/native-notify.ts +154 -0
  47. package/src/core/record-history.ts +6 -4
  48. package/src/core/secrets.ts +385 -0
  49. package/src/core/structured-log.ts +9 -0
  50. package/src/core/telegram.ts +219 -0
  51. package/src/db/schema.ts +15 -0
  52. package/src/gui.tsx +543 -6
  53. package/src/index.ts +459 -22
  54. package/src/notifications.ts +232 -40
  55. package/src/rpc.ts +157 -0
  56. package/src/server.ts +67 -0
  57. package/src/settings.ts +213 -4
  58. package/src/workspaces.ts +22 -4
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-windows-scheduler",
3
- "version": "1.2.3",
3
+ "version": "1.4.0",
4
4
  "description": "OpenCode v2 plugin for scheduling and orchestrating AI agent jobs: cron, one-shot runs, DAG pipelines, matrix builds, quality gates, SQLite history, metrics and a local web dashboard. Windows, macOS and Linux. Free and open source (MIT).",
5
5
  "license": "MIT",
6
6
  "author": "opencode-windows-scheduler contributors",
@@ -69,7 +69,7 @@
69
69
  "demo": "node scripts/demo-dashboard.mjs",
70
70
  "prepare": "npm run build",
71
71
  "prepublishOnly": "npm run build && npm run build:gui",
72
- "test": "node test-sqlite.mjs && node test-crash-recovery.mjs && node test-workspaces.mjs && node test-role-scoped.mjs && node test-dry-run.mjs && node test-matrix.mjs && node test-matrix-lifecycle.mjs && node test-matrix-sync.mjs && node test-retention.mjs && node test-metrics.mjs && node test-schedule-v2.mjs && node test-notifications-v2.mjs && node test-profiles.mjs && node test-env.mjs && node test-agent-tools.mjs && node test-skill.mjs && node test-integrations.mjs && node test-one-shot.mjs && node test-session-continuity.mjs && node test-task-status.mjs && node test-jobs-view.mjs && node test-dag.mjs && node test-dashboard.mjs && node test-dashboard-dag.mjs && node test-dashboard-json.mjs && node test-docs.mjs",
72
+ "test": "node test-sqlite.mjs && node test-crash-recovery.mjs && node test-workspaces.mjs && node test-role-scoped.mjs && node test-dry-run.mjs && node test-matrix.mjs && node test-matrix-lifecycle.mjs && node test-matrix-sync.mjs && node test-retention.mjs && node test-metrics.mjs && node test-schedule-v2.mjs && node test-notifications-v2.mjs && node test-notifications-v3.mjs && node test-secrets.mjs && node test-audit.mjs && node test-profiles.mjs && node test-env.mjs && node test-agent-tools.mjs && node test-skill.mjs && node test-integrations.mjs && node test-one-shot.mjs && node test-session-continuity.mjs && node test-task-status.mjs && node test-jobs-view.mjs && node test-dag.mjs && node test-dashboard.mjs && node test-dashboard-dag.mjs && node test-dashboard-json.mjs && node test-docs.mjs",
73
73
  "test:sqlite": "node test-sqlite.mjs",
74
74
  "test:crash": "node test-crash-recovery.mjs",
75
75
  "test:workspaces": "node test-workspaces.mjs",
@@ -82,6 +82,9 @@
82
82
  "test:metrics": "node test-metrics.mjs",
83
83
  "test:schedule-v2": "node test-schedule-v2.mjs",
84
84
  "test:notifications-v2": "node test-notifications-v2.mjs",
85
+ "test:notifications-v3": "node test-notifications-v3.mjs",
86
+ "test:secrets": "node test-secrets.mjs",
87
+ "test:audit": "node test-audit.mjs",
85
88
  "test:profiles": "node test-profiles.mjs",
86
89
  "test:env": "node test-env.mjs",
87
90
  "test:agent": "node test-agent-tools.mjs",
@@ -0,0 +1,291 @@
1
+ import { getDb } from "../db/index.js";
2
+ import { redactSecretsInText } from "./secrets.js";
3
+
4
+ /**
5
+ * Журнал аудита мутаций (Спринт 26).
6
+ *
7
+ * Фиксирует кто, когда и через какой интерфейс создал / изменил / запустил /
8
+ * удалил задачу или настройки. Записи лежат в SQLite рядом с историей, поэтому
9
+ * аудит не зависит от файловых логов и переживает перезапуск. Любая ошибка
10
+ * записи проглатывается: аудит не должен ломать основную операцию.
11
+ */
12
+
13
+ export type AuditActor = "mcp" | "gui" | "http" | "system" | string;
14
+
15
+ export interface AuditEntryInput {
16
+ action: string;
17
+ targetType?: string | null;
18
+ target?: string | null;
19
+ actor: AuditActor;
20
+ /** Конкретный инструмент / RPC-метод / HTTP-маршрут. */
21
+ source?: string | null;
22
+ details?: unknown;
23
+ remote?: string | null;
24
+ /** Время события (ISO). По умолчанию — сейчас. */
25
+ ts?: string;
26
+ }
27
+
28
+ export interface AuditRecord {
29
+ id: number;
30
+ ts: string;
31
+ action: string;
32
+ targetType: string | null;
33
+ target: string | null;
34
+ actor: string;
35
+ source: string | null;
36
+ details: unknown;
37
+ remote: string | null;
38
+ }
39
+
40
+ export interface ReadAuditFilter {
41
+ action?: string;
42
+ target?: string;
43
+ actor?: string;
44
+ since?: string;
45
+ until?: string;
46
+ limit?: number;
47
+ }
48
+
49
+ export interface ReadAuditResult {
50
+ records: AuditRecord[];
51
+ total: number;
52
+ }
53
+
54
+ export const DEFAULT_AUDIT_RETENTION_DAYS = 90;
55
+ export const DEFAULT_AUDIT_MAX_RECORDS = 10_000;
56
+
57
+ const SENSITIVE_KEY_RE = /(TOKEN|SECRET|PASS|PASSWORD|PASSWD|API_?KEY|CREDENTIAL|AUTH)/i;
58
+ const PURE_SECRET_REF_RE = /^\$\{secret:[A-Za-z0-9_.-]{1,64}\}$/;
59
+
60
+ function looksLikeSecretRef(value: string): boolean {
61
+ return PURE_SECRET_REF_RE.test(value.trim());
62
+ }
63
+
64
+ /** Рекурсивно вычищает секреты из произвольной структуры details. */
65
+ export function redactAuditDetails(value: unknown, depth = 0): unknown {
66
+ if (depth > 8) return "[truncated]";
67
+ if (typeof value === "string") return redactSecretsInText(value);
68
+ if (value == null || typeof value !== "object") return value;
69
+ if (Array.isArray(value)) {
70
+ return value.slice(0, 200).map((item) => redactAuditDetails(item, depth + 1));
71
+ }
72
+ const result: Record<string, unknown> = {};
73
+ for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
74
+ if (
75
+ typeof item === "string" &&
76
+ SENSITIVE_KEY_RE.test(key) &&
77
+ !looksLikeSecretRef(item)
78
+ ) {
79
+ result[key] = "***";
80
+ } else {
81
+ result[key] = redactAuditDetails(item, depth + 1);
82
+ }
83
+ }
84
+ return result;
85
+ }
86
+
87
+ function safeJson(value: unknown): string | null {
88
+ if (value === undefined || value === null) return null;
89
+ try {
90
+ return JSON.stringify(redactAuditDetails(value));
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+
96
+ let lastCleanupAt = 0;
97
+
98
+ /**
99
+ * Записывает событие аудита. Никогда не бросает исключение.
100
+ * Возвращает id записи или null при ошибке.
101
+ */
102
+ export function recordAudit(entry: AuditEntryInput): number | null {
103
+ try {
104
+ const ts = entry.ts ?? new Date().toISOString();
105
+ const result = getDb()
106
+ .prepare(
107
+ `INSERT INTO audit_log
108
+ (ts, action, target_type, target, actor, source, details_json, remote)
109
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
110
+ )
111
+ .run(
112
+ ts,
113
+ String(entry.action || "unknown").slice(0, 128),
114
+ entry.targetType == null ? null : String(entry.targetType).slice(0, 64),
115
+ entry.target == null ? null : String(entry.target).slice(0, 256),
116
+ String(entry.actor || "system").slice(0, 32),
117
+ entry.source == null ? null : String(entry.source).slice(0, 128),
118
+ safeJson(entry.details),
119
+ entry.remote == null ? null : String(entry.remote).slice(0, 128)
120
+ );
121
+ maybeCleanup();
122
+ return Number(result.lastInsertRowid) || null;
123
+ } catch (err) {
124
+ try {
125
+ console.warn(
126
+ `[audit] не удалось записать событие: ${
127
+ err instanceof Error ? err.message : String(err)
128
+ }`
129
+ );
130
+ } catch {
131
+ // console недоступен — молча игнорируем.
132
+ }
133
+ return null;
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Ленивая ротация: не чаще раза в час, лимиты по умолчанию. Точные лимиты из
139
+ * settings применяются в cleanupHistory / manage_settings.
140
+ */
141
+ function maybeCleanup(): void {
142
+ const now = Date.now();
143
+ if (now - lastCleanupAt < 60 * 60 * 1000) return;
144
+ lastCleanupAt = now;
145
+ try {
146
+ cleanupAuditLog({
147
+ retentionDays: DEFAULT_AUDIT_RETENTION_DAYS,
148
+ maxRecords: DEFAULT_AUDIT_MAX_RECORDS,
149
+ });
150
+ } catch {
151
+ // очистка не критична
152
+ }
153
+ }
154
+
155
+ function rowToRecord(row: any): AuditRecord {
156
+ let details: unknown = null;
157
+ if (row.details_json) {
158
+ try {
159
+ details = JSON.parse(String(row.details_json));
160
+ } catch {
161
+ details = String(row.details_json);
162
+ }
163
+ }
164
+ return {
165
+ id: Number(row.id),
166
+ ts: String(row.ts),
167
+ action: String(row.action),
168
+ targetType: row.target_type == null ? null : String(row.target_type),
169
+ target: row.target == null ? null : String(row.target),
170
+ actor: String(row.actor ?? "system"),
171
+ source: row.source == null ? null : String(row.source),
172
+ details,
173
+ remote: row.remote == null ? null : String(row.remote),
174
+ };
175
+ }
176
+
177
+ /** Читает журнал аудита (новые сверху). */
178
+ export function readAuditLog(filter: ReadAuditFilter = {}): ReadAuditResult {
179
+ const limit = Math.max(1, Math.min(5000, Math.floor(filter.limit ?? 200) || 200));
180
+ const where: string[] = [];
181
+ const params: unknown[] = [];
182
+ if (filter.action?.trim()) {
183
+ where.push("action = ?");
184
+ params.push(filter.action.trim());
185
+ }
186
+ if (filter.target?.trim()) {
187
+ where.push("target = ?");
188
+ params.push(filter.target.trim());
189
+ }
190
+ if (filter.actor?.trim()) {
191
+ where.push("actor = ?");
192
+ params.push(filter.actor.trim());
193
+ }
194
+ if (filter.since?.trim()) {
195
+ where.push("ts >= ?");
196
+ params.push(filter.since.trim());
197
+ }
198
+ if (filter.until?.trim()) {
199
+ where.push("ts <= ?");
200
+ params.push(filter.until.trim());
201
+ }
202
+ const clause = where.length ? `WHERE ${where.join(" AND ")}` : "";
203
+ try {
204
+ const db = getDb();
205
+ const totalRow = db
206
+ .prepare(`SELECT COUNT(*) AS count FROM audit_log ${clause}`)
207
+ .get(...params) as any;
208
+ const rows = db
209
+ .prepare(`SELECT * FROM audit_log ${clause} ORDER BY ts DESC, id DESC LIMIT ?`)
210
+ .all(...params, limit) as any[];
211
+ return { records: rows.map(rowToRecord), total: Number(totalRow?.count) || 0 };
212
+ } catch (err) {
213
+ try {
214
+ console.warn(
215
+ `[audit] не удалось прочитать журнал: ${
216
+ err instanceof Error ? err.message : String(err)
217
+ }`
218
+ );
219
+ } catch {
220
+ // ignore
221
+ }
222
+ return { records: [], total: 0 };
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Удаляет старые записи и лишние сверх maxRecords.
228
+ * Возвращает количество удалённых строк.
229
+ */
230
+ export function cleanupAuditLog(options: {
231
+ retentionDays?: number;
232
+ maxRecords?: number;
233
+ } = {}): number {
234
+ const retentionDays = Math.max(
235
+ 0,
236
+ Math.floor(options.retentionDays ?? DEFAULT_AUDIT_RETENTION_DAYS) || 0
237
+ );
238
+ const maxRecords = Math.max(
239
+ 100,
240
+ Math.floor(options.maxRecords ?? DEFAULT_AUDIT_MAX_RECORDS) || DEFAULT_AUDIT_MAX_RECORDS
241
+ );
242
+ let deleted = 0;
243
+ try {
244
+ const db = getDb();
245
+ if (retentionDays > 0) {
246
+ const cutoff = new Date(
247
+ Date.now() - retentionDays * 24 * 60 * 60 * 1000
248
+ ).toISOString();
249
+ const result = db.prepare("DELETE FROM audit_log WHERE ts < ?").run(cutoff);
250
+ deleted += Number(result.changes) || 0;
251
+ }
252
+ const countRow = db.prepare("SELECT COUNT(*) AS count FROM audit_log").get() as any;
253
+ const count = Number(countRow?.count) || 0;
254
+ if (count > maxRecords) {
255
+ const excess = count - maxRecords;
256
+ const result = db
257
+ .prepare(
258
+ `DELETE FROM audit_log WHERE id IN (
259
+ SELECT id FROM audit_log ORDER BY ts ASC, id ASC LIMIT ?
260
+ )`
261
+ )
262
+ .run(excess);
263
+ deleted += Number(result.changes) || 0;
264
+ }
265
+ } catch (err) {
266
+ try {
267
+ console.warn(
268
+ `[audit] не удалось очистить журнал: ${
269
+ err instanceof Error ? err.message : String(err)
270
+ }`
271
+ );
272
+ } catch {
273
+ // ignore
274
+ }
275
+ }
276
+ return deleted;
277
+ }
278
+
279
+ /** Удаляет все записи (тесты / обслуживание). */
280
+ export function clearAuditLog(): void {
281
+ try {
282
+ getDb().exec("DELETE FROM audit_log");
283
+ } catch {
284
+ // ignore
285
+ }
286
+ }
287
+
288
+ /** Сбрасывает троттлинг очистки (для тестов). */
289
+ export function resetAuditCleanupThrottle(): void {
290
+ lastCleanupAt = 0;
291
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Нативные уведомления ОС (Спринт 25).
3
+ *
4
+ * Windows — Toast через PowerShell/WinRT, macOS — Notification Center через
5
+ * osascript, Linux — notify-send (libnotify). Внешних зависимостей нет:
6
+ * node-notifier не требуется. Все ошибки проглатываются намеренно —
7
+ * уведомление не должно ломать задачу.
8
+ */
9
+ import { execFile } from "node:child_process";
10
+ import { promisify } from "node:util";
11
+
12
+ const execFileAsync = promisify(execFile);
13
+
14
+ /** Таймаут запуска процесса уведомления. */
15
+ const DEFAULT_TIMEOUT_MS = 15_000;
16
+
17
+ export interface NativeNotificationMessage {
18
+ /** Заголовок; по умолчанию «OpenCode Scheduler». */
19
+ title?: string;
20
+ /** Текст уведомления. */
21
+ body: string;
22
+ /** Со звуком, если платформа поддерживает. */
23
+ sound?: boolean;
24
+ }
25
+
26
+ /** Готовая команда запуска — удобно проверять в тестах. */
27
+ export interface NativeCommand {
28
+ command: string;
29
+ args: string[];
30
+ env?: Record<string, string>;
31
+ }
32
+
33
+ /** Скрипт Windows Toast: текст передаётся через env, чтобы не экранировать кавычки. */
34
+ const WINDOWS_TOAST_SCRIPT = `
35
+ $ErrorActionPreference = 'Stop'
36
+ $title = [System.Security.SecurityElement]::Escape($env:OCS_NOTIFY_TITLE)
37
+ $body = [System.Security.SecurityElement]::Escape($env:OCS_NOTIFY_BODY)
38
+ $silent = if ($env:OCS_NOTIFY_SOUND -eq '1') { '' } else { '<audio silent="true"/>' }
39
+ $xml = '<toast><visual><binding template="ToastGeneric"><text>' + $title + '</text><text>' + $body + '</text></binding></visual>' + $silent + '</toast>'
40
+ [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType=WindowsRuntime] > $null
41
+ [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType=WindowsRuntime] > $null
42
+ $doc = [Windows.Data.Xml.Dom.XmlDocument]::new()
43
+ $doc.LoadXml($xml)
44
+ $toast = [Windows.UI.Notifications.ToastNotification]::new($doc)
45
+ $appId = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe'
46
+ [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($appId).Show($toast)
47
+ `.trim();
48
+
49
+ /**
50
+ * Собирает команду нативного уведомления для платформы.
51
+ * Чистая функция: ничего не запускает.
52
+ */
53
+ export function buildNativeNotificationCommand(
54
+ platform: NodeJS.Platform,
55
+ message: NativeNotificationMessage
56
+ ): NativeCommand {
57
+ const title = (message.title ?? "OpenCode Scheduler").trim() || "OpenCode Scheduler";
58
+ const body = String(message.body ?? "");
59
+ const sound = message.sound !== false;
60
+
61
+ if (platform === "win32") {
62
+ return {
63
+ command: "powershell.exe",
64
+ args: [
65
+ "-NoProfile",
66
+ "-NonInteractive",
67
+ "-ExecutionPolicy",
68
+ "Bypass",
69
+ "-Command",
70
+ WINDOWS_TOAST_SCRIPT,
71
+ ],
72
+ env: {
73
+ OCS_NOTIFY_TITLE: title,
74
+ OCS_NOTIFY_BODY: body,
75
+ OCS_NOTIFY_SOUND: sound ? "1" : "0",
76
+ },
77
+ };
78
+ }
79
+
80
+ if (platform === "darwin") {
81
+ const script =
82
+ 'display notification (system attribute "OCS_NOTIFY_BODY") ' +
83
+ 'with title (system attribute "OCS_NOTIFY_TITLE")' +
84
+ (sound ? ' sound name "Glass"' : "");
85
+ return {
86
+ command: "osascript",
87
+ args: ["-e", script],
88
+ env: {
89
+ OCS_NOTIFY_TITLE: title,
90
+ OCS_NOTIFY_BODY: body,
91
+ },
92
+ };
93
+ }
94
+
95
+ return {
96
+ command: "notify-send",
97
+ args: [
98
+ "-a",
99
+ "OpenCode Scheduler",
100
+ "-u",
101
+ "normal",
102
+ "-i",
103
+ "dialog-information",
104
+ title,
105
+ body,
106
+ ],
107
+ };
108
+ }
109
+
110
+ export interface SendNativeOptions {
111
+ /** Подмена платформы для тестов. */
112
+ platform?: NodeJS.Platform;
113
+ /** Подмена запуска процесса для тестов. */
114
+ exec?: (command: string, args: string[], env: NodeJS.ProcessEnv) => Promise<void>;
115
+ /** Таймаут процесса в мс. */
116
+ timeoutMs?: number;
117
+ }
118
+
119
+ export interface NativeSendResult {
120
+ success: boolean;
121
+ error?: string;
122
+ }
123
+
124
+ /**
125
+ * Показывает нативное уведомление. Никогда не бросает исключение.
126
+ */
127
+ export async function sendNativeNotification(
128
+ message: NativeNotificationMessage,
129
+ options: SendNativeOptions = {}
130
+ ): Promise<NativeSendResult> {
131
+ const platform = options.platform ?? process.platform;
132
+ const command = buildNativeNotificationCommand(platform, message);
133
+ const env = { ...process.env, ...(command.env ?? {}) };
134
+ const timeoutMs = Math.max(1_000, Math.floor(options.timeoutMs ?? DEFAULT_TIMEOUT_MS));
135
+
136
+ try {
137
+ if (options.exec) {
138
+ await options.exec(command.command, command.args, env);
139
+ } else {
140
+ await execFileAsync(command.command, command.args, {
141
+ env,
142
+ timeout: timeoutMs,
143
+ windowsHide: true,
144
+ maxBuffer: 1024 * 1024,
145
+ });
146
+ }
147
+ return { success: true };
148
+ } catch (err: any) {
149
+ return {
150
+ success: false,
151
+ error: err instanceof Error ? err.message : String(err),
152
+ };
153
+ }
154
+ }
@@ -337,7 +337,7 @@ async function main() {
337
337
  return;
338
338
  }
339
339
 
340
- await handleCompletion(taskName, st, chainTarget, error, durationMs);
340
+ await handleCompletion(taskName, st, chainTarget, error, durationMs, tokens, costUsd);
341
341
  return;
342
342
  }
343
343
 
@@ -389,7 +389,7 @@ async function main() {
389
389
  definition?.deniedTools ?? null
390
390
  );
391
391
 
392
- await handleCompletion(taskName, st, chainTarget, error, durationMs);
392
+ await handleCompletion(taskName, st, chainTarget, error, durationMs, tokens, costUsd);
393
393
  }
394
394
 
395
395
  /**
@@ -401,11 +401,13 @@ async function handleCompletion(
401
401
  st: Status,
402
402
  chainTarget: string | null,
403
403
  error: string | null,
404
- durationMs: number
404
+ durationMs: number,
405
+ tokens?: number | null,
406
+ costUsd?: number | null
405
407
  ): Promise<void> {
406
408
  // Уведомление о завершении (webhook). Ошибки отправки логируются внутри
407
409
  // и не влияют на историю, цепочки и повторы.
408
- await notifyTaskCompletion(taskName, st, durationMs, error);
410
+ await notifyTaskCompletion(taskName, st, durationMs, error, tokens, costUsd);
409
411
 
410
412
  // Matrix (Спринт 15): клон завершился — двигаем sequential-цепочку или
411
413
  // очередь concurrency-лимита (Спринт 17), а когда все клоны готовы —