@goodandready/dsh-goal 0.2.2 → 0.2.4

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,317 @@
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
+
8
+ /**
9
+ * Host-side one-click updater for @goodandready/dsh-goal.
10
+ * Based on canonical plugin-updater pattern from dsh-plugin-authoring.
11
+ */
12
+
13
+ const UPDATE_HEADER = 'x-dsh-plugin-update';
14
+ const UPDATE_TIMEOUT_MS = 10 * 60_000;
15
+ const VERSION_CACHE_MS = 5 * 60_000;
16
+ let latestCache;
17
+
18
+ function header(request, name) {
19
+ const value = request?.headers?.[name];
20
+ return Array.isArray(value) ? value[0] : value;
21
+ }
22
+
23
+ export function isLoopback(value) {
24
+ const address = value?.toLowerCase()?.replace(/^\[|\]$/g, '');
25
+ return (
26
+ address === 'localhost' ||
27
+ address === 'localhost.' ||
28
+ address === '::1' ||
29
+ address?.startsWith('127.') === true ||
30
+ address?.startsWith('::ffff:127.') === true
31
+ );
32
+ }
33
+
34
+ export function isTrustedUpdateRequest(request) {
35
+ if (header(request, UPDATE_HEADER) !== '1') return false;
36
+ if (!isLoopback(request.socket?.remoteAddress)) return false;
37
+ const site = header(request, 'sec-fetch-site');
38
+ if (site !== undefined && site !== 'same-origin') return false;
39
+ const origin = header(request, 'origin');
40
+ const host = header(request, 'host');
41
+ if (origin === undefined || host === undefined) return false;
42
+ try {
43
+ const url = new URL(origin);
44
+ return (
45
+ (url.protocol === 'http:' || url.protocol === 'https:') &&
46
+ isLoopback(url.hostname) &&
47
+ url.host === host
48
+ );
49
+ } catch (err) {
50
+ return false;
51
+ }
52
+ }
53
+
54
+ function validProfileName(value) {
55
+ return (
56
+ typeof value === 'string' &&
57
+ value !== '' &&
58
+ value !== '.' &&
59
+ value !== '..' &&
60
+ !value.includes('/') &&
61
+ !value.includes('\\') &&
62
+ ![...value].some((c) => c.charCodeAt(0) <= 31 || c.charCodeAt(0) === 127)
63
+ );
64
+ }
65
+
66
+ function profileNameFromArgv(argv) {
67
+ for (let index = 2; index < argv.length; index += 1) {
68
+ if (argv[index] === '--profile') return argv[index + 1];
69
+ if (argv[index]?.startsWith('--profile=')) return argv[index].slice('--profile='.length);
70
+ }
71
+ return argv[2] === 'web' ? 'web' : undefined;
72
+ }
73
+
74
+ function findDshCliEntry() {
75
+ const value = process.argv[1];
76
+ if (value === undefined || value === '') return undefined;
77
+ const entry = value.startsWith('file:') ? fileURLToPath(value) : resolve(process.cwd(), value);
78
+ if (!existsSync(entry)) return undefined;
79
+ for (let directory = dirname(entry); ; directory = dirname(directory)) {
80
+ const manifestPath = resolve(directory, 'package.json');
81
+ if (existsSync(manifestPath)) {
82
+ try {
83
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
84
+ const bin =
85
+ typeof manifest.bin === 'string'
86
+ ? manifest.bin
87
+ : typeof manifest.bin === 'object' && manifest.bin !== null
88
+ ? manifest.bin.dsh
89
+ : undefined;
90
+ if (
91
+ manifest.name === '@deepseek-ai/dsh' &&
92
+ typeof bin === 'string' &&
93
+ !isAbsolute(bin) &&
94
+ resolve(directory, bin) === resolve(entry)
95
+ ) {
96
+ return entry;
97
+ }
98
+ } catch (err) {
99
+ // Continue searching parent directories
100
+ }
101
+ }
102
+ const parent = dirname(directory);
103
+ if (parent === directory) return undefined;
104
+ }
105
+ }
106
+
107
+ function runtime() {
108
+ const profileDir = resolve(process.env.DSH_PROFILE_DIR ?? resolve(homedir(), '.dsh', 'profiles', 'web'));
109
+ const selected = profileNameFromArgv(process.argv);
110
+ const profileName = validProfileName(selected)
111
+ ? selected
112
+ : validProfileName(basename(profileDir))
113
+ ? basename(profileDir)
114
+ : 'web';
115
+ const cliEntry = findDshCliEntry();
116
+ return cliEntry === undefined ? { profileName, profileDir } : { profileName, profileDir, cliEntry };
117
+ }
118
+
119
+ function parseSemver(value) {
120
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(value);
121
+ if (match === null) return undefined;
122
+ return {
123
+ core: [Number(match[1]), Number(match[2]), Number(match[3])],
124
+ prerelease: match[4]?.split('.') ?? [],
125
+ };
126
+ }
127
+
128
+ function comparePrerelease(left, right) {
129
+ if (left.length === 0 || right.length === 0) {
130
+ return left.length === right.length ? 0 : left.length === 0 ? 1 : -1;
131
+ }
132
+ const length = Math.max(left.length, right.length);
133
+ for (let index = 0; index < length; index += 1) {
134
+ const a = left[index];
135
+ const b = right[index];
136
+ if (a === undefined || b === undefined) return a === b ? 0 : a === undefined ? -1 : 1;
137
+ if (a === b) continue;
138
+ const aNumeric = /^\d+$/.test(a);
139
+ const bNumeric = /^\d+$/.test(b);
140
+ if (aNumeric && bNumeric) {
141
+ const aNumber = BigInt(a);
142
+ const bNumber = BigInt(b);
143
+ if (aNumber !== bNumber) return aNumber > bNumber ? 1 : -1;
144
+ continue;
145
+ }
146
+ if (aNumeric !== bNumeric) return aNumeric ? -1 : 1;
147
+ return a > b ? 1 : -1;
148
+ }
149
+ return 0;
150
+ }
151
+
152
+ export function isNewerVersion(currentValue, candidateValue) {
153
+ const current = parseSemver(currentValue);
154
+ const candidate = parseSemver(candidateValue);
155
+ if (current === undefined || candidate === undefined) return false;
156
+ for (let index = 0; index < 3; index += 1) {
157
+ if (candidate.core[index] !== current.core[index]) {
158
+ return candidate.core[index] > current.core[index];
159
+ }
160
+ }
161
+ return comparePrerelease(candidate.prerelease, current.prerelease) > 0;
162
+ }
163
+
164
+ async function latestVersion(packageName, registry) {
165
+ if (
166
+ latestCache?.packageName === packageName &&
167
+ latestCache.registry === registry &&
168
+ Date.now() < latestCache.expiresAt
169
+ ) {
170
+ return latestCache.version;
171
+ }
172
+ try {
173
+ const response = await fetch(`${registry.replace(/\/$/, '')}/${encodeURIComponent(packageName)}/latest`, {
174
+ signal: AbortSignal.timeout(8_000),
175
+ });
176
+ if (!response.ok) return undefined;
177
+ const value = await response.json();
178
+ if (typeof value?.version !== 'string' || value.version === '') return undefined;
179
+ latestCache = { packageName, registry, version: value.version, expiresAt: Date.now() + VERSION_CACHE_MS };
180
+ return value.version;
181
+ } catch (err) {
182
+ return undefined;
183
+ }
184
+ }
185
+
186
+ async function currentVersion(manifestUrl) {
187
+ const value = JSON.parse(await readFile(manifestUrl, 'utf8'));
188
+ if (typeof value?.version !== 'string' || value.version === '') {
189
+ throw new Error('Cannot read current plugin version.');
190
+ }
191
+ return value.version;
192
+ }
193
+
194
+ async function status(options, target) {
195
+ const current = await currentVersion(options.manifestUrl);
196
+ const latest = await latestVersion(options.packageName, options.registry ?? 'https://registry.npmjs.org');
197
+ return {
198
+ packageName: options.packageName,
199
+ currentVersion: current,
200
+ ...(latest === undefined ? {} : { latestVersion: latest }),
201
+ latestCheckFailed: latest === undefined,
202
+ updateAvailable: latest !== undefined && isNewerVersion(current, latest),
203
+ profileName: target.profileName,
204
+ canAutoUpdate: target.cliEntry !== undefined,
205
+ };
206
+ }
207
+
208
+ async function installExact(target, packageSpec, options) {
209
+ if (target.cliEntry === undefined) {
210
+ throw new Error('Automatic update is unavailable in this runtime.');
211
+ }
212
+ await new Promise((resolvePromise, reject) => {
213
+ // Note: Do not pass --config.minimumReleaseAge=0 per Issue #49
214
+ const args = [
215
+ target.cliEntry,
216
+ 'plugin',
217
+ '--profile',
218
+ target.profileName,
219
+ 'add',
220
+ packageSpec,
221
+ `--registry=${options.registry ?? 'https://registry.npmjs.org/'}`,
222
+ ];
223
+ const child = spawn(process.execPath, args, {
224
+ cwd: target.profileDir,
225
+ windowsHide: true,
226
+ stdio: ['ignore', 'pipe', 'pipe'],
227
+ env: { ...process.env, NO_COLOR: '1' },
228
+ });
229
+ let detail = '';
230
+ child.stdout?.on('data', (chunk) => {
231
+ detail = (detail + String(chunk)).slice(-4_000);
232
+ });
233
+ child.stderr?.on('data', (chunk) => {
234
+ detail = (detail + String(chunk)).slice(-4_000);
235
+ });
236
+ const timer = setTimeout(() => {
237
+ child.kill();
238
+ reject(new Error('Update timed out; use normal DSH update flow.'));
239
+ }, UPDATE_TIMEOUT_MS);
240
+ child.once('error', (error) => {
241
+ clearTimeout(timer);
242
+ reject(error);
243
+ });
244
+ child.once('exit', (code) => {
245
+ clearTimeout(timer);
246
+ if (code === 0) resolvePromise();
247
+ else reject(new Error(detail.trim() || `Update exited with code ${String(code)}.`));
248
+ });
249
+ });
250
+ }
251
+
252
+ function json(response, statusCode, value) {
253
+ response.writeHead(statusCode, {
254
+ 'content-type': 'application/json; charset=utf-8',
255
+ 'cache-control': 'no-store',
256
+ });
257
+ response.end(JSON.stringify(value));
258
+ }
259
+
260
+ export function registerPluginUpdater(ctx, options) {
261
+ const host = ctx;
262
+ let installing = false;
263
+ return host.webServer.register({
264
+ kind: 'exact',
265
+ path: options.endpoint,
266
+ handler: async (request, response) => {
267
+ try {
268
+ const target = runtime();
269
+ if (request.method === 'GET' || request.method === 'HEAD') {
270
+ const payload = await status(options, target);
271
+ response.writeHead(200, {
272
+ 'content-type': 'application/json; charset=utf-8',
273
+ 'cache-control': 'no-store',
274
+ });
275
+ response.end(request.method === 'HEAD' ? undefined : JSON.stringify(payload));
276
+ return;
277
+ }
278
+ if (request.method !== 'POST') {
279
+ response.writeHead(405, { allow: 'GET, HEAD, POST' });
280
+ response.end();
281
+ return;
282
+ }
283
+ if (!isTrustedUpdateRequest(request)) {
284
+ json(response, 403, { error: 'Rejected non-local or cross-origin update request.' });
285
+ return;
286
+ }
287
+ if (installing) {
288
+ json(response, 409, { error: 'This plugin is already updating.' });
289
+ return;
290
+ }
291
+ installing = true;
292
+ try {
293
+ const before = await status(options, target);
294
+ if (before.latestVersion === undefined) {
295
+ json(response, 503, { error: 'The latest version is temporarily unavailable.' });
296
+ return;
297
+ }
298
+ if (!before.updateAvailable) {
299
+ json(response, 200, before);
300
+ return;
301
+ }
302
+ await installExact(target, `${options.packageName}@${before.latestVersion}`, options);
303
+ json(response, 200, {
304
+ ...before,
305
+ updatedVersion: before.latestVersion,
306
+ restartRequired: true,
307
+ });
308
+ } finally {
309
+ installing = false;
310
+ }
311
+ } catch (error) {
312
+ ctx?.logger?.warn?.(`[dsh-goal] plugin updater failed: ${String(error)}`);
313
+ json(response, 503, { error: 'Plugin update failed; see server logs.' });
314
+ }
315
+ },
316
+ });
317
+ }
package/package.json CHANGED
@@ -1,63 +1,62 @@
1
- {
2
- "name": "@goodandready/dsh-goal",
3
- "version": "0.2.2",
4
- "description": "Autonomous Goal Execution & Multi-Turn Task Tracking Engine with Sticky Header for DeepSeek Harness",
5
- "type": "module",
6
- "main": "./lib/index.js",
7
- "exports": {
8
- ".": "./lib/index.js",
9
- "./client": "./lib/client.js",
10
- "./package.json": "./package.json",
11
- "./cordis.patch.yml": "./cordis.patch.yml"
12
- },
13
- "files": [
14
- "lib",
15
- "package.json",
16
- "README.md",
17
- "README.ru.md",
18
- "README.zh.md",
19
- "cordis.patch.yml",
20
- "LICENSE"
21
- ],
22
- "scripts": {
23
- "test": "node --test test/*.test.mjs"
24
- },
25
- "keywords": [
26
- "dsh",
27
- "dsh-plugin",
28
- "deepseek-harness",
29
- "goal-mode",
30
- "autonomous-agent",
31
- "cordis"
32
- ],
33
- "repository": {
34
- "type": "git",
35
- "url": "https://github.com/GooDAnDReaDY/dsh-goal.git"
36
- },
37
- "homepage": "https://github.com/GooDAnDReaDY/dsh-goal",
38
- "bugs": {
39
- "url": "https://github.com/GooDAnDReaDY/dsh-goal/issues"
40
- },
41
- "author": "goodandready",
42
- "license": "MIT",
43
- "dsh": {
44
- "bundle": {
45
- "patch": "./cordis.patch.yml"
46
- },
47
- "client": {
48
- "platform": "web",
49
- "inject": []
50
- }
51
- },
52
- "peerDependencies": {
53
- "@deepseek-ai/cordis": "^4.0.1",
54
- "@deepseek-ai/dsh-host-webserver": "^0.1.0-rc.6",
55
- "@deepseek-ai/schemastery": "^3.18.1"
56
- },
57
- "devDependencies": {
58
- "@deepseek-ai/schemastery": "^3.18.1"
59
- },
60
- "dependencies": {
61
- "@deepseek-ai/schemastery": "^3.18.1"
62
- }
63
- }
1
+ {
2
+ "name": "@goodandready/dsh-goal",
3
+ "version": "0.2.4",
4
+ "description": "Autonomous Goal Execution & Multi-Turn Task Tracking Engine with Sticky Header for DeepSeek Harness",
5
+ "type": "module",
6
+ "main": "./lib/index.js",
7
+ "exports": {
8
+ ".": "./lib/index.js",
9
+ "./client": "./lib/client.js",
10
+ "./package.json": "./package.json",
11
+ "./cordis.patch.yml": "./cordis.patch.yml"
12
+ },
13
+ "files": [
14
+ "lib",
15
+ "README.md",
16
+ "README.ru.md",
17
+ "README.zh.md",
18
+ "cordis.patch.yml",
19
+ "LICENSE"
20
+ ],
21
+ "scripts": {
22
+ "test": "node --test test/*.test.mjs"
23
+ },
24
+ "keywords": [
25
+ "dsh",
26
+ "dsh-plugin",
27
+ "deepseek-harness",
28
+ "goal-mode",
29
+ "autonomous-agent",
30
+ "cordis"
31
+ ],
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "https://github.com/GooDAnDReaDY/dsh-goal.git"
35
+ },
36
+ "homepage": "https://github.com/GooDAnDReaDY/dsh-goal",
37
+ "bugs": {
38
+ "url": "https://github.com/GooDAnDReaDY/dsh-goal/issues"
39
+ },
40
+ "author": "goodandready",
41
+ "license": "MIT",
42
+ "dsh": {
43
+ "bundle": {
44
+ "patch": "./cordis.patch.yml"
45
+ },
46
+ "client": {
47
+ "platform": "web",
48
+ "inject": []
49
+ }
50
+ },
51
+ "peerDependencies": {
52
+ "@deepseek-ai/cordis": "^4.0.1",
53
+ "@deepseek-ai/dsh-host-webserver": "^0.1.0-rc.6",
54
+ "@deepseek-ai/schemastery": "^3.18.1"
55
+ },
56
+ "devDependencies": {
57
+ "@deepseek-ai/schemastery": "^3.18.1"
58
+ },
59
+ "dependencies": {
60
+ "@deepseek-ai/schemastery": "^3.18.1"
61
+ }
62
+ }