@goodandready/dsh-cron 0.3.43 → 0.3.45

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 (42) hide show
  1. package/lib/client.js +998 -3987
  2. package/lib/llm-ask.js +2 -1
  3. package/lib/routes/api-actions.js +36 -6
  4. package/lib/routes/api-item.js +1 -1
  5. package/lib/routes/api-webhook.js +2 -4
  6. package/lib/runtimes/runner-external.js +2 -3
  7. package/lib/runtimes/runner-session.js +385 -0
  8. package/lib/runtimes/runner-turn.js +255 -0
  9. package/lib/runtimes/runner.js +43 -616
  10. package/lib/scheduler/scheduler-execution.js +4 -1
  11. package/lib/scheduler/scheduler-lifecycle.js +65 -0
  12. package/lib/scheduler/scheduler-parser.js +261 -0
  13. package/lib/scheduler/scheduler.js +13 -319
  14. package/lib/store/store-archive.js +195 -0
  15. package/lib/store/store-io.js +331 -0
  16. package/lib/store/store-loader.js +165 -0
  17. package/lib/store/store-migration.js +38 -0
  18. package/lib/store/store-settings.js +126 -0
  19. package/lib/store/store-stats.js +55 -0
  20. package/lib/store/store.js +75 -888
  21. package/package.json +8 -6
  22. package/lib/client-src/00-open.js +0 -63
  23. package/lib/client-src/10-locales.js +0 -540
  24. package/lib/client-src/20-styles.js +0 -64
  25. package/lib/client-src/30-utils.js +0 -372
  26. package/lib/client-src/40-delivery-settings.js +0 -96
  27. package/lib/client-src/45-dag-graph-view.js +0 -287
  28. package/lib/client-src/46-live-logs-modal.js +0 -108
  29. package/lib/client-src/47-analytics-digest-modal.js +0 -166
  30. package/lib/client-src/48-timeline-heatmap-view.js +0 -176
  31. package/lib/client-src/50-cron-screen-state.js +0 -457
  32. package/lib/client-src/52-cron-screen-actions.js +0 -330
  33. package/lib/client-src/53-cron-screen-modal-actions.js +0 -677
  34. package/lib/client-src/54-cron-screen-analytics-actions.js +0 -68
  35. package/lib/client-src/55-cron-screen-view.js +0 -378
  36. package/lib/client-src/60-modal-task-form-head.js +0 -581
  37. package/lib/client-src/62-modal-task-form-tail.js +0 -563
  38. package/lib/client-src/65-modal-dialogs.js +0 -350
  39. package/lib/client-src/70-settings-card.js +0 -453
  40. package/lib/client-src/75-quick-action-bar.js +0 -146
  41. package/lib/client-src/80-sidebar-jobs.js +0 -200
  42. package/lib/client-src/90-close.js +0 -219
@@ -4,72 +4,58 @@ import { ArtifactManager } from './artifacts.js';
4
4
  import { logger } from '../logger.js';
5
5
  import { bestEffort } from '../best-effort.js';
6
6
  import fs from 'node:fs';
7
- import { gzipSync, gunzipSync } from 'node:zlib';
8
- import { pipeline } from 'node:stream/promises';
9
7
  import path from 'node:path';
10
- import { getDshDefaultTelegramCredentials } from '../telegram.js';
11
8
 
12
- /**
13
- * Where plugin data lives.
14
- *
15
- * DSH_DATA_DIR wins when the harness sets it. Otherwise the profile home
16
- * (DSH_HOME) is authoritative: falling back to ~/.dsh would make an isolated
17
- * profile — a test contour, a second profile — write its tasks into another
18
- * home's data directory, which is how an isolated test cycle once leaked a
19
- * task into the wrong profile.
20
- */
21
-
22
- export const CURRENT_SCHEMA_VERSION = 2;
23
-
24
- export function runStoreMigrations(data, fromVersion = 1, toVersion = CURRENT_SCHEMA_VERSION) {
25
- if (!data || typeof data !== 'object') return data;
26
- let current = { ...data };
27
-
28
- // Migration from version 1 to 2 (Issue #390 & #393)
29
- if (fromVersion < 2 && toVersion >= 2) {
30
- if (Array.isArray(current.tasks)) {
31
- current.tasks = current.tasks.map((task) => {
32
- if (!task || typeof task !== 'object') return task;
33
- return {
34
- ...task,
35
- maxMemoryMb: task.maxMemoryMb !== undefined ? Number(task.maxMemoryMb) : 0,
36
- executionTimeoutMs: task.executionTimeoutMs !== undefined
37
- ? Number(task.executionTimeoutMs)
38
- : (Number(task.timeoutSeconds) > 0 ? Number(task.timeoutSeconds) * 1000 : 900000),
39
- maxLogBytesPerRun: task.maxLogBytesPerRun !== undefined ? Number(task.maxLogBytesPerRun) : (5 * 1024 * 1024),
40
- cpus: task.cpus !== undefined ? Number(task.cpus) : 0,
41
- maxArchiveMonths: task.maxArchiveMonths !== undefined ? Number(task.maxArchiveMonths) : 6,
42
- };
43
- });
44
- }
45
- current.schemaVersion = 2;
46
- }
47
-
48
- return current;
49
- }
50
-
51
- export function getDefaultStorePath() {
52
- const base = process.env.DSH_DATA_DIR
53
- || (process.env.DSH_HOME
54
- ? path.join(process.env.DSH_HOME, 'data')
55
- : path.join(process.env.HOME || '.', '.dsh', 'data'));
56
- return path.join(base, 'cron', 'tasks.json');
57
- }
58
-
59
- /** Mask a secret for transport to the browser, keeping a readable hint. */
60
- function maskSecretValue(value) {
61
- const s = String(value == null ? '' : value);
62
- if (!s) return '';
63
- if (s.length <= 8) return '••••••••';
64
- return s.slice(0, 4) + '••••••••' + s.slice(-3);
65
- }
66
-
67
-
68
- export function isAccessOrIoError(err) {
69
- if (!err) return false;
70
- const codes = ['EACCES', 'EPERM', 'EIO', 'EBUSY', 'EROFS', 'EMFILE', 'ENFILE'];
71
- return Boolean(err.code && codes.includes(err.code));
72
- }
9
+ import {
10
+ CURRENT_SCHEMA_VERSION,
11
+ runStoreMigrations,
12
+ getDefaultStorePath,
13
+ } from './store-migration.js';
14
+
15
+ import { initStore } from './store-loader.js';
16
+
17
+ import {
18
+ isAccessOrIoError,
19
+ cleanOrphanedTmpFiles,
20
+ scheduleSave,
21
+ flushSync,
22
+ createSnapshot,
23
+ waitForDiskVersion,
24
+ notifyDiskVersion,
25
+ saveAsync,
26
+ writeStoreStream,
27
+ save,
28
+ } from './store-io.js';
29
+
30
+ import {
31
+ archiveHistoryRuns,
32
+ listMonthlyArchives,
33
+ getMonthlyArchive,
34
+ pruneOldMonthlyArchives,
35
+ getArchivedRuns,
36
+ } from './store-archive.js';
37
+
38
+ import {
39
+ maskSecretValue,
40
+ FORBIDDEN_SETTING_KEYS,
41
+ MASKED_SETTING_KEYS,
42
+ getSettings,
43
+ getClientSettings,
44
+ saveSettings,
45
+ } from './store-settings.js';
46
+
47
+ import {
48
+ getTaskStats,
49
+ getAggregatedStats,
50
+ } from './store-stats.js';
51
+
52
+ export {
53
+ CURRENT_SCHEMA_VERSION,
54
+ runStoreMigrations,
55
+ getDefaultStorePath,
56
+ isAccessOrIoError,
57
+ maskSecretValue,
58
+ };
73
59
 
