@goodandready/dsh-cron 0.3.46 → 0.3.48

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
@@ -417,7 +417,7 @@ Developer-facing, no behaviour change. `parseScheduleExpression` was split into
417
417
  - **Self-Healing Runbooks & Auto-Diagnosis**: Failed tasks automatically execute an optional compensatory `selfHealingCommand` (e.g. system service restart or temp cleanup). Model failures can trigger `autoDiagnose: true` to append an instant root-cause diagnosis.
418
418
  - **Web UI Archive & Pipeline Visualization**: Interactive archive drawer with pagination and full log viewing; visual indicators for `➜ onSuccess` and `↳ onFailure` task connections.
419
419
  - **Shell & Disk Pre-flight Gate Hardening**: Supports both `command` and `shell` types with fail-closed semantics for invalid syntax, unknown types, or inspection failures. Disk space checks support exact path and threshold syntax (e.g. `/:10%`, `/data:500MB`).
420
- - **Complete Reliability Field Persistence**: HTTP POST task creation/editing and `cron_create_task` tool fully preserve and store all 13 reliability and session configuration fields (`agentPreset`, `targetSessionId`, `targetSessionReset`, `onSuccess`, `onFailure`, `heartbeatIntervalSeconds`, `gracePeriodSeconds`, `preflightType`, `preflightTarget`, `priority`, `concurrencyGroup`, `selfHealingCommand`, `autoDiagnose`, `fallbackProvider`, `fallbackModel`, `silentRule`, `inspectOnFailure`).
420
+ - **Complete Reliability Field Persistence**: HTTP POST task creation/editing and the `cron` tool (`action: 'create' | 'update'`) fully preserve and store all 13 reliability and session configuration fields (`agentPreset`, `targetSessionId`, `targetSessionReset`, `onSuccess`, `onFailure`, `heartbeatIntervalSeconds`, `gracePeriodSeconds`, `preflightType`, `preflightTarget`, `priority`, `concurrencyGroup`, `selfHealingCommand`, `autoDiagnose`, `fallbackProvider`, `fallbackModel`, `silentRule`, `inspectOnFailure`).
421
421
 
422
422
  ---
423
423
 
@@ -638,7 +638,7 @@ Save LLM tokens and API quotas on watcher tasks by dynamically slowing down exec
638
638
 
639
639
  ### 🔄 Session Resumption & GUI Session Naming (#346, GH #9, #354, GH #10, Added in v0.3.8, Patched in v0.3.9)
640
640
 
