@goodandready/dsh-agent-loop-guard 0.2.3 → 0.2.5

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