74
60
  export class TaskStore {
75
61
  constructor(filePath) {
@@ -97,171 +83,9 @@ export class TaskStore {
97
83
  }
98
84
 
99
85
  init() {
100
- const dir = path.dirname(this.filePath);
101
- if (!fs.existsSync(dir)) {
102
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
103
- }
104
- bestEffort('chmod-dir', () => fs.chmodSync(dir, 0o700));
105
- this._cleanOrphanedTmpFiles(dir);
106
- const bakPath = `${this.filePath}.bak`;
107
-
108
- const loadData = (raw) => {
109
- let data = JSON.parse(raw);
110
- const storedVersion = Number(data.schemaVersion) || 1;
111
- if (storedVersion < CURRENT_SCHEMA_VERSION) {
112
- // Pre-migration backup (#390)
113
- try {
114
- const preBakPath = `${this.filePath}.bak-v${storedVersion}-${Date.now()}`;
115
- fs.writeFileSync(preBakPath, raw, { encoding: 'utf-8', mode: 0o600 });
116
- bestEffort('chmod-pre-bak', () => fs.chmodSync(preBakPath, 0o600));
117
- logger.info(`[dsh-cron] pre-migration backup saved to ${preBakPath}`);
118
- } catch (bakErr) {
119
- logger.warn('[dsh-cron] failed to write pre-migration backup:', bakErr.message);
120
- }
121
- data = runStoreMigrations(data, storedVersion, CURRENT_SCHEMA_VERSION);
122
- this._needsMigrationFlush = true;
123
- }
124
- this.tasks.clear();
125
- this.history.clear();
126
- if (Array.isArray(data.tasks)) {
127
- const now = Date.now();
128
- const cutoff24h = now - 86400000;
129
- for (const t of data.tasks) {
130
- if (Array.isArray(t.costLedger) && t.costLedger.length > 0) {
131
- t.costLedger = t.costLedger.filter(e => e && typeof e.at === 'number' && e.at >= cutoff24h);
132
- } else {
133
- // Seed from active history if present (#221)
134
- const hist = (data.history && Array.isArray(data.history[t.id])) ? data.history[t.id] : [];
135
- t.costLedger = hist
136
- .filter(r => r && typeof r.at === 'number' && r.at >= cutoff24h)
137
- .map(r => ({
138
- at: r.at,
139
- costUsd: Number(r.costUsd) || 0,
140
- tokens: (r.usage?.inputTokens || 0) + (r.usage?.outputTokens || 0) + (r.usage?.cacheReadTokens || 0),
141
- }));
142
- }
143
- this.tasks.set(t.id, t);
144
- }
145
- }
146
- if (data.history && typeof data.history === 'object') {
147
- for (const [k, v] of Object.entries(data.history)) {
148
- this.history.set(k, Array.isArray(v) ? v : []);
149
- }
150
- }
151
- if (data.settings && typeof data.settings === 'object') {
152
- this.settings = data.settings;
153
- }
154
- if (data.chainCheckpoints && typeof data.chainCheckpoints === 'object') {
155
- this.chainCheckpoints = data.chainCheckpoints;
156
- }
157
- if (data.artifacts && typeof data.artifacts === 'object') {
158
- this.artifacts = data.artifacts;
159
- }
160
- };
161
-
162
- let loaded = false;
163
- if (fs.existsSync(this.filePath)) {
164
- try {
165
- bestEffort('chmod-store', () => fs.chmodSync(this.filePath, 0o600));
166
- const raw = fs.readFileSync(this.filePath, 'utf-8');
167
- loadData(raw);
168
- loaded = true;
169
- this._readOnly = false;
170
- this._loadFailed = false;
171
- this._accessErrorCode = null;
172
- this._loadError = null;
173
-
174
- if (!fs.existsSync(bakPath)) {
175
- bestEffort('backup-initial', () => {
176
- fs.copyFileSync(this.filePath, bakPath);
177
- fs.chmodSync(bakPath, 0o600);
178
- });
179
- } else {
180
- bestEffort('chmod-bak', () => fs.chmodSync(bakPath, 0o600));
181
- }
182
- } catch (err) {
183
- if (isAccessOrIoError(err)) {
184
- // File exists on disk but is inaccessible due to OS permissions/IO error (#435)
185
- this._enterReadOnlyMode(err, 'read', this.filePath);
186
- } else {
187
- // Genuine corruption or invalid data structure
188
- logger.error(`[dsh-cron] store read error (corrupted file): ${err.message}`);
189
- try {
190
- const corruptedPath = `${this.filePath}.corrupted.${Date.now()}`;
191
- fs.copyFileSync(this.filePath, corruptedPath);
192
- bestEffort('chmod-corrupted', () => fs.chmodSync(corruptedPath, 0o600));
193
- logger.warn(`[dsh-cron] corrupted store backed up to ${corruptedPath}`);
194
- } catch (snapErr) {
195
- logger.error('[dsh-cron] failed to snapshot corrupted store:', snapErr.message);
196
- }
197
- if (fs.existsSync(bakPath)) {
198
- try {
199
- bestEffort('chmod-bak', () => fs.chmodSync(bakPath, 0o600));
200
- const rawBak = fs.readFileSync(bakPath, 'utf-8');
201
- loadData(rawBak);
202
- loaded = true;
203
- this._readOnly = false;
204
- this._loadFailed = false;
205
- this._accessErrorCode = null;
206
- this._loadError = null;
207
- logger.warn(`[dsh-cron] successfully recovered tasks store from ${bakPath}`);
208
- } catch (bakErr) {
209
- if (isAccessOrIoError(bakErr)) {
210
- this._enterReadOnlyMode(bakErr, 'read', bakPath);
211
- } else {
212
- logger.error('[dsh-cron] failed to recover tasks store from .bak:', bakErr.message);
213
- this._enterReadOnlyMode(bakErr, 'parse', bakPath);
214
- }
215
- }
216
- } else {
217
- this._enterReadOnlyMode(err, 'parse', this.filePath);
218
- }
219
- }
220
- }
221
- } else if (fs.existsSync(bakPath)) {
222
- try {
223
- bestEffort('chmod-bak', () => fs.chmodSync(bakPath, 0o600));
224
- const rawBak = fs.readFileSync(bakPath, 'utf-8');
225
- loadData(rawBak);
226
- loaded = true;
227
- this._readOnly = false;
228
- this._loadFailed = false;
229
- this._accessErrorCode = null;
230
- this._loadError = null;
231
- bestEffort('restore-from-bak', () => {
232
- fs.copyFileSync(bakPath, this.filePath);
233
- fs.chmodSync(this.filePath, 0o600);
234
- });
235
- logger.warn(`[dsh-cron] restored missing tasks store from ${bakPath}`);
236
- } catch (bakErr) {
237
- if (isAccessOrIoError(bakErr)) {
238
- this._enterReadOnlyMode(bakErr, 'read', bakPath);
239
- } else {
240
- logger.error('[dsh-cron] failed to restore tasks store from .bak:', bakErr.message);
241
- this._enterReadOnlyMode(bakErr, 'parse', bakPath);
242
- }
243
- }
244
- } else {
245
- // Clean initial start: neither primary nor backup exists yet (#435)
246
- this._readOnly = false;
247
- this._loadFailed = false;
248
- this._accessErrorCode = null;
249
- this._loadError = null;
250
- }
251
-
252
- if (this._needsMigrationFlush && !this._readOnly && !this._loadFailed) {
253
- this._needsMigrationFlush = false;
254
- this.scheduleSave(100);
255
- }
256
- if (!this._readOnly && !this._loadFailed) {
257
- bestEffort('prune-old-archives', () => this._pruneOldMonthlyArchives(dir, 6));
258
- }
86
+ initStore(this);
259
87
  }
260
88
 
261
- /**
262
- * Schedule a debounced save using the asynchronous write queue to avoid
263
- * blocking the event loop on large task stores (#244).
264
- */
265
89
  _enterReadOnlyMode(err, operation = 'read', filePath = this.filePath) {
266
90
  this._readOnly = true;
267
91
  this._loadFailed = true;
@@ -305,336 +129,35 @@ export class TaskStore {
305
129
  }
306
130
 
307
131
  scheduleSave(delay = 50) {
308
- if (this._readOnly || this._loadFailed) {
309
- return;
310
- }
311
- if (this._saveTimer) return;
312
- this._saveTimer = setTimeout(() => {
313
- this._saveTimer = null;
314
- this.saveAsync().catch((err) => {
315
- logger.error('[dsh-cron] debounced save failed:', err.message);
316
- });
317
- }, delay);
318
- if (typeof this._saveTimer.unref === 'function') {
319
- this._saveTimer.unref();
320
- }
132
+ return scheduleSave(this, delay);
321
133
  }
322
134
 
323
- /**
324
- * Synchronously flush any pending debounced save to disk.
325
- */
326
135
  flushSync() {
327
- if (this._saveTimer) {
328
- clearTimeout(this._saveTimer);
329
- this._saveTimer = null;
330
- }
331
- if (this._readOnly || this._loadFailed) {
332
- return;
333
- }
334
- this.save();
136
+ return flushSync(this);
335
137
  }
336
138
 
337
- /**
338
- * Asynchronously serialize and write tasks store to disk using fs.promises queue (#244).
339
- * Safe mode 0600 on files and 0700 on dir (#222).
340
- */
341
- /**
342
- * Create an isolated deep snapshot of tasks, history, and settings (#301).
343
- * Prevents concurrent in-memory mutations (e.g. recordRun during streamed save)
344
- * from corrupting serialized JSON state or causing duplicate / skipped run records.
345
- */
346
139
  _createSnapshot() {
347
- const tasksSnapshot = Array.from(this.tasks.values()).map((t) => ({
348
- ...t,
349
- costLedger: Array.isArray(t.costLedger) ? t.costLedger.slice() : t.costLedger,
350
- }));
351
- const historySnapshot = {};
352
- for (const [id, runs] of this.history.entries()) {
353
- historySnapshot[id] = Array.isArray(runs) ? runs.slice() : runs;
354
- }
355
- return {
356
- version: 1,
357
- schemaVersion: CURRENT_SCHEMA_VERSION,
358
- updatedAt: new Date().toISOString(),
359
- tasks: tasksSnapshot,
360
- history: historySnapshot,
361
- settings: this.settings ? { ...this.settings } : {},
362
- chainCheckpoints: this.chainCheckpoints ? { ...this.chainCheckpoints } : {},
363
- artifacts: this.artifacts ? { ...this.artifacts } : {},
364
- };
140
+ return createSnapshot(this);
365
141
  }
366
142
 
367
- /**
368
- * Asynchronously serialize and write tasks store to disk using fs.promises queue (#244, #301, #303).
369
- * Safe mode 0600 on files and 0700 on dir (#222).
370
- */
371
- /**
372
- * Wait until diskVersion or lastSyncVersion is at least the target version (#372).
373
- */
374
143
  _waitForDiskVersion(version) {
375
- if ((this._diskVersion || 0) >= version || (this._lastSyncVersion || 0) >= version) {
376
- return Promise.resolve();
377
- }
378
- return new Promise((resolve, reject) => {
379
- if (!this._diskWaiters) this._diskWaiters = [];
380
- this._diskWaiters.push({ version, resolve, reject });
381
- });
144
+ return waitForDiskVersion(this, version);
382
145
  }
383
146
 
384
147
  _notifyDiskVersion(writtenVersion, err = null) {
385
- if (!this._diskWaiters || this._diskWaiters.length === 0) return;
386
- const remaining = [];
387
- for (const waiter of this._diskWaiters) {
388
- if (err) {
389
- waiter.reject(err);
390
- } else if ((this._diskVersion || 0) >= waiter.version || (this._lastSyncVersion || 0) >= waiter.version) {
391
- waiter.resolve();
392
- } else {
393
- remaining.push(waiter);
394
- }
395
- }
396
- this._diskWaiters = remaining;
148
+ return notifyDiskVersion(this, writtenVersion, err);
397
149
  }
398
150
 
399
151
  async saveAsync() {
400
- if (this._readOnly || this._loadFailed) {
401
- const reason = this._accessErrorCode
402
- ? `access error (${this._accessErrorCode})`
403
- : (this._loadError ? this._loadError.message : 'unrecovered read failure');
404
- logger.error(`[dsh-cron] saveAsync blocked: store is in read-only recovery mode due to ${reason} on "${this.filePath}". File on disk was preserved.`);
405
- return Promise.reject(new Error(`Store write blocked: read-only recovery mode (${this.filePath})`));
406
- }
407
- if (this._saveTimer) {
408
- clearTimeout(this._saveTimer);
409
- this._saveTimer = null;
410
- }
411
- const version = ++this._saveVersion;
412
- const data = this._createSnapshot();
413
-
414
- const writeOp = async () => {
415
- if ((this._diskVersion || 0) >= version || (this._lastSyncVersion || 0) >= version) {
416
- this._notifyDiskVersion(version);
417
- return;
418
- }
419
- const dir = path.dirname(this.filePath);
420
- await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 });
421
- bestEffort('chmod-dir', () => fs.chmodSync(dir, 0o700));
422
-
423
- const rand = Math.random().toString(36).slice(2, 8);
424
- const tmp = `${this.filePath}.tmp.${process.pid}_${Date.now()}_${rand}`;
425
- this._currentAsyncTmp = tmp;
426
-
427
- // Streamed chunked serialization with fine-grained event loop yields (#244).
428
- // Eliminates continuous CPU stalls on large stores (~21MB) by batching tasks and history runs
429
- // with setImmediate yields every 10 tasks and 15 runs, guaranteeing max event loop lag < 10ms.
430
- try {
431
- await this._writeStoreStream(tmp, data, version);
432
- bestEffort('chmod-tmp', () => fs.chmodSync(tmp, 0o600));
433
- } catch (writeErr) {
434
- await fs.promises.unlink(tmp).catch(() => {});
435
- if (this._currentAsyncTmp === tmp) this._currentAsyncTmp = null;
436
- this._notifyDiskVersion(null, writeErr);
437
- throw writeErr;
438
- }
439
-
440
- if ((this._diskVersion || 0) >= version || (this._lastSyncVersion || 0) >= version || this._saveVersion > version) {
441
- await fs.promises.unlink(tmp).catch(() => {});
442
- if (this._currentAsyncTmp === tmp) this._currentAsyncTmp = null;
443
- // Do not notify waiters yet: a newer queued saveOp will write to disk and notify (#372)
444
- return;
445
- }
446
-
447
- try {
448
- await fs.promises.rename(tmp, this.filePath);
449
- bestEffort('chmod-store', () => fs.chmodSync(this.filePath, 0o600));
450
- this._currentAsyncTmp = null;
451
- this._diskVersion = Math.max(this._diskVersion || 0, version);
452
- this._lastWrittenVersion = this._diskVersion;
453
- this._notifyDiskVersion(this._diskVersion);
454
- } catch (err) {
455
- this._currentAsyncTmp = null;
456
- // If tmp was unlinked by newer sync save, rename will fail with ENOENT - safely ignore only in that case (#244)
457
- if (err.code === 'ENOENT' && (this._lastSyncVersion || 0) >= version) {
458
- this._notifyDiskVersion(version);
459
- return;
460
- }
461
- this._notifyDiskVersion(null, err);
462
- throw err;
463
- }
464
-
465
- const now = Date.now();
466
- if (now - this._lastBackupTime > 60000) {
467
- this._lastBackupTime = now;
468
- try {
469
- const bakPath = `${this.filePath}.bak`;
470
- await fs.promises.copyFile(this.filePath, bakPath);
471
- bestEffort('chmod-bak', () => fs.chmodSync(bakPath, 0o600));
472
- } catch (bakErr) {
473
- logger.warn('[dsh-cron] async backup copy failed:', bakErr.message);
474
- }
475
- }
476
- };
477
-
478
- this._savePromise = this._savePromise.then(writeOp, writeOp);
479
- await this._savePromise;
480
- await this._waitForDiskVersion(version);
152
+ return saveAsync(this);
481
153
  }
482
154
 
483
- /**
484
- * Stream data incrementally to disk with fine-grained setImmediate yields (#244).
485
- * Prevents blocking the V8 single thread on heavy serialization (e.g. 21MB / 10k runs).
486
- */
487
- /**
488
- * Stream data incrementally to disk with fine-grained setImmediate yields (#244, #303).
489
- * Prevents blocking the V8 single thread on heavy serialization (e.g. 21MB / 10k runs).
490
- * Uses canonical Node stream/promises pipeline for error-handling and backpressure hygiene (#303).
491
- */
492
155
  async _writeStoreStream(filePath, data, version) {
493
- const isCanceled = () => {
494
- return (
495
- (this._diskVersion || 0) >= version ||
496
- (this._lastSyncVersion || 0) >= version ||
497
- this._saveVersion > version
498
- );
499
- };
500
-
501
- if (isCanceled()) {
502
- return;
503
- }
504
-
505
- const ac = new AbortController();
506
- let ws;
507
- try {
508
- ws = fs.createWriteStream(filePath, { encoding: 'utf-8', mode: 0o600 });
509
- } catch (createErr) {
510
- if (isCanceled()) return;
511
- throw createErr;
512
- }
513
-
514
- async function* generateChunks() {
515
- await new Promise((r) => setImmediate(r));
516
- if (isCanceled()) {
517
- ac.abort();
518
- return;
519
- }
520
-
521
- yield '{"version":' + JSON.stringify(data.version || 1);
522
- yield ',"schemaVersion":' + JSON.stringify(data.schemaVersion || CURRENT_SCHEMA_VERSION);
523
- yield ',"updatedAt":' + JSON.stringify(data.updatedAt || new Date().toISOString());
524
- yield ',"settings":' + JSON.stringify(data.settings || {});
525
-
526
- yield ',"tasks":[';
527
- const tasks = data.tasks || [];
528
- for (let i = 0; i < tasks.length; i++) {
529
- if (isCanceled()) {
530
- ac.abort();
531
- return;
532
- }
533
- if (i > 0) yield ',';
534
- yield JSON.stringify(tasks[i]);
535
- if ((i + 1) % 10 === 0) {
536
- await new Promise((r) => setImmediate(r));
537
- }
538
- }
539
- yield ']';
540
-
541
- yield ',"history":{';
542
- const historyEntries = Object.entries(data.history || {});
543
- for (let i = 0; i < historyEntries.length; i++) {
544
- if (isCanceled()) {
545
- ac.abort();
546
- return;
547
- }
548
- if (i > 0) yield ',';
549
- const [taskId, runs] = historyEntries[i];
550
- yield JSON.stringify(taskId) + ':[';
551
- if (Array.isArray(runs)) {
552
- for (let j = 0; j < runs.length; j++) {
553
- if (isCanceled()) {
554
- ac.abort();
555
- return;
556
- }
557
- if (j > 0) yield ',';
558
- yield JSON.stringify(runs[j]);
559
- if ((j + 1) % 15 === 0) {
560
- await new Promise((r) => setImmediate(r));
561
- }
562
- }
563
- } else {
564
- yield JSON.stringify(runs);
565
- }
566
- yield ']';
567
- await new Promise((r) => setImmediate(r));
568
- }
569
- yield '}';
570
- yield ',"chainCheckpoints":' + JSON.stringify(data.chainCheckpoints || {});
571
- yield ',"artifacts":' + JSON.stringify(data.artifacts || {});
572
- yield '}';
573
- }
574
-
575
- try {
576
- await pipeline(generateChunks(), ws, { signal: ac.signal });
577
- } catch (err) {
578
- if (ac.signal.aborted || isCanceled()) {
579
- return;
580
- }
581
- throw err;
582
- }
156
+ return writeStoreStream(this, filePath, data, version);
583
157
  }
584
158
 
585
159
  save() {
586
- if (this._readOnly || this._loadFailed) {
587
- const reason = this._accessErrorCode
588
- ? `access error (${this._accessErrorCode})`
589
- : (this._loadError ? this._loadError.message : 'unrecovered read failure');
590
- logger.error(`[dsh-cron] save blocked: store is in read-only recovery mode due to ${reason} on "${this.filePath}". File on disk was preserved.`);
591
- throw new Error(`Store write blocked: read-only recovery mode (${this.filePath})`);
592
- }
593
- if (this._saveTimer) {
594
- clearTimeout(this._saveTimer);
595
- this._saveTimer = null;
596
- }
597
- const version = ++this._saveVersion;
598
- this._lastSyncVersion = version;
599
-
600
- // Immediately cancel and unlink any in-flight async tmp file so async rename cannot touch disk (#244)
601
- if (this._currentAsyncTmp) {
602
- const inFlightTmp = this._currentAsyncTmp;
603
- this._currentAsyncTmp = null;
604
- bestEffort('unlink-async-tmp', () => fs.unlinkSync(inFlightTmp));
605
- }
606
- try {
607
- const dir = path.dirname(this.filePath);
608
- if (!fs.existsSync(dir)) {
609
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
610
- }
611
- bestEffort('chmod-dir', () => fs.chmodSync(dir, 0o700));
612
- const data = this._createSnapshot();
613
- // Unique tmp file per save call with process PID and random token to eliminate file collision
614
- const rand = Math.random().toString(36).slice(2, 8);
615
- const tmp = `${this.filePath}.tmp.${process.pid}_${Date.now()}_${rand}`;
616
- fs.writeFileSync(tmp, JSON.stringify(data, null, 2), { encoding: 'utf-8', mode: 0o600 });
617
- bestEffort('chmod-tmp', () => fs.chmodSync(tmp, 0o600));
618
- fs.renameSync(tmp, this.filePath);
619
- bestEffort('chmod-store', () => fs.chmodSync(this.filePath, 0o600));
620
- this._diskVersion = Math.max(this._diskVersion || 0, version);
621
- this._lastWrittenVersion = this._diskVersion;
622
- this._notifyDiskVersion(this._diskVersion);
623
-
624
- // Throttled backup (.bak): avoid expensive copyFileSync on every micro-save
625
- const now = Date.now();
626
- if (now - this._lastBackupTime > 60000) {
627
- this._lastBackupTime = now;
628
- bestEffort('backup-on-save', () => {
629
- const bakPath = `${this.filePath}.bak`;
630
- fs.copyFileSync(this.filePath, bakPath);
631
- fs.chmodSync(bakPath, 0o600);
632
- });
633
- }
634
- } catch (err) {
635
- logger.error('[dsh-cron] store save error:', err.message);
636
- throw err;
637
- }
160
+ return save(this);
638
161
  }
639
162
 
640
163
  getRun(runId) {
@@ -664,123 +187,23 @@ export class TaskStore {
664
187
  }
665
188
 
666
189
  getSettings() {
667
- const defaults = getDshDefaultTelegramCredentials();
668
- const base = { ...this.settings };
669
- base.botToken = base.botToken !== undefined ? base.botToken : (defaults.botToken || '');
670
- base.botTokenRef = base.botTokenRef || '';
671
- base.chatId = base.chatId !== undefined ? base.chatId : (defaults.chatId || '');
672
- base.notifyTelegram = Boolean(base.notifyTelegram);
673
- base.onlyOnFailure = Boolean(base.onlyOnFailure);
674
- base.kanbanBaseUrl = base.kanbanBaseUrl || 'http://127.0.0.1:3000';
675
- base.hasDefaultCredentials = Boolean(defaults.botToken && defaults.chatId);
676
- base.llmActionsEnabled = Boolean(base.llmActionsEnabled);
677
- base.showChatHeaderButton = base.showChatHeaderButton !== undefined ? Boolean(base.showChatHeaderButton) : true;
678
- base.showChatHeaderActions = base.showChatHeaderActions !== undefined ? Boolean(base.showChatHeaderActions) : true;
679
- return base;
190
+ return getSettings(this);
680
191
  }
681
192
 
682
193
  getClientSettings() {
683
- const raw = this.getSettings();
684
- const isCustom = Boolean(this.settings.botToken);
685
- const hasToken = Boolean(raw.botToken);
686
- const masked = hasToken ? (raw.botToken.length > 8 ? raw.botToken.slice(0, 4) + '••••••••' + raw.botToken.slice(-3) : '••••••••') : '';
687
- const { botToken, ...rest } = raw;
688
- const out = {
689
- ...rest,
690
- botToken: masked,
691
- botTokenMasked: masked,
692
- hasBotToken: hasToken,
693
- hasCustomBotToken: isCustom,
694
- };
695
- // Webhook URLs and the Bark device key carry an embedded secret, so they
696
- // are never sent to the browser in clear text either.
697
- for (const key of TaskStore.MASKED_SETTING_KEYS) {
698
- if (key === 'botToken') continue;
699
- out[key] = maskSecretValue(raw[key]);
700
- }
701
- return out;
194
+ return getClientSettings(this);
702
195
  }
703
196
 
704
- /**
705
- * Raw secret values that must not be stored in plugin settings; the
706
- * corresponding *Ref credential names are the supported way to configure
707
- * these channels.
708
- */
709
197
  static get FORBIDDEN_SETTING_KEYS() {
710
- return ['giteaToken', 'ntfyToken', 'pushplusToken', 'discordToken', 'slackToken'];
198
+ return FORBIDDEN_SETTING_KEYS;
711
199
  }
712
200
 
713
- /**
714
- * Settings that hold a secret and are therefore masked on read: tokens and
715
- * webhook URLs (the URL embeds the auth token), plus the Bark device key.
716
- * These are stored in the plugin settings file; the credential-reference
717
- * fields (botTokenRef, ntfyTokenRef, …) take precedence over them.
718
- */
719
201
  static get MASKED_SETTING_KEYS() {
720
- return ['botToken', 'discordWebhookUrl', 'slackWebhookUrl', 'barkKey', 'apiToken', 'telegramWebhookSecret'];
202
+ return MASKED_SETTING_KEYS;
721
203
  }
722
204
 
723
205
  saveSettings(newSettings = {}) {
724
- const patch = { ...newSettings };
725
-
726
- for (const key of TaskStore.FORBIDDEN_SETTING_KEYS) {
727
- if (key in patch) {
728
- logger.warn(`[dsh-cron] refusing to store raw secret "${key}" in settings — use a credential reference instead`);
729
- delete patch[key];
730
- }
731
- }
732
-
733
- let botTokenToSave = this.settings.botToken || '';
734
- if (patch.botToken !== undefined) {
735
- const val = String(patch.botToken).trim();
736
- // If client sends masked token or empty string while custom token existed, don't overwrite with dots
737
- if (val && !val.includes('••') && !val.includes('****')) {
738
- botTokenToSave = val;
739
- } else if (val === '') {
740
- botTokenToSave = '';
741
- }
742
- delete patch.botToken;
743
- }
744
-
745
- // A masked value echoed back by the UI must never overwrite the real one.
746
- for (const key of TaskStore.MASKED_SETTING_KEYS) {
747
- if (key === 'botToken') continue;
748
- const val = patch[key];
749
- if (typeof val === 'string' && (val.includes('••') || val.includes('****'))) {
750
- delete patch[key];
751
- }
752
- }
753
-
754
- for (const [key, value] of Object.entries(patch)) {
755
- if (value === undefined) delete patch[key];
756
- else if (typeof value === 'string') patch[key] = value.trim();
757
- }
758
-
759
- const prevSettings = this.settings;
760
- this.settings = {
761
- ...this.settings,
762
- ...patch,
763
- botToken: botTokenToSave,
764
- kanbanBaseUrl: patch.kanbanBaseUrl !== undefined
765
- ? (patch.kanbanBaseUrl || 'http://127.0.0.1:3000')
766
- : (this.settings.kanbanBaseUrl || 'http://127.0.0.1:3000'),
767
- notifyTelegram: patch.notifyTelegram !== undefined ? Boolean(patch.notifyTelegram) : Boolean(this.settings.notifyTelegram),
768
- onlyOnFailure: patch.onlyOnFailure !== undefined ? Boolean(patch.onlyOnFailure) : Boolean(this.settings.onlyOnFailure),
769
- llmActionsEnabled: patch.llmActionsEnabled !== undefined ? Boolean(patch.llmActionsEnabled) : Boolean(this.settings.llmActionsEnabled),
770
- showChatHeaderButton: patch.showChatHeaderButton !== undefined ? Boolean(patch.showChatHeaderButton) : (this.settings.showChatHeaderButton !== undefined ? Boolean(this.settings.showChatHeaderButton) : true),
771
- showChatHeaderActions: patch.showChatHeaderActions !== undefined ? Boolean(patch.showChatHeaderActions) : (this.settings.showChatHeaderActions !== undefined ? Boolean(this.settings.showChatHeaderActions) : true),
772
- };
773
- if (this._readOnly || this._loadFailed) {
774
- logger.warn(`[dsh-cron] store is in read-only recovery mode; updated in-memory settings but skipped writing to "${this.filePath}".`);
775
- return this.getSettings();
776
- }
777
- try {
778
- this.save();
779
- } catch (err) {
780
- this.settings = prevSettings;
781
- throw err;
782
- }
783
- return this.getSettings();
206
+ return saveSettings(this, newSettings);
784
207
  }
785
208
 
786
209
  list(filter = {}) {
@@ -1039,196 +462,27 @@ export class TaskStore {
1039
462
  * Remove orphaned temporary write files older than 10 minutes (#379, GH #17).
1040
463
  */
1041
464
  _cleanOrphanedTmpFiles(dir) {
1042
- try {
1043
- if (!fs.existsSync(dir)) return;
1044
- const entries = fs.readdirSync(dir);
1045
- const now = Date.now();
1046
- const tenMinutesMs = 10 * 60 * 1000;
1047
- for (const entry of entries) {
1048
- if (entry.includes('.tmp.')) {
1049
- const fullPath = path.join(dir, entry);
1050
- bestEffort('clean-tmp-file', () => {
1051
- const stat = fs.statSync(fullPath);
1052
- if (stat.isFile() && (now - stat.mtimeMs > tenMinutesMs)) {
1053
- fs.unlinkSync(fullPath);
1054
- }
1055
- });
1056
- }
1057
- }
1058
- } catch (dirErr) {
1059
- bestEffort('log-clean-tmp-dir-error', () => logger.debug?.(`[dsh-cron] clean orphaned tmp dir error: ${dirErr?.message}`));
1060
- }
465
+ return cleanOrphanedTmpFiles(dir);
1061
466
  }
1062
467
 
1063
- /**
1064
- * Append rotated overflow history entries into tasks-history-archive.json (#134, #379, GH #17).
1065
- */
1066
468
  _archiveHistoryRuns(id, overflowRuns) {
1067
- if (!Array.isArray(overflowRuns) || overflowRuns.length === 0) return;
1068
- try {
1069
- const dir = path.dirname(this.filePath);
1070
- const archivePath = path.join(dir, 'tasks-history-archive.json');
1071
- let archive = {};
1072
- if (fs.existsSync(archivePath)) {
1073
- archive = bestEffort('parse-history-archive', () => JSON.parse(fs.readFileSync(archivePath, 'utf-8'))) || {};
1074
- }
1075
- if (!Array.isArray(archive[id])) archive[id] = [];
1076
-
1077
- // Strip full raw diff payload from archived overflow runs to prevent runaway JSON growth (#379, GH #17)
1078
- const sanitizedOverflow = overflowRuns.map((r) => {
1079
- if (!r || !r.gitDiff) return r;
1080
- const { diff, ...gitDiffMeta } = r.gitDiff;
1081
- return {
1082
- ...r,
1083
- gitDiff: {
1084
- ...gitDiffMeta,
1085
- diffExcerpt: diff ? diff.slice(0, 500) : '',
1086
- hasChanges: Boolean(gitDiffMeta.hasChanges),
1087
- archived: true,
1088
- },
1089
- };
1090
- });
1091
-
1092
- archive[id].push(...sanitizedOverflow);
1093
- if (archive[id].length > 1000) {
1094
- archive[id] = archive[id].slice(-1000);
1095
- }
1096
-
1097
- // Enforce total archive size budget (max 15MB) across tasks (#379, GH #17)
1098
- const MAX_ARCHIVE_BYTES = 15 * 1024 * 1024;
1099
- let serialized = JSON.stringify(archive);
1100
- if (serialized.length > MAX_ARCHIVE_BYTES) {
1101
- for (const taskId of Object.keys(archive)) {
1102
- if (Array.isArray(archive[taskId]) && archive[taskId].length > 100) {
1103
- archive[taskId] = archive[taskId].slice(-100);
1104
- }
1105
- }
1106
- serialized = JSON.stringify(archive);
1107
- }
1108
-
1109
- // Write atomically with tmp file using compact JSON (avoiding mega-lines and null, 2 serialization bloat)
1110
- const rand = Math.random().toString(36).slice(2, 8);
1111
- const tmp = `${archivePath}.tmp.${process.pid}_${Date.now()}_${rand}`;
1112
- fs.writeFileSync(tmp, serialized, { encoding: 'utf-8', mode: 0o600 });
1113
- bestEffort('chmod-tmp', () => fs.chmodSync(tmp, 0o600));
1114
- fs.renameSync(tmp, archivePath);
1115
- bestEffort('chmod-archive', () => fs.chmodSync(archivePath, 0o600));
1116
-
1117
- // Partition runs into monthly buckets for compressed archives (#391)
1118
- const monthlyBuckets = new Map();
1119
- for (const run of sanitizedOverflow) {
1120
- const at = run.at || run.timestamp || run.startedAt || Date.now();
1121
- const date = new Date(at);
1122
- const monthKey = !isNaN(date.getTime())
1123
- ? `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}`
1124
- : new Date().toISOString().slice(0, 7);
1125
- if (!monthlyBuckets.has(monthKey)) {
1126
- monthlyBuckets.set(monthKey, []);
1127
- }
1128
- monthlyBuckets.get(monthKey).push(run);
1129
- }
1130
-
1131
- for (const [monthKey, runsForMonth] of monthlyBuckets.entries()) {
1132
- const gzPath = path.join(dir, `tasks-history-${monthKey}.json.gz`);
1133
- let monthArchive = {};
1134
- if (fs.existsSync(gzPath)) {
1135
- try {
1136
- const rawGz = fs.readFileSync(gzPath);
1137
- const decompressed = gunzipSync(rawGz).toString('utf-8');
1138
- monthArchive = JSON.parse(decompressed) || {};
1139
- } catch (gzReadErr) {
1140
- logger.warn(`[dsh-cron] failed to read existing gzip archive for ${monthKey}:`, gzReadErr.message);
1141
- monthArchive = {};
1142
- }
1143
- }
1144
- if (!Array.isArray(monthArchive[id])) {
1145
- monthArchive[id] = [];
1146
- }
1147
- monthArchive[id].push(...runsForMonth);
1148
- const compressed = gzipSync(Buffer.from(JSON.stringify(monthArchive), 'utf-8'), { level: 9 });
1149
- const randGz = Math.random().toString(36).slice(2, 8);
1150
- const tmpGz = `${gzPath}.tmp.${process.pid}_${Date.now()}_${randGz}`;
1151
- fs.writeFileSync(tmpGz, compressed, { mode: 0o600 });
1152
- bestEffort('chmod-tmp-gz', () => fs.chmodSync(tmpGz, 0o600));
1153
- fs.renameSync(tmpGz, gzPath);
1154
- bestEffort('chmod-archive-gz', () => fs.chmodSync(gzPath, 0o600));
1155
- }
1156
-
1157
- this._pruneOldMonthlyArchives(dir, 6);
1158
- } catch (archiveErr) {
1159
- logger.error('[dsh-cron] history archive error:', archiveErr.message);
1160
- }
469
+ return archiveHistoryRuns(this, id, overflowRuns);
1161
470
  }
1162
471
 
1163
472
  listMonthlyArchives() {
1164
- try {
1165
- const dir = path.dirname(this.filePath);
1166
- if (!fs.existsSync(dir)) return [];
1167
- const files = fs.readdirSync(dir);
1168
- const archives = [];
1169
- for (const file of files) {
1170
- const match = file.match(/^tasks-history-(\d{4}-\d{2})\.json\.gz$/);
1171
- if (match) {
1172
- const month = match[1];
1173
- const fullPath = path.join(dir, file);
1174
- try {
1175
- const stat = fs.statSync(fullPath);
1176
- archives.push({
1177
- month,
1178
- filename: file,
1179
- sizeBytes: stat.size,
1180
- mtime: stat.mtime.toISOString(),
1181
- path: fullPath,
1182
- });
1183
- } catch (_err) {
1184
- // ignore unreadable stat
1185
- }
1186
- }
1187
- }
1188
- return archives.sort((a, b) => b.month.localeCompare(a.month));
1189
- } catch (err) {
1190
- logger.error('[dsh-cron] listMonthlyArchives error:', err.message);
1191
- return [];
1192
- }
473
+ return listMonthlyArchives(this);
1193
474
  }
1194
475
 
1195
476
  getMonthlyArchive(month) {
1196
- if (!month || !/^\d{4}-\d{2}$/.test(month)) return null;
1197
- try {
1198
- const dir = path.dirname(this.filePath);
1199
- const gzPath = path.join(dir, `tasks-history-${month}.json.gz`);
1200
- if (!fs.existsSync(gzPath)) return null;
1201
- const rawGz = fs.readFileSync(gzPath);
1202
- const decompressed = gunzipSync(rawGz).toString('utf-8');
1203
- return JSON.parse(decompressed);
1204
- } catch (err) {
1205
- logger.error(`[dsh-cron] getMonthlyArchive error for ${month}:`, err.message);
1206
- return null;
1207
- }
477
+ return getMonthlyArchive(this, month);
1208
478
  }
1209
479
 
1210
480
  _pruneOldMonthlyArchives(dir, maxMonths = 6) {
1211
- try {
1212
- if (!fs.existsSync(dir) || maxMonths < 0) return;
1213
- const files = fs.readdirSync(dir);
1214
- const monthlyFiles = [];
1215
- for (const file of files) {
1216
- const match = file.match(/^tasks-history-(\d{4}-\d{2})\.json\.gz$/);
1217
- if (match) {
1218
- monthlyFiles.push({ month: match[1], file, fullPath: path.join(dir, file) });
1219
- }
1220
- }
1221
- monthlyFiles.sort((a, b) => b.month.localeCompare(a.month));
1222
- if (monthlyFiles.length > maxMonths) {
1223
- const toDelete = monthlyFiles.slice(maxMonths);
1224
- for (const item of toDelete) {
1225
- bestEffort('delete-old-archive', () => fs.unlinkSync(item.fullPath));
1226
- logger.info(`[dsh-cron] pruned old monthly history archive: ${item.file}`);
1227
- }
1228
- }
1229
- } catch (err) {
1230
- bestEffort('log-prune-err', () => logger.debug?.(`[dsh-cron] prune old monthly archives error: ${err.message}`));
1231
- }
481
+ return pruneOldMonthlyArchives(dir, maxMonths);
482
+ }
483
+
484
+ getArchivedRuns(id, options = {}) {
485
+ return getArchivedRuns(this, id, options);
1232
486
  }
1233
487
 
1234
488
  getHistory(id, limit = 20) {
@@ -1236,78 +490,11 @@ export class TaskStore {
1236
490
  return runs.slice(0, limit);
1237
491
  }
1238
492
 
1239
- getArchivedRuns(id, { limit = 50, offset = 0, search = '' } = {}) {
1240
- try {
1241
- const dir = path.dirname(this.filePath);
1242
- const archivePath = path.join(dir, 'tasks-history-archive.json');
1243
- if (!fs.existsSync(archivePath)) return { runs: [], total: 0 };
1244
- const archive = JSON.parse(fs.readFileSync(archivePath, 'utf-8')) || {};
1245
- let runs = Array.isArray(archive[id]) ? [...archive[id]].sort((a, b) => ((b.at || b.timestamp || b.startedAt || 0) - (a.at || a.timestamp || a.startedAt || 0))) : [];
1246
- if (search && search.trim()) {
1247
- const q = search.toLowerCase();
1248
- runs = runs.filter(r => (r.output && r.output.toLowerCase().includes(q)) || (r.error && r.error.toLowerCase().includes(q)));
1249
- }
1250
- const total = runs.length;
1251
- const paged = runs.slice(offset, offset + limit);
1252
- return { runs: paged, total };
1253
- } catch (err) {
1254
- return { runs: [], total: 0, error: err.message };
1255
- }
1256
- }
1257
-
1258
493
  getTaskStats(id) {
1259
- const runs = this.history.get(id) || [];
1260
- const total = runs.length;
1261
- let success = 0;
1262
- let error = 0;
1263
- let timeout = 0;
1264
- const recentDurations = [];
1265
-
1266
- for (let i = 0; i < runs.length; i++) {
1267
- const r = runs[i];
1268
- if (r.status === 'success') success++;
1269
- else if (r.status === 'error') error++;
1270
- else if (r.status === 'timeout') timeout++;
1271
-
1272
- if (recentDurations.length < 10 && r.durationMs !== undefined) {
1273
- recentDurations.push({
1274
- at: r.at,
1275
- durationMs: r.durationMs,
1276
- status: r.status,
1277
- });
1278
- }
1279
- }
1280
-
1281
- const successRate = total > 0 ? Number((success / total).toFixed(2)) : 1.0;
1282
- return {
1283
- totalRuns: total,
1284
- successRuns: success,
1285
- errorRuns: error,
1286
- timeoutRuns: timeout,
1287
- successRate,
1288
- recentDurations,
1289
- };
494
+ return getTaskStats(this, id);
1290
495
  }
1291
496
 
1292
497
  getAggregatedStats() {
1293
- let totalRuns = 0;
1294
- let totalTokens = 0;
1295
- let totalCostUsd = 0;
1296
- let activeTasks = 0;
1297
-
1298
- for (const t of this.tasks.values()) {
1299
- if (t.status === 'active') activeTasks++;
1300
- totalTokens += (t.totalTokens || 0);
1301
- totalCostUsd += (t.totalCostUsd || 0);
1302
- const h = this.history.get(t.id) || [];
1303
- totalRuns += h.length;
1304
- }
1305
-
1306
- return {
1307
- activeTasks,
1308
- totalRuns,
1309
- totalTokens,
1310
- totalCostUsd: Number(totalCostUsd.toFixed(4)),
1311
- };
498
+ return getAggregatedStats(this);
1312
499
  }
1313
500
  }