641
- - **HTTP API `sessionTitle` Persistence (v0.3.10, #354, GH #10, PR #11)**: Tasks created or updated via HTTP endpoints (`POST /dsh-cron/tasks` and `POST /dsh-cron/api/tasks`) now reliably forward and persist `sessionTitle` into the task store and runner, mirroring the agent-tool (`cron_create_task`) and PATCH pathways.
641
+ - **HTTP API `sessionTitle` Persistence (v0.3.10, #354, GH #10, PR #11)**: Tasks created or updated via HTTP endpoints (`POST /dsh-cron/tasks` and `POST /dsh-cron/api/tasks`) now reliably forward and persist `sessionTitle` into the task store and runner, mirroring the `cron` tool and PATCH pathways.
642
642
 
643
643
  - **Universal Host Resumption (`resumeSessionId`)**: DeepSeek Harness host `0.2.0-rc.2+` specifies `readonly resumeSessionId: SessionId` on `agents.resume()`. The runner now passes both `resumeSessionId` and `sessionId`, guaranteeing seamless session resumption across all DSH core versions without falling back to recreating sessions that already exist.
644
644
  - **Enhanced Diagnostics on Failure**: When an existing session cannot be resumed, `dsh-cron` logs an actionable warning and, if recreating the session fails, surfaces the underlying resume error in the task run output.
package/lib/client.css CHANGED
@@ -28,10 +28,116 @@
28
28
  display: none !important;
29
29
  }
30
30
 
31
- .dsh-cron-entry-clone { display: flex; align-items: center; gap: 8px; }
32
- .dsh-cron-entry-icon { display: flex; align-items: center; justify-content: center; flex: none; width: 16px; height: 16px; }
33
- .dsh-cron-entry-label { text-overflow: ellipsis; overflow: hidden; }
34
- [data-dsh-frame][data-sidebar-collapsed] .dsh-cron-entry-label { display: none; }
31
+ .dsh-cron-nav-icon { display: inline-flex; align-items: center; justify-content: center; color: currentColor; flex-shrink: 0; }
32
+ .dsh-cron-nav-icon svg { width: 100%; height: 100%; display: block; }
33
+
34
+ /* In-session quick action bar & button (Issue #448, DSH style) */
35
+ .dsh-cron-session-add-btn {
36
+ display: inline-flex;
37
+ align-items: center;
38
+ gap: 5px;
39
+ height: 28px;
40
+ min-height: 28px;
41
+ padding: 0 8px;
42
+ border: 0;
43
+ border-radius: var(--dsw-radius-sm, 6px);
44
+ background: transparent;
45
+ color: var(--dsw-alias-label-tertiary, #999);
46
+ font-family: inherit;
47
+ font-size: 12px;
48
+ font-weight: 500;
49
+ line-height: 18px;
50
+ cursor: pointer;
51
+ user-select: none;
52
+ box-sizing: border-box;
53
+ transition: background-color 0.15s ease, color 0.15s ease;
54
+ }
55
+ .dsh-cron-session-add-btn:hover {
56
+ background: var(--dsw-alias-fill-l2, color-mix(in srgb, var(--dsw-alias-label-primary, #fff) 10%, transparent));
57
+ color: var(--dsw-alias-label-primary, #fff);
58
+ }
59
+ .dsh-cron-session-add-btn:focus-visible {
60
+ background: var(--dsw-alias-fill-l2, color-mix(in srgb, var(--dsw-alias-label-primary, #fff) 10%, transparent));
61
+ color: var(--dsw-alias-label-primary, #fff);
62
+ outline: 2px solid var(--dsw-alias-focus-ring, #007acc);
63
+ outline-offset: 1px;
64
+ }
65
+ .dsh-cron-session-add-btn:active {
66
+ background: var(--dsw-alias-fill-l1, color-mix(in srgb, var(--dsw-alias-label-primary, #fff) 18%, transparent));
67
+ }
68
+ .dsh-cron-session-bar-icon {
69
+ display: inline-flex;
70
+ align-items: center;
71
+ justify-content: center;
72
+ width: 14px;
73
+ height: 14px;
74
+ flex-shrink: 0;
75
+ color: currentColor;
76
+ }
77
+ .dsh-cron-session-bar-icon svg {
78
+ width: 14px;
79
+ height: 14px;
80
+ display: block;
81
+ }
82
+ .dsh-cron-session-bar {
83
+ display: inline-flex;
84
+ align-items: center;
85
+ gap: 5px;
86
+ height: 28px;
87
+ min-height: 28px;
88
+ padding: 0 6px 0 8px;
89
+ border: 0;
90
+ border-radius: var(--dsw-radius-sm, 6px);
91
+ background: var(--dsw-alias-fill-l3, color-mix(in srgb, var(--dsw-alias-label-primary, #fff) 6%, transparent));
92
+ box-sizing: border-box;
93
+ font-size: 12px;
94
+ line-height: 18px;
95
+ }
96
+ .dsh-cron-session-badge {
97
+ display: inline-flex;
98
+ align-items: center;
99
+ max-width: 130px;
100
+ overflow: hidden;
101
+ text-overflow: ellipsis;
102
+ white-space: nowrap;
103
+ border: 0;
104
+ background: transparent;
105
+ color: var(--dsw-alias-label-secondary, #ccc);
106
+ font-family: inherit;
107
+ font-size: 12px;
108
+ line-height: 18px;
109
+ padding: 2px 4px;
110
+ border-radius: var(--dsw-radius-xs, 4px);
111
+ cursor: pointer;
112
+ transition: background-color 0.15s ease, color 0.15s ease;
113
+ }
114
+ .dsh-cron-session-badge:hover {
115
+ background: var(--dsw-alias-fill-l2, color-mix(in srgb, var(--dsw-alias-label-primary, #fff) 10%, transparent));
116
+ color: var(--dsw-alias-label-primary, #fff);
117
+ }
118
+ .dsh-cron-session-run-btn {
119
+ display: inline-flex;
120
+ align-items: center;
121
+ justify-content: center;
122
+ height: 20px;
123
+ padding: 0 6px;
124
+ border: 0;
125
+ border-radius: var(--dsw-radius-xs, 4px);
126
+ background: var(--dsw-alias-fill-l2, color-mix(in srgb, var(--dsw-alias-label-primary, #fff) 10%, transparent));
127
+ color: var(--dsw-alias-label-secondary, #ccc);
128
+ font-family: inherit;
129
+ font-size: 11px;
130
+ cursor: pointer;
131
+ transition: background-color 0.15s ease, color 0.15s ease;
132
+ }
133
+ .dsh-cron-session-run-btn:hover:not(:disabled) {
134
+ background: var(--dsw-alias-fill-l1, color-mix(in srgb, var(--dsw-alias-label-primary, #fff) 18%, transparent));
135
+ color: var(--dsw-alias-label-primary, #fff);
136
+ }
137
+ .dsh-cron-session-run-btn:disabled {
138
+ opacity: 0.5;
139
+ cursor: not-allowed;
140
+ }
35
141
 
36
142
  .dsh-cron-overlay { position: absolute; inset: 0; display: flex; flex-direction: column; background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); overflow-y: auto; padding: 24px 48px 32px; z-index: 100; box-sizing: border-box; }
37
143
  .dsh-cron-container { max-width: 960px; width: 100%; margin: 0 auto; display: flex; flex-direction: column; gap: 20px; padding: 8px 0 32px; box-sizing: border-box; }
package/lib/client.js CHANGED
@@ -2,7 +2,10 @@ window.__ModuleLoader__.load({id: '@goodandready/dsh-cron',factory: (require) =>
2
2
  var exports = module.exports
3
3
  const React = window.React || require('react');
4
4
  const _h = (...args) => (React && React.createElement ? React.createElement(...args) : null);
5
- const ReactDOM = window.ReactDOM || require('react-dom/client');
5
+ const ReactDOM = window.ReactDOM || (function() {try { return require('react-dom/client'); } catch (_e) { void _e; }
6
+ try { return require('react-dom'); } catch (_e) { void _e; }
7
+ return null;
8
+ })();
6
9
  const PLUGIN_ID = '@goodandready/dsh-cron';
7
10
  const NS = 'dsh-cron';
8
11
  const ROW_ID = 'dsh-cron';
@@ -278,9 +281,15 @@ function shouldDismissPanel(target) {if (target === null || target === undefined
278
281
  if (typeof target.closest !== 'function') return false;
279
282
  return target.closest(PANEL_OWNED_SELECTOR) === null;
280
283
  }
284
+ function resolveSidebarAnchor() {if (typeof document === 'undefined') return null;
285
+ const marker = document.querySelector('[' + ENTRY_ATTR + ']');
286
+ if (!marker) return null;
287
+ return marker.closest('div[class*="panelEntry"]') || marker.closest('button') || marker.parentElement || marker;
288
+ }
281
289
  function sidebarJobsSeatIsCurrent(state, entry) {
282
290
  const root = state && state.root;
283
- return root !== undefined && root.isConnected && entry !== null && root.previousElementSibling === entry;
291
+ const anchor = (entry && typeof entry.closest === 'function') ? (entry.closest('div[class*="panelEntry"]') || entry.closest('button') || entry.parentElement || entry) : entry;
292
+ return root !== undefined && root.isConnected && anchor !== null && root.previousElementSibling === anchor;
284
293
  }
285
294
  function createToggle() {
286
295
  let open = false;
@@ -299,6 +308,11 @@ return () => listeners.delete(fn);
299
308
  }
300
309
  };
301
310
  }
311
+ function optionalService(ctx, name) {try {if (ctx && typeof ctx.get === 'function') return ctx.get(name);
312
+ } catch (err) {/* the host does not expose this optional service */
313
+ }
314
+ return undefined;
315
+ }
302
316
  async function openSession(ctx, sessionId) {if (!sessionId) return false;
303
317
  const getSessions = () => (ctx && typeof ctx.get === 'function' ? ctx.get('sessions') : (ctx && ctx.sessions));
304
318
  let sessions = getSessions();
@@ -1413,10 +1427,20 @@ preflightType: 'none',preflightTarget: '',priority: 5,concurrencyGroup: 'default
1413
1427
  captureGitDiff: false,httpMethod: 'GET',httpUrl: '',httpHttpHeaders: '',httpBody: '',sshProfileId: '',sshTarget: '',sshKeyPath: '',dockerImage: '',nodePath: '',pythonPath: '',skillName: '',workflowName: '',});
1414
1428
  setManualModalOpen(true);
1415
1429
  };
1416
- React.useEffect(() => {if (!pendingTaskPreset) return;
1430
+ React.useEffect(() => {
1431
+ const checkPreset = () => {if (!pendingTaskPreset) return;
1417
1432
  const p = pendingTaskPreset;
1418
1433
  pendingTaskPreset = null;
1419
1434
  openManualModal(p);
1435
+ };
1436
+ checkPreset();
1437
+ const onPreset = (ev) => {if (ev && ev.detail) openManualModal(ev.detail);
1438
+ else checkPreset();
1439
+ };
1440
+ if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {window.addEventListener('dsh-cron:preset', onPreset);
1441
+ return () => {try { window.removeEventListener('dsh-cron:preset', onPreset); } catch (_e) { void _e; }
1442
+ };
1443
+ }
1420
1444
  }, [tasks]);
1421
1445
  const handleRetryDelivery = async (taskId, runId) => {setRetryingDeliveryId(runId);
1422
1446
  try {
@@ -2472,38 +2496,9 @@ updateState.currentVersion && !updateState.error && !updateState.checking ? _h('
2472
2496
  )
2473
2497
  );
2474
2498
  }
2475
- function nativeButton() {
2476
- const nodes = document.querySelectorAll('button[class*="newSession"]');
2477
- for (const node of nodes) {if (String(node.className).indexOf('newSessionLabel') === -1) return node;
2478
- }
2479
- return undefined;
2480
- }
2481
- function createEntry(target, toggle, label) {
2482
- const entry = target.cloneNode(true);
2483
- entry.className = String(target.className) + ' dsh-cron-entry-clone';
2484
- entry.setAttribute(ENTRY_ATTR, '');
2485
- entry.setAttribute('data-dsh-plugin', 'dsh-cron');
2486
- entry.setAttribute('data-dsh-part', 'sidebar-entry');
2487
- entry.setAttribute('aria-label', label);
2488
- entry.removeAttribute('id');
2489
- entry.innerHTML = '';
2490
- const icon = document.createElement('span');
2491
- icon.className = 'dsh-cron-entry-icon';
2492
- icon.innerHTML = ICON_TIMER;
2493
- entry.appendChild(icon);
2494
- const text = document.createElement('span');
2495
- text.className = 'dsh-cron-entry-label';
2496
- text.textContent = label;
2497
- entry.appendChild(text);
2498
- entry.addEventListener('click', (event) => {event.preventDefault();
2499
- event.stopPropagation();
2500
- toggle.toggle();
2501
- });
2502
- return entry;
2503
- }
2504
- const SIDEBAR_JOBS_KEY = 'dsh-cron-sidebar-open';
2505
- const SIDEBAR_JOBS_MAX_ROWS = 5;
2506
- function sessionIdOf(ctx, props) {try {if (props && props.session && props.session.id) return String(props.session.id);
2499
+ function sessionIdOf(ctx, props) {try {if (typeof props === 'string' && props) return props;
2500
+ if (props && typeof props.sessionId === 'string' && props.sessionId) return props.sessionId;
2501
+ if (props && props.session && props.session.id) return String(props.session.id);
2507
2502
  if (props && props.session && props.session.sessionId) return String(props.session.sessionId);
2508
2503
  if (props && props.input && props.input.sessionId) return String(props.input.sessionId);
2509
2504
  if (ctx && ctx.scope && ctx.scope.session) return String(ctx.scope.session.id || ctx.scope.session.header?.id || '');
@@ -2551,6 +2546,9 @@ e.stopPropagation();
2551
2546
  const sessionObj = props.session || (ctx && ctx.scope && ctx.scope.session);
2552
2547
  const titleVal = (sessionObj && (sessionObj.title || sessionObj.name)) || '';
2553
2548
  pendingTaskPreset = {title: titleVal ? titleVal + ' (Cron)' : '',targetSessionId: sessionId || '',type: 'llm',schedule: '0 9 * * 1-5',};
2549
+ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') {try {window.dispatchEvent(new CustomEvent('dsh-cron:preset', { detail: pendingTaskPreset }));
2550
+ } catch (_e) { void _e; }
2551
+ }
2554
2552
  toggle.set(true);
2555
2553
  };
2556
2554
  const handleQuickRun = async (e) => {e.preventDefault();
@@ -2581,6 +2579,8 @@ return _h('button', {type: 'button',className: 'dsh-cron-session-add-btn','data-
2581
2579
  _h('span', {key: 'icon',className: 'dsh-cron-session-bar-icon',dangerouslySetInnerHTML: { __html: ICON_TIMER },}),_h('span', { key: 'label' }, T_KEY(barT, 'sessionBar.addRecurring'))
2582
2580
  ]);
2583
2581
  }
2582
+ const SIDEBAR_JOBS_KEY = 'dsh-cron-sidebar-open';
2583
+ const SIDEBAR_JOBS_MAX_ROWS = 5;
2584
2584
  function buildSidebarJobRow(state, task) {
2585
2585
  const row = document.createElement('button');
2586
2586
  row.type = 'button';
@@ -2648,7 +2648,7 @@ headEl.textContent = label;
2648
2648
  headEl.addEventListener('click', (event) => {event.preventDefault();
2649
2649
  event.stopPropagation();
2650
2650
  state.open = !state.open;
2651
- try { window.localStorage.setItem(SIDEBAR_JOBS_KEY, state.open ? '1' : '0'); } catch (err) { /* localStorage write failed */ }
2651
+ try { window.localStorage.setItem(SIDEBAR_JOBS_KEY, state.open ? '1' : '0'); } catch (err) { void err; }
2652
2652
  applySidebarJobsOpen(state);
2653
2653
  });
2654
2654
  root.appendChild(headEl);
@@ -2661,7 +2661,7 @@ state.listEl = listEl;
2661
2661
  return root;
2662
2662
  }
2663
2663
  function placeSidebarJobs(state, label) {
2664
- const entry = document.querySelector('[' + ENTRY_ATTR + ']');
2664
+ const entry = resolveSidebarAnchor();
2665
2665
  if (sidebarJobsSeatIsCurrent(state, entry)) return;
2666
2666
  if (entry === null || entry.parentElement === null) return;
2667
2667
  if (state.root === undefined) {entry.insertAdjacentElement('afterend', buildSidebarJobsRoot(state, label));
@@ -2674,9 +2674,9 @@ applySidebarJobsOpen(state);
2674
2674
  }
2675
2675
  function mountSidebarJobs(toggle, label, openTaskSignal) {if (typeof document === 'undefined') return () => {};
2676
2676
  const state = { toggle, openTaskSignal, root: undefined, listEl: undefined, headEl: undefined, open: false };
2677
- try { state.open = window.localStorage.getItem(SIDEBAR_JOBS_KEY) === '1'; } catch (err) { /* localStorage read failed */ }
2677
+ try { state.open = window.localStorage.getItem(SIDEBAR_JOBS_KEY) === '1'; } catch (err) { void err; }
2678
2678
  let rafPending = false;
2679
- const schedulePlace = () => {if (sidebarJobsSeatIsCurrent(state, document.querySelector('[' + ENTRY_ATTR + ']'))) return;
2679
+ const schedulePlace = () => {if (sidebarJobsSeatIsCurrent(state, resolveSidebarAnchor())) return;
2680
2680
  if (rafPending) return;
2681
2681
  rafPending = true;
2682
2682
  const scheduleFn = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : (cb) => setTimeout(cb, 16);
@@ -2690,7 +2690,7 @@ placeSidebarJobs(state, label);
2690
2690
  loadSidebarJobs(state);
2691
2691
  const fetchTimer = setInterval(() => {
2692
2692
  let isOpen = false;
2693
- try { isOpen = window.localStorage.getItem(SIDEBAR_JOBS_KEY) === '1'; } catch (err) { /* localStorage poll failed */ }
2693
+ try { isOpen = window.localStorage.getItem(SIDEBAR_JOBS_KEY) === '1'; } catch (err) { void err; }
2694
2694
  if (isOpen) loadSidebarJobs(state);
2695
2695
  }, 30000);
2696
2696
  return () => {observer.disconnect();
@@ -2699,39 +2699,6 @@ if (state.root !== undefined && state.root.isConnected) state.root.remove();
2699
2699
  state.root = undefined;
2700
2700
  };
2701
2701
  }
2702
- function placeEntry(target, entry) {
2703
- let anchor = target;
2704
- let next = target.nextElementSibling;
2705
- while (next !== null && next.tagName === 'BUTTON'
2706
- && String(next.className).indexOf('sidebar-entry') >= 0) {anchor = next;
2707
- next = next.nextElementSibling;
2708
- }
2709
- anchor.insertAdjacentElement('afterend', entry);
2710
- }
2711
- function mountSidebarEntry(toggle, label) {if (typeof document === 'undefined') return () => {};
2712
- let entry;
2713
- const tryPlace = () => {if (entry !== undefined && entry.isConnected) return;
2714
- const target = nativeButton();
2715
- if (target === undefined || target.parentElement === null) return;
2716
- if (target.parentElement.querySelector('[' + ENTRY_ATTR + ']') !== null) return;
2717
- entry = createEntry(target, toggle, label);
2718
- placeEntry(target, entry);
2719
- syncActive();
2720
- };
2721
- const syncActive = () => {if (entry === undefined) return;
2722
- if (toggle.isOpen()) entry.dataset.active = 'true';
2723
- else delete entry.dataset.active;
2724
- };
2725
- const observer = new MutationObserver(tryPlace);
2726
- observer.observe(document.body, { childList: true, subtree: true });
2727
- const unsubscribe = toggle.subscribe(syncActive);
2728
- tryPlace();
2729
- return () => {observer.disconnect();
2730
- unsubscribe();
2731
- if (entry !== undefined) entry.remove();
2732
- entry = undefined;
2733
- };
2734
- }
2735
2702
  function mountCronScreen(ctx, toggle) {if (typeof document === 'undefined') return () => {};
2736
2703
  let root;
2737
2704
  let container;
@@ -2745,6 +2712,11 @@ container = undefined;
2745
2712
  const ensure = () => {if (!toggle.isOpen()) {teardownPanel();
2746
2713
  return;
2747
2714
  }
2715
+ const layoutService = optionalService(ctx, 'layout');
2716
+ if (layoutService && typeof layoutService.panelInfo?.getSnapshot === 'function') {if (layoutService.panelInfo.getSnapshot()?.activePanelId === 'dsh-cron') {teardownPanel();
2717
+ return;
2718
+ }
2719
+ }
2748
2720
  if (container !== undefined && container.isConnected) return;
2749
2721
  const column = document.querySelector(COLUMN_SELECTOR);
2750
2722
  if (column === null) return;
@@ -2819,7 +2791,40 @@ if (!cardOk) {console.warn('[dsh-cron] settings.plugin.item slot unavailable —
2819
2791
  const chipOk = registerIntoMount(ctx, 'conversation.session.header.utilities', {name: 'conversation.session.header.utilities',id: PLUGIN_ID + '.chip',order: 27,locale: NS,inject: () => ({ ctx, toggle }),}, CronChip);
2820
2792
  const cardSlot = cardOk ? 'settings.plugin.item' : undefined;
2821
2793
  const chipSlot = chipOk ? 'conversation.session.header.utilities' : undefined;
2822
- const barOk = registerIntoMount(ctx, 'conversation.session.header.actions', {name: 'conversation.session.header.actions',id: PLUGIN_ID + '.sessionBar',order: 28,locale: NS,inject: (slotProps) => ({ ctx, toggle, ...slotProps }),}, function QuickBarBoundary(props) {
2794
+ function CronNavIcon(props) {
2795
+ const size = (props && props.size) || 16;
2796
+ return _h('span', {className: 'dsh-cron-nav-icon','data-dsh-cron-entry': '','data-dsh-plugin': 'dsh-cron',style: { width: size, height: size },dangerouslySetInnerHTML: { __html: ICON_TIMER }
2797
+ });
2798
+ }
2799
+ const navOk = registerIntoMount(ctx, 'sidebar.panellist', {name: 'sidebar.panellist',id: 'dsh-cron',order: 12,label: () => translate('sidebar.label'),locale: NS,}, CronNavIcon);
2800
+ function CronMainPage(props) {
2801
+ return _h(ErrorBoundary, null, _h(CronScreen, {...props,ctx: props.ctx || ctx,toggle: props.toggle || toggle,t: translate,onClose: () => {
2802
+ const layoutService = optionalService(ctx, 'layout');
2803
+ if (layoutService && typeof layoutService.selectPanel === 'function') {layoutService.selectPanel(null);
2804
+ }
2805
+ toggle.set(false);
2806
+ }
2807
+ }));
2808
+ }
2809
+ const mainOk = registerIntoMount(ctx, 'main', {name: 'main',key: 'dsh-cron',locale: NS,inject: () => ({ ctx, toggle }),}, CronMainPage);
2810
+ const layout = optionalService(ctx, 'layout');
2811
+ if (layout && typeof layout.selectPanel === 'function') {toggle.subscribe((isOpen) => {if (isOpen) {layout.selectPanel('dsh-cron');
2812
+ } else if (layout.panelInfo && typeof layout.panelInfo.getSnapshot === 'function') {if (layout.panelInfo.getSnapshot()?.activePanelId === 'dsh-cron') {layout.selectPanel(null);
2813
+ }
2814
+ }
2815
+ });
2816
+ if (layout.panelInfo && typeof layout.panelInfo.subscribe === 'function') {layout.panelInfo.subscribe(() => {
2817
+ const active = layout.panelInfo.getSnapshot()?.activePanelId === 'dsh-cron';
2818
+ if (toggle.isOpen() !== active) {toggle.set(active);
2819
+ }
2820
+ });
2821
+ }
2822
+ }
2823
+ const barOk = registerIntoMount(ctx, 'conversation.session.header.actions', {name: 'conversation.session.header.actions',id: PLUGIN_ID + '.sessionBar',order: 28,locale: NS,inject: (slotParam) => {
2824
+ const sid = typeof slotParam === 'string' ? slotParam : (slotParam && (slotParam.sessionId || slotParam.id));
2825
+ const extra = (typeof slotParam === 'object' && slotParam !== null) ? slotParam : {};
2826
+ return { ctx, toggle, sessionId: sid, ...extra };
2827
+ },}, function QuickBarBoundary(props) {
2823
2828
  return _h(ErrorBoundary, null, _h(SessionQuickActionBar, props));
2824
2829
  });
2825
2830
  const barSlot = barOk ? 'conversation.session.header.actions' : undefined;
@@ -2833,11 +2838,11 @@ dangerouslySetInnerHTML: { __html: ICON_TIMER }
2833
2838
  }
2834
2839
  ctx.effect(() => {
2835
2840
  const off = [
2836
- mountSidebarEntry(toggle, translate('sidebar.label')),mountSidebarJobs(toggle, translate('sidebar.jobsTitle'), (taskId) => { pendingTaskHighlight = taskId; }),mountCronScreen(ctx, toggle)
2841
+ mountSidebarJobs(toggle, translate('sidebar.jobsTitle'), (taskId) => { pendingTaskHighlight = taskId; }),mountCronScreen(ctx, toggle)
2837
2842
  ];
2838
2843
  return () => { for (const dispose of off) dispose(); stopStyleSelfHeal(); };
2839
2844
  }, 'dsh-cron: client overlay');
2840
- exports.slots = { card: cardSlot, chip: chipSlot, sessionBar: barSlot };
2845
+ exports.slots = { card: cardSlot, chip: chipSlot, sessionBar: barSlot, nav: navOk ? 'sidebar.panellist' : undefined, main: mainOk ? 'main' : undefined };
2841
2846
  module.exports.panelDismissRule = shouldDismissPanel;
2842
2847
  module.exports.sidebarJobsSeatIsCurrent = sidebarJobsSeatIsCurrent;
2843
2848
  module.exports.updateHeaderSettings = updateHeaderSettings;
package/lib/cron-tool.js CHANGED
@@ -414,7 +414,9 @@ export async function executeCronTool(store, scheduler, args = {}) {
414
414
  };
415
415
  }
416
416
  try {
417
- return executeCreateTask(store, scheduler, args);
417
+ const created = executeCreateTask(store, scheduler, args);
418
+ await store.flushAsync();
419
+ return created;
418
420
  } catch (err) {
419
421
  return { success: false, message: err.message };
420
422
  }
@@ -467,6 +469,7 @@ export async function executeCronTool(store, scheduler, args = {}) {
467
469
  allowCodeSwitch: confirmCodeSwitch === true,
468
470
  });
469
471
  if (!result.ok) return { success: false, message: result.error };
472
+ await store.flushAsync();
470
473
  return {
471
474
  success: true,
472
475
  message: `Task "${result.task.title}" updated (${result.task.scheduleText || result.task.schedule}). Changed: ${describeTaskPatch(result.task, result.patch)}`,
@@ -503,6 +506,7 @@ export async function executeCronTool(store, scheduler, args = {}) {
503
506
  if (isConfigOwned(store.get(args.id))) return { success: false, message: configOwnedMessage(args.id) };
504
507
  scheduler.pauseTask(args.id);
505
508
  const ok = store.delete(args.id);
509
+ if (ok) await store.flushAsync();
506
510
  return { success: ok, message: ok ? 'Task deleted' : 'Task not found' };
507
511
  }
508
512
 
package/lib/git-diff.js CHANGED
@@ -15,6 +15,18 @@ const execFileAsync = promisify(execFile);
15
15
 
16
16
  export const MAX_DIFF_SIZE = 256 * 1024; // 256 KiB safety ceiling
17
17
 
18
+ /**
19
+ * Normalizes CRLF to LF so a captured diff is byte-stable across platforms.
20
+ * `git diff` emits CRLF on Windows checkouts with `core.autocrlf=true`, and a
21
+ * stored CRLF patch no longer applies on a POSIX host (and vice versa).
22
+ *
23
+ * @param {string} value
24
+ * @returns {string}
25
+ */
26
+ export function normalizeEol(value) {
27
+ return typeof value === 'string' ? value.replace(/\r\n/g, '\n') : value;
28
+ }
29
+
18
30
  /**
19
31
  * Checks if a given directory is inside a git working tree.
20
32
  *
@@ -110,7 +122,7 @@ export async function captureGitDiff(cwd, { maxSize = MAX_DIFF_SIZE } = {}) {
110
122
  try {
111
123
  // 1. Check if there are any changes
112
124
  const { stdout: statusOut } = await execFileAsync('git', ['status', '--porcelain'], { cwd, timeout: 5000 });
113
- const cleanStatus = statusOut.trim();
125
+ const cleanStatus = normalizeEol(statusOut).trim();
114
126
  if (!cleanStatus) {
115
127
  return { hasChanges: false, stat: '', diff: '', files: [], summary: { filesCount: 0, insertions: 0, deletions: 0 } };
116
128
  }
@@ -121,12 +133,12 @@ export async function captureGitDiff(cwd, { maxSize = MAX_DIFF_SIZE } = {}) {
121
133
  let stat = '';
122
134
  try {
123
135
  const { stdout: statOut } = await execFileAsync('git', ['diff', '--stat', 'HEAD'], { cwd, timeout: 5000 });
124
- stat = statOut.trim();
136
+ stat = normalizeEol(statOut).trim();
125
137
  } catch {
126
138
  // Fallback without HEAD (e.g. unborn branch)
127
139
  try {
128
140
  const { stdout: statOut } = await execFileAsync('git', ['diff', '--stat'], { cwd, timeout: 5000 });
129
- stat = statOut.trim();
141
+ stat = normalizeEol(statOut).trim();
130
142
  } catch {
131
143
  stat = `${files.length} file(s) changed`;
132
144
  }
@@ -141,11 +153,11 @@ export async function captureGitDiff(cwd, { maxSize = MAX_DIFF_SIZE } = {}) {
141
153
  let rawDiff = '';
142
154
  try {
143
155
  const { stdout: diffOut } = await execFileAsync('git', ['diff', 'HEAD'], { cwd, timeout: 8000, maxBuffer: 10 * 1024 * 1024 });
144
- rawDiff = diffOut;
156
+ rawDiff = normalizeEol(diffOut);
145
157
  } catch {
146
158
  try {
147
159
  const { stdout: diffOut } = await execFileAsync('git', ['diff'], { cwd, timeout: 8000, maxBuffer: 10 * 1024 * 1024 });
148
- rawDiff = diffOut;
160
+ rawDiff = normalizeEol(diffOut);
149
161
  } catch (err) {
150
162
  rawDiff = `[Diff unavailable: ${err.message}]`;
151
163
  }
package/lib/index.js CHANGED
@@ -218,6 +218,9 @@ export function apply(ctx, rawConfig) {
218
218
  try {
219
219
  const configJobs = Array.isArray(config && config.jobs) ? config.jobs : [];
220
220
  const summary = applyConfigSync({ store, scheduler, entries: configJobs, log: logger });
221
+ // Config-owned tasks are re-synced on every boot, but the first successful
222
+ // sync must reach disk before the scheduler starts arming timers.
223
+ store.flushSync();
221
224
  logger.info('[dsh-cron] config jobs synced: ' + JSON.stringify(summary));
222
225
  } catch (err) {
223
226
  logger.error('[dsh-cron] config job sync failed:', err.message);
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Single source of truth for "is this path safe to touch?" checks.
3
+ *
4
+ * File watchers (`lib/watcher.js`) and wake triggers (`lib/wake-triggers.js`)
5
+ * used to keep two drifting copies of the disallowed-root list: one compared
6
+ * only exact matches (so `/etc/ssh` slipped through), the other compared
7
+ * subtrees but only after `path.resolve()`, so POSIX roots never matched on a
8
+ * Windows host (`/etc` becomes `C:\etc`). Both now delegate here.
9
+ */
10
+
11
+ import path from 'node:path';
12
+
13
+ /** Sensitive locations, written POSIX-style and compared case-insensitively. */
14
+ export const DISALLOWED_ROOTS = Object.freeze([
15
+ '/proc',
16
+ '/sys',
17
+ '/dev',
18
+ '/etc',
19
+ '/boot',
20
+ '/run',
21
+ '/var/run',
22
+ 'c:/windows',
23
+ 'c:/windows/system32',
24
+ 'c:/program files',
25
+ 'c:/program files (x86)',
26
+ ]);
27
+
28
+ function normalize(value) {
29
+ return String(value).split('\\').join('/').replace(/\/+$/, '').toLowerCase();
30
+ }
31
+
32
+ function matchesDisallowedRoot(candidate) {
33
+ for (const root of DISALLOWED_ROOTS) {
34
+ if (candidate === root || candidate.startsWith(root + '/')) return root;
35
+ }
36
+ return null;
37
+ }
38
+
39
+ /**
40
+ * Validates that a path does not target a sensitive system location or a
41
+ * filesystem root.
42
+ *
43
+ * Both the path as written and its resolved form are compared, so a POSIX-style
44
+ * input is rejected on Windows too, and a Windows-style input is rejected
45
+ * regardless of the current drive.
46
+ *
47
+ * @param {string} targetPath
48
+ * @param {string} [label] — prefix used in error messages ("Path", "Watched path").
49
+ * @returns {{ safe: boolean, resolved?: string, error?: string }}
50
+ */
51
+ export function isSafePath(targetPath, label = 'Path') {
52
+ if (!targetPath || typeof targetPath !== 'string') {
53
+ return { safe: false, error: 'Path must be a non-empty string' };
54
+ }
55
+ const trimmed = targetPath.trim();
56
+ if (!trimmed) {
57
+ return { safe: false, error: 'Path must be a non-empty string' };
58
+ }
59
+ if (trimmed.indexOf('\0') !== -1) {
60
+ return { safe: false, error: 'Path must not contain null bytes' };
61
+ }
62
+
63
+ if (matchesDisallowedRoot(normalize(trimmed))) {
64
+ return { safe: false, error: `${label} "${targetPath}" targets a disallowed system location` };
65
+ }
66
+
67
+ const resolved = path.resolve(trimmed);
68
+ if (resolved === path.parse(resolved).root) {
69
+ return { safe: false, error: `${label} "${resolved}" is a filesystem root` };
70
+ }
71
+ if (matchesDisallowedRoot(normalize(resolved))) {
72
+ return { safe: false, error: `${label} "${resolved}" targets a disallowed system location` };
73
+ }
74
+
75
+ return { safe: true, resolved };
76
+ }
@@ -166,6 +166,7 @@ export async function handleItemPost({ store, scheduler, req, res, url, id, acti
166
166
  try {
167
167
  rollbackPromptVersion(task, targetVersion);
168
168
  store.set(task);
169
+ await store.flushAsync();
169
170
  sendJson(res, 200, {
170
171
  ok: true,
171
172
  task: redactTaskSecrets(task),
@@ -304,6 +305,7 @@ export async function handleItemPost({ store, scheduler, req, res, url, id, acti
304
305
  const copy = buildDuplicateTask(source, { id: randomUUID() });
305
306
  try {
306
307
  store.set(copy);
308
+ await store.flushAsync();
307
309
  } catch (err) {
308
310
  sendJson(res, 500, { ok: false, error: 'Failed to persist duplicate task: ' + err.message });
309
311
  return true;
@@ -131,6 +131,7 @@ export async function createOrUpdateTask({ store, scheduler, req, res, apiToken,
131
131
  let task;
132
132
  try {
133
133
  task = store.set(buildTaskRecord(store, body, taskType, parsed));
134
+ await store.flushAsync();
134
135
  } catch (err) {
135
136
  sendJson(res, 500, { ok: false, error: 'Failed to persist task: ' + err.message });
136
137
  return;
@@ -90,7 +90,7 @@ export async function handleTaskImport({ store, scheduler, req, res }) {
90
90
  });
91
91
  return;
92
92
  }
93
- const applied = applyImportPlan({ store, scheduler, plan });
93
+ const applied = await applyImportPlan({ store, scheduler, plan });
94
94
  if (applied.error) {
95
95
  sendJson(res, 500, { ok: false, error: applied.error });
96
96
  return;
@@ -110,7 +110,7 @@ export async function handleTaskImport({ store, scheduler, req, res }) {
110
110
  * "paused" does not stop an already-armed croner job. A failed write rolls the
111
111
  * store back so a partial import cannot survive.
112
112
  */
113
- export function applyImportPlan({ store, scheduler, plan }) {
113
+ export async function applyImportPlan({ store, scheduler, plan }) {
114
114
  const imported = [];
115
115
  const rollback = [];
116
116
  const disarm = [];
@@ -130,6 +130,7 @@ export function applyImportPlan({ store, scheduler, plan }) {
130
130
  rollback.push({ id: replaced.id, previous: before });
131
131
  disarm.push(replaced.id);
132
132
  }
133
+ await store.flushAsync();
133
134
  } catch (writeErr) {
134
135
  for (const entry of rollback.reverse()) {
135
136
  try {
@@ -124,7 +124,7 @@ export async function handleTaskItem({ store, scheduler, req, res, url, id, acti
124
124
  return;
125
125
  }
126
126
  if (req.method === 'DELETE' || (req.method === 'POST' && action === 'delete')) {
127
- deleteTask({ store, scheduler, res, id });
127
+ await deleteTask({ store, scheduler, res, id });
128
128
  return;
129
129
  }
130
130
  sendJson(res, 405, NOT_ALLOWED);
@@ -144,13 +144,20 @@ export async function patchTask({ store, scheduler, req, res, id }) {
144
144
  }
145
145
  const { body, error } = await readBody(req, res);
146
146
  if (error) return;
147
- const result = applyTaskPatch({
148
- store,
149
- scheduler,
150
- id,
151
- body,
152
- allowCodeSwitch: req.headers[SCRIPT_CONFIRM_HEADER] === 'script',
153
- });
147
+ let result;
148
+ try {
149
+ result = applyTaskPatch({
150
+ store,
151
+ scheduler,
152
+ id,
153
+ body,
154
+ allowCodeSwitch: req.headers[SCRIPT_CONFIRM_HEADER] === 'script',
155
+ });
156
+ if (result.ok) await store.flushAsync();
157
+ } catch (err) {
158
+ sendJson(res, 500, { ok: false, error: 'Failed to persist task patch: ' + err.message });
159
+ return;
160
+ }
154
161
  if (!result.ok) {
155
162
  const status = result.status || (result.notFound ? 404 : (result.needsConfirmation ? 403 : 400));
156
163
  const error = result.needsConfirmation
@@ -167,7 +174,7 @@ export async function patchTask({ store, scheduler, req, res, id }) {
167
174
  }
168
175
 
169
176
 
170
- export function deleteTask({ store, scheduler, res, id }) {
177
+ export async function deleteTask({ store, scheduler, res, id }) {
171
178
  const current = store.get(id);
172
179
  if (current && current.managedBy === MANAGED_BY_CONFIG) {
173
180
  refuseConfigOwned(res, id);
@@ -181,6 +188,7 @@ export function deleteTask({ store, scheduler, res, id }) {
181
188
  }
182
189
  try {
183
190
  store.delete(id);
191
+ await store.flushAsync();
184
192
  } catch (err) {
185
193
  sendJson(res, 500, { ok: false, error: 'Failed to delete task: ' + err.message });
186
194
  return;
package/lib/routes/api.js CHANGED
@@ -168,7 +168,7 @@ export async function handleExternalTaskRequest({ store, scheduler, req, res, ur
168
168
  return;
169
169
  }
170
170
  if (req.method === 'DELETE' && !action) {
171
- deleteTask({ store, scheduler, res, id });
171
+ await deleteTask({ store, scheduler, res, id });
172
172
  return;
173
173
  }
174
174
  sendJson(res, 405, NOT_ALLOWED);
@@ -1,6 +1,7 @@
1
1
  import { logStreamer } from '../log-streamer.js';
2
2
  import { logger } from '../logger.js';
3
3
  import { bestEffort } from '../best-effort.js';
4
+ import { spawn } from 'node:child_process';
4
5
  import {
5
6
  buildInvocation,
6
7
  } from './runtimes.js';
@@ -30,14 +31,24 @@ export function terminateProcessTree(child, sig = 'SIGTERM', { isPosix = process
30
31
  if (isPosix && child.pid) {
31
32
  bestEffort('kill-posix-pid', () => process.kill(-child.pid, sig));
32
33
  } else if (child.pid) {
33
- const runner = execFn || ((cmd) => {
34
- void bestEffort('exec-taskkill-fn', () =>
35
- import('node:child_process').then(({ exec }) => {
36
- exec(cmd, { windowsHide: true }, () => {});
37
- }), logger);
38
- });
39
- bestEffort('exec-taskkill', () => runner(`taskkill /pid ${child.pid} /T /F`));
40
- bestEffort('child-kill', () => child.kill(sig));
34
+ if (execFn) {
35
+ bestEffort('exec-taskkill', () => execFn(`taskkill /pid ${child.pid} /T /F`));
36
+ bestEffort('child-kill', () => child.kill(sig));
37
+ } else {
38
+ // Spawning taskkill with an argv array avoids cmd.exe quoting rules.
39
+ // Do NOT call child.kill() here: terminating cmd.exe first detaches the
40
+ // grandchildren, and taskkill can no longer find the process tree (#452).
41
+ bestEffort('spawn-taskkill', () => {
42
+ const killer = spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], {
43
+ windowsHide: true,
44
+ stdio: 'ignore',
45
+ });
46
+ killer.on('error', (err) => {
47
+ logger.warn('[dsh-cron] taskkill failed, falling back to child.kill:', err.message);
48
+ bestEffort('child-kill-fallback', () => child.kill(sig));
49
+ });
50
+ });
51
+ }
41
52
  }
42
53
  });
43
54
  }
@@ -192,12 +203,7 @@ export async function runExternal(task, runtime, signal, execOptions = {}, { ctx
192
203
  let forceKillTimer = null;
193
204
 
194
205
  const killProcessTree = (sig = 'SIGTERM') => {
195
- terminateProcessTree(child, sig, {
196
- isPosix,
197
- execFn: (cmd) => {
198
- bestEffort('exec-cmd', () => exec(cmd, { windowsHide: true }, () => {}));
199
- }
200
- });
206
+ terminateProcessTree(child, sig, { isPosix });
201
207
  };
202
208
 
203
209
  const cleanupTimers = () => {
@@ -258,7 +264,14 @@ export async function runExternal(task, runtime, signal, execOptions = {}, { ctx
258
264
  }
259
265
  const shellPath = isPosix ? (process.env.SHELL || '/bin/bash') : (process.env.ComSpec || 'cmd.exe');
260
266
  const shellArgs = isPosix ? ['-c', command] : ['/d', '/s', '/c', command];
261
- child = spawn(shellPath, shellArgs, options);
267
+ // The command is already a fully formed shell line. Letting Node quote it
268
+ // again corrupts embedded double quotes on Windows (cmd sees the escaped
269
+ // quote as a literal and cuts the argument), so pass argv verbatim there.
270
+ child = spawn(shellPath, shellArgs, {
271
+ ...options,
272
+ windowsHide: true,
273
+ windowsVerbatimArguments: !isPosix,
274
+ });
262
275
  }
263
276
 
264
277
  child.stdout.on('data', (chunk) => {
package/lib/settings.js CHANGED
@@ -158,7 +158,7 @@ export function sanitizeSettingsPayload(body) {
158
158
  delete payload[key];
159
159
  }
160
160
  }
161
- for (const key of ['botTokenRef', 'barkKeyRef', 'giteaTokenRef']) {
161
+ for (const key of ['botTokenRef', 'giteaTokenRef']) {
162
162
  if (key in payload && typeof payload[key] === 'string' && payload[key].trim()) {
163
163
  const refCheck = credentialRefStatus(payload[key]);
164
164
  if (!refCheck.ok) {
@@ -152,6 +152,15 @@ export class TaskStore {
152
152
  return saveAsync(this);
153
153
  }
154
154
 
155
+ /**
156
+ * Durability point for user-facing mutations. `set()`/`delete()` only mark
157
+ * the store dirty and coalesce writes; HTTP and tool handlers await this so a
158
+ * disk failure still becomes an error response instead of a silent 200.
159
+ */
160
+ async flushAsync() {
161
+ return saveAsync(this);
162
+ }
163
+
155
164
  async _writeStoreStream(filePath, data, version) {
156
165
  return writeStoreStream(this, filePath, data, version);
157
166
  }
@@ -300,13 +309,10 @@ export class TaskStore {
300
309
  }
301
310
  }
302
311
  this.tasks.set(id, record);
303
- try {
304
- this.save();
305
- } catch (err) {
306
- if (existing) this.tasks.set(id, existing);
307
- else this.tasks.delete(id);
308
- throw err;
309
- }
312
+ // Persist through the debounced async writer: a synchronous full-store
313
+ // rewrite here blocked the event loop on every mutation (#451). Durability
314
+ // points are `flushSync()` and the lifecycle hook on plugin unload.
315
+ this.scheduleSave(0);
310
316
  return record;
311
317
  }
312
318
 
@@ -317,25 +323,13 @@ export class TaskStore {
317
323
  return null;
318
324
  }
319
325
  const now = Date.now();
320
- const prevPing = task.lastPingAt;
321
- const prevAlerted = task.heartbeatAlerted;
322
- const prevUpdated = task.updatedAt;
323
- const prevStatus = task.lastStatus;
324
326
  task.lastPingAt = now;
325
327
  task.heartbeatAlerted = false;
326
328
  task.updatedAt = now;
327
329
  if (task.lastStatus === 'missed') {
328
330
  task.lastStatus = 'active';
329
331
  }
330
- try {
331
- this.save();
332
- } catch (err) {
333
- task.lastPingAt = prevPing;
334
- task.heartbeatAlerted = prevAlerted;
335
- task.updatedAt = prevUpdated;
336
- task.lastStatus = prevStatus;
337
- throw err;
338
- }
332
+ this.scheduleSave(0);
339
333
  const interval = (task.heartbeatIntervalSeconds || 0) + (task.gracePeriodSeconds || 300);
340
334
  return {
341
335
  ok: true,
@@ -352,16 +346,9 @@ export class TaskStore {
352
346
  }
353
347
  const existing = this.tasks.get(id);
354
348
  if (!existing) return false;
355
- const existingHistory = this.history.get(id);
356
349
  this.tasks.delete(id);
357
350
  this.history.delete(id);
358
- try {
359
- this.save();
360
- } catch (err) {
361
- this.tasks.set(id, existing);
362
- if (existingHistory) this.history.set(id, existingHistory);
363
- throw err;
364
- }
351
+ this.scheduleSave(0);
365
352
  return true;
366
353
  }
367
354
 
@@ -2,60 +2,14 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { logger } from './logger.js';
4
4
  import { bestEffort } from './best-effort.js';
5
-
6
- const DISALLOWED_ROOTS = [
7
- '/proc',
8
- '/sys',
9
- '/dev',
10
- '/etc',
11
- '/boot',
12
- '/run',
13
- '/var/run',
14
- 'c:\\windows',
15
- 'c:\\windows\\system32',
16
- 'c:\\program files',
17
- 'c:\\program files (x86)',
18
- ];
5
+ import { isSafePath } from './path-safety.js';
19
6
 
20
7
  /**
21
8
  * Validates that a path does not target sensitive system locations or escape root.
9
+ * Kept as a named export because the task schema and tests refer to it.
22
10
  */
23
11
  export function isSafeWakePath(targetPath) {
24
- if (!targetPath || typeof targetPath !== 'string') {
25
- return { safe: false, error: 'Path must be a non-empty string' };
26
- }
27
- const trimmed = targetPath.trim();
28
- if (trimmed.indexOf('\0') !== -1) {
29
- return { safe: false, error: 'Path must not contain null bytes' };
30
- }
31
- const rawLower = trimmed.toLowerCase().split('\\').join('/');
32
- if (
33
- rawLower === 'c:' ||
34
- rawLower === 'c:/' ||
35
- rawLower.startsWith('c:/windows') ||
36
- rawLower.startsWith('c:/program files')
37
- ) {
38
- return { safe: false, error: `Path "${targetPath}" targets a disallowed system location` };
39
- }
40
-
41
- const resolved = path.resolve(trimmed);
42
-
43
- // Filesystem root check ('/' on POSIX, 'C:\' on Windows)
44
- if (resolved === path.parse(resolved).root) {
45
- return { safe: false, error: `Path "${resolved}" is a filesystem root` };
46
- }
47
-
48
- const lower = resolved.toLowerCase().split('\\').join('/');
49
-
50
- for (const root of DISALLOWED_ROOTS) {
51
- const normRoot = root.toLowerCase().split('\\').join('/');
52
- const rootWithSlash = normRoot.endsWith('/') ? normRoot : normRoot + '/';
53
- if (lower === normRoot || lower.startsWith(rootWithSlash)) {
54
- return { safe: false, error: `Path "${resolved}" targets a disallowed system location` };
55
- }
56
- }
57
-
58
- return { safe: true, resolved };
12
+ return isSafePath(targetPath);
59
13
  }
60
14
 
61
15
  /**
package/lib/watcher.js CHANGED
@@ -2,22 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { logger } from './logger.js';
4
4
  import { bestEffort } from './best-effort.js';
5
-
6
- const DISALLOWED_ROOTS = [
7
- '/',
8
- '/proc',
9
- '/sys',
10
- '/dev',
11
- '/etc',
12
- '/boot',
13
- '/run',
14
- '/var/run',
15
- 'c:\\',
16
- 'c:\\windows',
17
- 'c:\\windows\\system32',
18
- 'c:\\program files',
19
- 'c:\\program files (x86)',
20
- ];
5
+ import { isSafePath as isSafeTargetPath } from './path-safety.js';
21
6
 
22
7
  /**
23
8
  * FileSystemWatcherManager handles fs.watch instances for tasks configured with fileWatch (#327).
@@ -32,23 +17,7 @@ export class FileSystemWatcherManager {
32
17
  }
33
18
 
34
19
  isSafePath(targetPath) {
35
- if (!targetPath || typeof targetPath !== 'string') {
36
- return { safe: false, error: 'Path must be a non-empty string' };
37
- }
38
- const resolved = path.resolve(targetPath.trim());
39
- const lower = resolved.toLowerCase();
40
-
41
- for (const root of DISALLOWED_ROOTS) {
42
- if (lower === root || lower === root.replace(/\\/g, '/')) {
43
- return { safe: false, error: `Watched path "${resolved}" is a disallowed system root directory` };
44
- }
45
- }
46
-
47
- if (resolved === path.parse(resolved).root) {
48
- return { safe: false, error: `Watched path "${resolved}" is a filesystem root` };
49
- }
50
-
51
- return { safe: true, resolved };
20
+ return isSafeTargetPath(targetPath, 'Watched path');
52
21
  }
53
22
 
54
23
  matchPattern(filename, pattern) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-cron",
3
- "version": "0.3.46",
3
+ "version": "0.3.48",
4
4
  "packageManager": "pnpm@10.33.2",
5
5
  "description": "Background automation runner for DSH: isolated agent runs, script/HTTP/SSH/Docker runtimes, cost guard, notifications, heartbeats.",
6
6
  "type": "module",
@@ -26,6 +26,7 @@
26
26
  "build:client": "node scripts/build-client.mjs",
27
27
  "pretest": "node scripts/build-client.mjs",
28
28
  "preflight": "node scripts/ci-preflight.mjs",
29
+ "check:client-inject": "node scripts/check-client-inject.mjs",
29
30
  "test:engine": "node scripts/test-engines.mjs",
30
31
  "build:client:check": "node scripts/build-client.mjs --check"
31
32
  },
@@ -61,9 +62,10 @@
61
62
  "dshReleases": {
62
63
  "0.2.1-rc.2": "compatible",
63
64
  "0.2.1-rc.3": "compatible",
64
- "0.2.1-rc.4": "compatible"
65
+ "0.2.1-rc.4": "compatible",
66
+ "0.2.2-rc.3": "compatible"
65
67
  },
66
- "dsh": ">=0.2.1-rc.2 <0.2.2-0"
68
+ "dsh": ">=0.2.1-rc.2 <0.2.3-0"
67
69
  }
68
70
  },
69
71
  "dependencies": {