@goodandready/dsh-cron 0.2.41 → 0.2.42

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/README.md CHANGED
@@ -550,7 +550,7 @@ dsh-cron:
550
550
  Notes:
551
551
 
552
552
  * Run history is capped at **50 entries per task** (fixed); each entry keeps up to 4000 characters of output.
553
- * Tasks run in the **server's local timezone**; cron expressions are evaluated by `croner` on the host clock.
553
+ * Tasks run in their configured **timezone** (`task.timezone`, falling back to `settings.defaultTimezone` or server local timezone); cron expressions are evaluated by `croner` against the resolved timezone.
554
554
  * Tasks persist in the DSH data directory (`cron/tasks.json`) and survive restarts; missed one-shots are detected on startup.
555
555
 
556
556
  ---
@@ -21,22 +21,26 @@ export async function handleTelegramWebhook({ store, scheduler, req, res }) {
21
21
  const botToken = settings.botToken || defaults.botToken;
22
22
  const allowedChatId = String(settings.chatId || defaults.chatId || '').trim();
23
23
 
24
- // Secret token verification (Issue #208)
24
+ // Secret token verification (Issue #208) - fail-closed: secret MUST be configured
25
25
  const webhookSecret = settings.telegramWebhookSecret || settings.webhookSecret || settings.secretToken || process.env.TELEGRAM_WEBHOOK_SECRET;
26
- if (webhookSecret) {
27
- const receivedSecret = req.headers['x-telegram-bot-api-secret-token'];
28
- if (!receivedSecret || typeof receivedSecret !== 'string') {
29
- logger.warn('[dsh-cron] unauthorized telegram webhook: missing secret token header');
30
- sendJson(res, 401, { ok: false, error: 'Unauthorized: missing secret token' });
31
- return;
32
- }
33
- const secretBuf = Buffer.from(String(webhookSecret));
34
- const receivedBuf = Buffer.from(String(receivedSecret));
35
- if (secretBuf.length !== receivedBuf.length || !crypto.timingSafeEqual(secretBuf, receivedBuf)) {
36
- logger.warn('[dsh-cron] unauthorized telegram webhook: invalid secret token');
37
- sendJson(res, 401, { ok: false, error: 'Unauthorized: invalid secret token' });
38
- return;
39
- }
26
+ if (!webhookSecret) {
27
+ logger.warn('[dsh-cron] unauthorized telegram webhook: webhook secret is not configured (fail-closed)');
28
+ sendJson(res, 401, { ok: false, error: 'Unauthorized: webhook secret is not configured' });
29
+ return;
30
+ }
31
+ const headers = req.headers || {};
32
+ const receivedSecret = headers['x-telegram-bot-api-secret-token'] || headers['X-Telegram-Bot-Api-Secret-Token'];
33
+ if (!receivedSecret || typeof receivedSecret !== 'string') {
34
+ logger.warn('[dsh-cron] unauthorized telegram webhook: missing secret token header');
35
+ sendJson(res, 401, { ok: false, error: 'Unauthorized: missing secret token' });
36
+ return;
37
+ }
38
+ const secretBuf = Buffer.from(String(webhookSecret));
39
+ const receivedBuf = Buffer.from(String(receivedSecret));
40
+ if (secretBuf.length !== receivedBuf.length || !crypto.timingSafeEqual(secretBuf, receivedBuf)) {
41
+ logger.warn('[dsh-cron] unauthorized telegram webhook: invalid secret token');
42
+ sendJson(res, 401, { ok: false, error: 'Unauthorized: invalid secret token' });
43
+ return;
40
44
  }
41
45
 
42
46
  // Deduplicate updates by update_id (Issue #208)
package/lib/client.js CHANGED
@@ -1499,11 +1499,32 @@ window.__ModuleLoader__.load({
1499
1499
 
1500
1500
  const actionInProgressRef = React.useRef(new Set());
1501
1501
 
1502
+ const fetchWithTimeout = async (url, options = {}, timeoutMs = 15000) => {
1503
+ const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
1504
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
1505
+ try {
1506
+ const res = await fetch(url, {
1507
+ ...options,
1508
+ signal: controller ? controller.signal : options.signal,
1509
+ });
1510
+ return res;
1511
+ } catch (err) {
1512
+ if (err && err.name === 'AbortError') {
1513
+ const timeoutErr = new Error(`Request timed out after ${Math.round(timeoutMs / 1000)}s`);
1514
+ timeoutErr.isTimeout = true;
1515
+ throw timeoutErr;
1516
+ }
1517
+ throw err;
1518
+ } finally {
1519
+ if (timer) clearTimeout(timer);
1520
+ }
1521
+ };
1522
+
1502
1523
  const handleToggleTask = async (id) => {
1503
1524
  if (actionInProgressRef.current.has(id)) return;
1504
1525
  actionInProgressRef.current.add(id);
1505
1526
  try {
1506
- const res = await fetch('/dsh-cron/tasks/' + encodeURIComponent(id) + '/toggle', { method: 'POST' });
1527
+ const res = await fetchWithTimeout('/dsh-cron/tasks/' + encodeURIComponent(id) + '/toggle', { method: 'POST' }, 15000);
1507
1528
  const data = await res.json().catch(() => ({}));
1508
1529
  if (!res.ok || (data && data.ok === false)) {
1509
1530
  const msg = (data && data.error) || `Toggle failed (HTTP ${res.status})`;
@@ -1526,7 +1547,7 @@ window.__ModuleLoader__.load({
1526
1547
  const prevStatus = prevTask ? prevTask.lastStatus : null;
1527
1548
  setTasks(prev => prev.map(t2 => t2.id === id ? { ...t2, lastStatus: 'running' } : t2));
1528
1549
  try {
1529
- const res = await fetch('/dsh-cron/tasks/' + encodeURIComponent(id) + '/run', { method: 'POST' });
1550
+ const res = await fetchWithTimeout('/dsh-cron/tasks/' + encodeURIComponent(id) + '/run', { method: 'POST' }, 15000);
1530
1551
  const data = await res.json().catch(() => ({}));
1531
1552
  if (!res.ok || (data && data.ok === false)) {
1532
1553
  setTasks(prev => prev.map(t2 => t2.id === id ? { ...t2, lastStatus: prevStatus } : t2));
package/lib/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import fs from 'node:fs';
2
+ import { bestEffort } from './best-effort.js';
2
3
  import { setLogger, logger } from './logger.js';
3
4
  import { registerPluginUpdater } from './updater.js';
4
5
  import { credentialRefStatus } from './secrets.js';
@@ -182,6 +183,8 @@ export function apply(ctx, rawConfig) {
182
183
 
183
184
  scheduler.start();
184
185
 
186
+ // Heartbeat / dead man's snitch (#16): an optional periodic GET ping so an
187
+ // external monitor can alert when this scheduler stops responding.
185
188
  // Heartbeat / dead man's snitch (#16): an optional periodic GET ping so an
186
189
  // external monitor can alert when this scheduler stops responding.
187
190
  let heartbeatTimer = null;
@@ -203,6 +206,46 @@ export function apply(ctx, rawConfig) {
203
206
  }
204
207
  updateHeartbeat(config && config.heartbeatUrl, config && config.heartbeatIntervalSec);
205
208
 
209
+ // Synchronize volatile Config settings to runtime scheduler and store (#235)
210
+ let activeVolatileConfig = {};
211
+ function syncVolatileConfig(updatedConfig) {
212
+ try {
213
+ const cfg = updatedConfig || ctx.config || config || {};
214
+ const unwrapped = unwrapConfig(cfg);
215
+ activeVolatileConfig = { ...activeVolatileConfig, ...unwrapped };
216
+ if (typeof unwrapped.maxConcurrent === 'number') {
217
+ scheduler.maxConcurrent = unwrapped.maxConcurrent;
218
+ }
219
+ if (typeof unwrapped.defaultTimezone === 'string') {
220
+ scheduler.defaultTimezone = unwrapped.defaultTimezone;
221
+ }
222
+ if (typeof unwrapped.llmActionsEnabled === 'boolean') {
223
+ scheduler.llmActionsEnabled = unwrapped.llmActionsEnabled;
224
+ }
225
+ if (unwrapped.heartbeatUrl !== undefined || unwrapped.heartbeatIntervalSec !== undefined) {
226
+ updateHeartbeat(unwrapped.heartbeatUrl, unwrapped.heartbeatIntervalSec);
227
+ }
228
+ const current = store.getSettings();
229
+ const patch = {};
230
+ for (const k of ['maxConcurrent', 'defaultTimezone', 'heartbeatUrl', 'heartbeatIntervalSec', 'llmActionsEnabled']) {
231
+ if (unwrapped[k] !== undefined && unwrapped[k] !== current[k]) {
232
+ patch[k] = unwrapped[k];
233
+ }
234
+ }
235
+ if (Object.keys(patch).length > 0) {
236
+ store.saveSettings(patch);
237
+ }
238
+ } catch (err) {
239
+ logger.warn('[dsh-cron] error syncing volatile config:', err.message);
240
+ }
241
+ }
242
+
243
+ if (typeof ctx.on === 'function') {
244
+ ctx.on('loader/volatile-update', (updatedConfig) => {
245
+ syncVolatileConfig(updatedConfig);
246
+ });
247
+ }
248
+
206
249
  ctx.effect(() => {
207
250
  return () => {
208
251
  if (heartbeatTimer) clearInterval(heartbeatTimer);
@@ -237,7 +280,17 @@ export function apply(ctx, rawConfig) {
237
280
  handler: async (req, res) => {
238
281
  try {
239
282
  if (req.method === 'GET') {
240
- sendJson(res, 200, { ok: true, settings: { ...store.getClientSettings(), version: pkgVersion } });
283
+ const unwrapped = {
284
+ ...unwrapConfig(ctx.config || config || {}),
285
+ ...activeVolatileConfig,
286
+ };
287
+ const clientSettings = store.getClientSettings();
288
+ for (const k of ['maxConcurrent', 'defaultTimezone', 'heartbeatUrl', 'heartbeatIntervalSec', 'llmActionsEnabled']) {
289
+ if (unwrapped[k] !== undefined) {
290
+ clientSettings[k] = unwrapped[k];
291
+ }
292
+ }
293
+ sendJson(res, 200, { ok: true, settings: { ...clientSettings, version: pkgVersion } });
241
294
  return;
242
295
  }
243
296
  if (req.method === 'POST') {
@@ -112,11 +112,29 @@ export async function runViaRemoteWorkspace(task, signal, ctx) {
112
112
 
113
113
  let profile = null;
114
114
  profile = bestEffort('get-remoteSsh-profile', () => {
115
+ const remoteProfilesSvc = ctx.get('remoteProfiles');
116
+ if (remoteProfilesSvc && typeof remoteProfilesSvc.list === 'function') {
117
+ const list = remoteProfilesSvc.list();
118
+ if (Array.isArray(list)) {
119
+ const found = list.find((p) => p && p.id === task.sshProfileId);
120
+ if (found) return found;
121
+ }
122
+ }
115
123
  const settings = ctx.get('settings');
116
- if (settings && typeof settings.get === 'function') {
117
- const snap = settings.get('dsh-remote-workspace');
118
- const profiles = snap && Array.isArray(snap.profiles) ? snap.profiles : [];
119
- return profiles.find((p) => p && p.id === task.sshProfileId) || null;
124
+ if (settings) {
125
+ if (typeof settings.describe === 'function') {
126
+ const desc = settings.describe();
127
+ const entry = Array.isArray(desc) ? desc.find((r) => r && r.ns === 'dsh-remote-workspace') : null;
128
+ const snap = entry ? entry.value : null;
129
+ const profiles = snap && Array.isArray(snap.profiles) ? snap.profiles : [];
130
+ const found = profiles.find((p) => p && p.id === task.sshProfileId);
131
+ if (found) return found;
132
+ }
133
+ if (typeof settings.get === 'function') {
134
+ const snap = settings.get('dsh-remote-workspace');
135
+ const profiles = snap && Array.isArray(snap.profiles) ? snap.profiles : [];
136
+ return profiles.find((p) => p && p.id === task.sshProfileId) || null;
137
+ }
120
138
  }
121
139
  return null;
122
140
  });
package/lib/runner.js CHANGED
@@ -423,22 +423,41 @@ export class SessionRunner {
423
423
  turnEvents = handle.agent.log.slice(startSeq);
424
424
  }
425
425
 
426
- // 3. Terminal turn failure check (#227)
426
+ // Extract usage FIRST so failed turns and budget checks have accurate token and cost accounting (#228)
427
+ const usage = this._extractUsage(handle, turnEvents);
428
+ const costUsd = estimateTokenCost(prep.model, usage);
429
+
430
+ // 3. Terminal turn failure and settlement check (#227)
431
+ let hasTerminalEvent = false;
427
432
  for (const ev of turnEvents) {
428
433
  if (!ev) continue;
429
434
  if (ev.type === 'turn/end' || ev.type === 'turn/error' || ev.type === 'turn/failure') {
435
+ hasTerminalEvent = true;
430
436
  const reason = ev.data?.reason || ev.reason;
431
437
  const reasonKind = (reason && typeof reason === 'object') ? reason.kind : reason;
432
- if (['error', 'interrupted', 'failed', 'aborted'].includes(reasonKind) || ev.data?.error || ev.error) {
433
- const errMsg = ev.data?.error?.message || ev.error?.message || reason?.message || (typeof reason === 'string' ? reason : 'Agent turn ended with error');
438
+ if (['error', 'interrupted', 'failed', 'aborted', 'blocked'].includes(reasonKind) || ev.data?.error || ev.error) {
439
+ const errMsg = ev.data?.error?.message || ev.error?.message || reason?.message || (typeof reason === 'string' ? reason : `Agent turn ended with status: ${reasonKind || 'error'}`);
434
440
  const err = new Error(errMsg);
435
441
  err.reason = reason;
442
+ err.reasonKind = reasonKind;
436
443
  err.turnFailed = true;
444
+ err.usage = usage;
445
+ err.costUsd = costUsd;
446
+ err.sessionId = handle.agent.session?.id || null;
437
447
  throw err;
438
448
  }
439
449
  }
440
450
  }
441
451
 
452
+ if (turnEvents.length > 0 && !hasTerminalEvent) {
453
+ const err = new Error('Agent turn ended without terminal completion event');
454
+ err.turnFailed = true;
455
+ err.usage = usage;
456
+ err.costUsd = costUsd;
457
+ err.sessionId = handle.agent.session?.id || null;
458
+ throw err;
459
+ }
460
+
442
461
  // 4. Extract assistant message text from turn events (#227)
443
462
  const messageTexts = [];
444
463
  const chunkTexts = [];
@@ -476,11 +495,10 @@ export class SessionRunner {
476
495
  outputText = `[dsh-cron] Agent finished turn for task "${task.title}" (${sessionNote})`;
477
496
  }
478
497
 
479
- const usage = this._extractUsage(handle, turnEvents);
480
498
  return {
481
499
  output: outputText,
482
500
  usage,
483
- costUsd: estimateTokenCost(prep.model, usage),
501
+ costUsd,
484
502
  sessionId: handle.agent.session?.id || null,
485
503
  };
486
504
  } finally {
@@ -541,27 +559,35 @@ export class SessionRunner {
541
559
  }
542
560
  }
543
561
 
544
- // assistant/attempt usage (e.g. paid failed attempts or retry attempts)
545
- if (ev.type === 'assistant/attempt' && ev.data?.usage) {
546
- const u = ev.data.usage;
547
- if (ev.data.failed || ev.data.error || ev.data.status === 'failed') {
548
- failedAttempts.push({
562
+ // assistant/attempt usage (e.g. paid failed attempts, retries, streaming attempts) (#228)
563
+ if (ev.type === 'assistant/attempt') {
564
+ let attemptUsage = null;
565
+ if (ev.data?.usage) {
566
+ const u = ev.data.usage;
567
+ attemptUsage = {
549
568
  inputTokens: Number(u.inputTokens || u.promptTokens || u.uncachedInputTokens) || 0,
550
569
  outputTokens: Number(u.outputTokens || u.completionTokens) || 0,
551
570
  cacheReadTokens: Number(u.cacheReadTokens || u.cachedTokens) || 0,
552
- });
553
- hasEventUsage = true;
554
- } else {
555
- const key = `${ev.data.turn || 0}:${ev.data.step || 0}`;
556
- if (!stepUsage.has(key)) {
557
- stepUsage.set(key, {
558
- inputTokens: Number(u.inputTokens || u.promptTokens || u.uncachedInputTokens) || 0,
559
- outputTokens: Number(u.outputTokens || u.completionTokens) || 0,
560
- cacheReadTokens: Number(u.cacheReadTokens || u.cachedTokens) || 0,
561
- });
562
- hasEventUsage = true;
571
+ };
572
+ }
573
+ // DSH 0.2.0-rc.2 AssistantStreamRecord: stream contains usage chunks
574
+ if (Array.isArray(ev.data?.stream)) {
575
+ for (const item of ev.data.stream) {
576
+ const u = item?.chunk?.usage || item?.usage;
577
+ if (u) {
578
+ if (!attemptUsage) {
579
+ attemptUsage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0 };
580
+ }
581
+ attemptUsage.inputTokens += Number(u.inputTokens || u.promptTokens || u.uncachedInputTokens) || 0;
582
+ attemptUsage.outputTokens += Number(u.outputTokens || u.completionTokens) || 0;
583
+ attemptUsage.cacheReadTokens += Number(u.cacheReadTokens || u.cachedTokens) || 0;
584
+ }
563
585
  }
564
586
  }
587
+ if (attemptUsage) {
588
+ failedAttempts.push(attemptUsage);
589
+ hasEventUsage = true;
590
+ }
565
591
  }
566
592
  }
567
593
 
@@ -146,6 +146,9 @@ export async function executeOnce(scheduler, task, signal, options = {}) {
146
146
  result.error = err.message || String(err);
147
147
  const timedOut = result.error.toLowerCase().includes('timed out') || result.error.toLowerCase().includes('timeout');
148
148
  result.status = timedOut ? 'timeout' : 'error';
149
+ if (err.usage) result.usage = err.usage;
150
+ if (typeof err.costUsd === 'number') result.costUsd = err.costUsd;
151
+ if (err.sessionId) result.sessionId = err.sessionId;
149
152
  }
150
153
  return result;
151
154
  }
package/lib/store.js CHANGED
@@ -39,6 +39,7 @@ export class TaskStore {
39
39
  this._saveTimer = null;
40
40
  this._savePromise = Promise.resolve();
41
41
  this._saveVersion = 0;
42
+ this._diskVersion = 0;
42
43
  this._lastWrittenVersion = 0;
43
44
  this.init();
44
45
  }
@@ -178,7 +179,7 @@ export class TaskStore {
178
179
  };
179
180
 
180
181
  const writeOp = async () => {
181
- if (this._lastWrittenVersion >= version) {
182
+ if ((this._diskVersion || 0) >= version) {
182
183
  return;
183
184
  }
184
185
  const dir = path.dirname(this.filePath);
@@ -191,13 +192,31 @@ export class TaskStore {
191
192
  await fs.promises.writeFile(tmp, payload, { encoding: 'utf-8', mode: 0o600 });
192
193
  bestEffort('chmod-tmp', () => fs.chmodSync(tmp, 0o600));
193
194
 
194
- if (this._lastWrittenVersion >= version) {
195
+ if ((this._diskVersion || 0) >= version || this._saveVersion > version) {
195
196
  await fs.promises.unlink(tmp).catch(() => {});
196
197
  return;
197
198
  }
198
199
 
199
200
  await fs.promises.rename(tmp, this.filePath);
200
201
  bestEffort('chmod-store', () => fs.chmodSync(this.filePath, 0o600));
202
+
203
+ // Monotonic versioning & sync save interleaving repair (#244)
204
+ if ((this._diskVersion || 0) > version) {
205
+ const syncData = {
206
+ version: 1,
207
+ updatedAt: new Date().toISOString(),
208
+ tasks: Array.from(this.tasks.values()),
209
+ history: Object.fromEntries(this.history.entries()),
210
+ settings: this.settings || {},
211
+ };
212
+ const randRep = Math.random().toString(36).slice(2, 8);
213
+ const tmpRep = `${this.filePath}.tmp.${process.pid}_${Date.now()}_${randRep}`;
214
+ fs.writeFileSync(tmpRep, JSON.stringify(syncData, null, 2), { encoding: 'utf-8', mode: 0o600 });
215
+ fs.renameSync(tmpRep, this.filePath);
216
+ return;
217
+ }
218
+
219
+ this._diskVersion = version;
201
220
  this._lastWrittenVersion = version;
202
221
 
203
222
  const now = Date.now();
@@ -243,7 +262,8 @@ export class TaskStore {
243
262
  bestEffort('chmod-tmp', () => fs.chmodSync(tmp, 0o600));
244
263
  fs.renameSync(tmp, this.filePath);
245
264
  bestEffort('chmod-store', () => fs.chmodSync(this.filePath, 0o600));
246
- this._lastWrittenVersion = version;
265
+ this._diskVersion = Math.max(this._diskVersion || 0, version);
266
+ this._lastWrittenVersion = this._diskVersion;
247
267
 
248
268
  // Throttled backup (.bak): avoid expensive copyFileSync on every micro-save
249
269
  const now = Date.now();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-cron",
3
- "version": "0.2.41",
3
+ "version": "0.2.42",
4
4
  "description": "Background automation runner for DSH: isolated agent runs, script/HTTP/SSH/Docker runtimes, cost guard, notifications, heartbeats.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",