@goodandready/dsh-cron 0.2.14 → 0.2.16

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/lib/updater.js ADDED
@@ -0,0 +1,237 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { basename, dirname, isAbsolute, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { rejectCrossOrigin } from './http-utils.js';
8
+
9
+ const UPDATE_TIMEOUT_MS = 10 * 60_000;
10
+ const VERSION_CACHE_MS = 5 * 60_000;
11
+ let latestCache = null;
12
+
13
+ function validProfileName(value) {
14
+ return typeof value === 'string' && value !== '' && value !== '.' && value !== '..'
15
+ && !value.includes('/') && !value.includes('\\') && !/[\0-\x1f\x7f]/.test(value);
16
+ }
17
+
18
+ function profileNameFromArgv(argv) {
19
+ for (let index = 2; index < argv.length; index += 1) {
20
+ if (argv[index] === '--profile' || argv[index] === '-p') return argv[index + 1];
21
+ if (argv[index]?.startsWith('--profile=')) return argv[index].slice('--profile='.length);
22
+ }
23
+ return argv[2] === 'web' ? 'web' : undefined;
24
+ }
25
+
26
+ function findDshCliEntry() {
27
+ const value = process.argv[1];
28
+ if (value === undefined || value === '') return undefined;
29
+ const entry = value.startsWith('file:') ? fileURLToPath(value) : resolve(process.cwd(), value);
30
+ if (!existsSync(entry)) return undefined;
31
+ for (let directory = dirname(entry); ; directory = dirname(directory)) {
32
+ const manifestPath = resolve(directory, 'package.json');
33
+ if (existsSync(manifestPath)) {
34
+ try {
35
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
36
+ const bin = typeof manifest.bin === 'string'
37
+ ? manifest.bin
38
+ : typeof manifest.bin === 'object' && manifest.bin !== null
39
+ ? manifest.bin.dsh
40
+ : undefined;
41
+ if (manifest.name === '@deepseek-ai/dsh' && typeof bin === 'string'
42
+ && !isAbsolute(bin) && resolve(directory, bin) === resolve(entry)) return entry;
43
+ } catch {
44
+ // Continue searching parent directories
45
+ }
46
+ }
47
+ const parent = dirname(directory);
48
+ if (parent === directory) return undefined;
49
+ }
50
+ }
51
+
52
+ export function runtime() {
53
+ const profileDir = resolve(process.env.DSH_PROFILE_DIR
54
+ ?? resolve(homedir(), '.dsh', 'profiles', 'web'));
55
+ const selected = profileNameFromArgv(process.argv);
56
+ const profileName = validProfileName(selected)
57
+ ? selected
58
+ : validProfileName(basename(profileDir)) ? basename(profileDir) : 'web';
59
+ const cliEntry = findDshCliEntry();
60
+ return cliEntry === undefined ? { profileName, profileDir } : { profileName, profileDir, cliEntry };
61
+ }
62
+
63
+ export function parseSemver(value) {
64
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(String(value || '').trim());
65
+ if (match === null) return undefined;
66
+ return {
67
+ core: [Number(match[1]), Number(match[2]), Number(match[3])],
68
+ prerelease: match[4]?.split('.') ?? [],
69
+ };
70
+ }
71
+
72
+ function comparePrerelease(left, right) {
73
+ if (left.length === 0 || right.length === 0) return left.length === right.length ? 0 : left.length === 0 ? 1 : -1;
74
+ const length = Math.max(left.length, right.length);
75
+ for (let index = 0; index < length; index += 1) {
76
+ const a = left[index];
77
+ const b = right[index];
78
+ if (a === undefined || b === undefined) return a === b ? 0 : a === undefined ? -1 : 1;
79
+ if (a === b) continue;
80
+ const aNumeric = /^\d+$/.test(a);
81
+ const bNumeric = /^\d+$/.test(b);
82
+ if (aNumeric && bNumeric) {
83
+ const aNumber = BigInt(a);
84
+ const bNumber = BigInt(b);
85
+ if (aNumber !== bNumber) return aNumber > bNumber ? 1 : -1;
86
+ continue;
87
+ }
88
+ if (aNumeric !== bNumeric) return aNumeric ? -1 : 1;
89
+ return a > b ? 1 : -1;
90
+ }
91
+ return 0;
92
+ }
93
+
94
+ export function isNewerVersion(currentValue, candidateValue) {
95
+ const current = parseSemver(currentValue);
96
+ const candidate = parseSemver(candidateValue);
97
+ if (current === undefined || candidate === undefined) return false;
98
+ for (let index = 0; index < 3; index += 1) {
99
+ if (candidate.core[index] !== current.core[index]) return candidate.core[index] > current.core[index];
100
+ }
101
+ return comparePrerelease(candidate.prerelease, current.prerelease) > 0;
102
+ }
103
+
104
+ export async function latestVersion(packageName, registry = 'https://registry.npmjs.org') {
105
+ if (latestCache?.packageName === packageName && latestCache.registry === registry && Date.now() < latestCache.expiresAt) {
106
+ return latestCache.version;
107
+ }
108
+ try {
109
+ const cleanReg = registry.replace(/\/$/, '');
110
+ const response = await fetch(`${cleanReg}/${encodeURIComponent(packageName)}/latest`, {
111
+ signal: AbortSignal.timeout(8000),
112
+ headers: { accept: 'application/json' },
113
+ });
114
+ if (!response.ok) return undefined;
115
+ const value = await response.json();
116
+ if (typeof value.version !== 'string' || value.version === '') return undefined;
117
+ latestCache = { packageName, registry, version: value.version, expiresAt: Date.now() + VERSION_CACHE_MS };
118
+ return value.version;
119
+ } catch {
120
+ return undefined;
121
+ }
122
+ }
123
+
124
+ export async function currentVersion(manifestUrl) {
125
+ const raw = await readFile(manifestUrl, 'utf8');
126
+ const value = JSON.parse(raw);
127
+ if (typeof value.version !== 'string' || value.version === '') throw new Error('Cannot read current plugin version.');
128
+ return value.version;
129
+ }
130
+
131
+ export async function getUpdateStatus(options, target = runtime()) {
132
+ const current = await currentVersion(options.manifestUrl);
133
+ const latest = await latestVersion(options.packageName, options.registry ?? 'https://registry.npmjs.org');
134
+ return {
135
+ packageName: options.packageName,
136
+ currentVersion: current,
137
+ ...(latest === undefined ? {} : { latestVersion: latest }),
138
+ latestCheckFailed: latest === undefined,
139
+ updateAvailable: latest !== undefined && isNewerVersion(current, latest),
140
+ profileName: target.profileName,
141
+ canAutoUpdate: target.cliEntry !== undefined,
142
+ };
143
+ }
144
+
145
+ export async function installExact(target, packageSpec, options = {}) {
146
+ if (target.cliEntry === undefined) throw new Error('Automatic update is unavailable in this runtime.');
147
+ return new Promise((resolvePromise, reject) => {
148
+ // IMPORTANT: As required by #147, do NOT add minimumReleaseAge bypass
149
+ const args = [
150
+ target.cliEntry, 'plugin', '--profile', target.profileName, 'add',
151
+ packageSpec,
152
+ `--registry=${options.registry ?? 'https://registry.npmjs.org/'}`,
153
+ ];
154
+ const child = spawn(process.execPath, args, {
155
+ cwd: target.profileDir,
156
+ windowsHide: true,
157
+ stdio: ['ignore', 'pipe', 'pipe'],
158
+ env: { ...process.env, NO_COLOR: '1' },
159
+ });
160
+ let detail = '';
161
+ child.stdout?.on('data', chunk => { detail = (detail + String(chunk)).slice(-4000); });
162
+ child.stderr?.on('data', chunk => { detail = (detail + String(chunk)).slice(-4000); });
163
+ const timer = setTimeout(() => {
164
+ child.kill();
165
+ reject(new Error('Update timed out; use the normal DSH update flow.'));
166
+ }, UPDATE_TIMEOUT_MS);
167
+ child.once('error', error => { clearTimeout(timer); reject(error); });
168
+ child.once('exit', code => {
169
+ clearTimeout(timer);
170
+ if (code === 0) resolvePromise();
171
+ else reject(new Error(detail.trim() || `Update exited with code ${String(code)}.`));
172
+ });
173
+ });
174
+ }
175
+
176
+ export function registerPluginUpdater(ctx, options) {
177
+ let installing = false;
178
+ return ctx.webServer.register({
179
+ kind: 'exact',
180
+ path: options.endpoint || '/api/dsh-cron/update',
181
+ handler: async (req, res) => {
182
+ try {
183
+ const target = runtime();
184
+ if (req.method === 'GET' || req.method === 'HEAD') {
185
+ const payload = await getUpdateStatus(options, target);
186
+ res.writeHead(200, {
187
+ 'content-type': 'application/json; charset=utf-8',
188
+ 'cache-control': 'no-store',
189
+ });
190
+ res.end(req.method === 'HEAD' ? undefined : JSON.stringify(payload));
191
+ return;
192
+ }
193
+ if (req.method !== 'POST') {
194
+ res.writeHead(405, { allow: 'GET, HEAD, POST' });
195
+ res.end();
196
+ return;
197
+ }
198
+ if (rejectCrossOrigin(req, res)) {
199
+ return;
200
+ }
201
+ if (installing) {
202
+ res.writeHead(409, { 'content-type': 'application/json; charset=utf-8' });
203
+ res.end(JSON.stringify({ ok: false, error: 'This plugin is already updating.' }));
204
+ return;
205
+ }
206
+ installing = true;
207
+ try {
208
+ const before = await getUpdateStatus(options, target);
209
+ if (before.latestVersion === undefined) {
210
+ res.writeHead(503, { 'content-type': 'application/json; charset=utf-8' });
211
+ res.end(JSON.stringify({ ok: false, error: 'The latest version is temporarily unavailable.' }));
212
+ return;
213
+ }
214
+ if (!before.updateAvailable) {
215
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
216
+ res.end(JSON.stringify({ ...before, updated: false, message: 'Already up to date.' }));
217
+ return;
218
+ }
219
+ await installExact(target, `${options.packageName}@${before.latestVersion}`, options);
220
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
221
+ res.end(JSON.stringify({
222
+ ...before,
223
+ updated: true,
224
+ updatedVersion: before.latestVersion,
225
+ restartRequired: true,
226
+ }));
227
+ } finally {
228
+ installing = false;
229
+ }
230
+ } catch (error) {
231
+ (ctx.logger || console).warn?.(`[dsh-cron] plugin updater failed: ${String(error)}`);
232
+ res.writeHead(503, { 'content-type': 'application/json; charset=utf-8' });
233
+ res.end(JSON.stringify({ ok: false, error: 'Plugin update failed; see server logs.' }));
234
+ }
235
+ },
236
+ });
237
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-cron",
3
- "version": "0.2.14",
3
+ "version": "0.2.16",
4
4
  "description": "Scheduled cron tasks, background automation and agent execution for DeepSeek Harness.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -14,8 +14,6 @@
14
14
  "lib/",
15
15
  "cordis.patch.yml",
16
16
  "README.md",
17
- "docs/README.ru.md",
18
- "docs/README.zh.md",
19
17
  "LICENSE"
20
18
  ],
21
19
  "scripts": {
@@ -44,7 +42,10 @@
44
42
  },
45
43
  "client": {
46
44
  "platform": "web",
47
- "inject": []
45
+ "inject": [
46
+ "locale",
47
+ "slots"
48
+ ]
48
49
  }
49
50
  },
50
51
  "dependencies": {