dsh-mcviseron-plugin 0.0.0-stage → 0.6.2
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/CHANGELOG.md +222 -0
- package/CONTRIBUTING.md +60 -0
- package/LICENSE +202 -0
- package/README.en.md +146 -0
- package/README.md +287 -2
- package/SECURITY.md +38 -0
- package/cordis.patch.yml +12 -0
- package/docs/automation-task.md +63 -0
- package/docs/migration-from-standalone.md +115 -0
- package/docs/release.md +85 -0
- package/lib/appearance.js +320 -0
- package/lib/auto-review-fix.js +453 -0
- package/lib/client.js +1266 -0
- package/lib/index.js +1701 -0
- package/lib/restart.js +226 -0
- package/lib/task-guard.js +736 -0
- package/package.json +148 -4
- package/scripts/repair-profile.mjs +77 -0
- package/src/api.ts +5 -0
- package/src/appearance/index.ts +103 -0
- package/src/auto-review-fix/index.ts +45 -0
- package/src/client/AppearanceScheduleRow.tsx +112 -0
- package/src/client/ConfigForm.tsx +284 -0
- package/src/client/FallbackRestartRow.tsx +23 -0
- package/src/client/RestartCard.tsx +108 -0
- package/src/client/SettingsSection.tsx +110 -0
- package/src/client/bridge.ts +131 -0
- package/src/client/driver.ts +166 -0
- package/src/client/index.ts +114 -0
- package/src/client/locales.ts +193 -0
- package/src/client/primitives.d.ts +15 -0
- package/src/client/section-presence.ts +33 -0
- package/src/client/styles.ts +154 -0
- package/src/components/auto-review-fix/index.ts +421 -0
- package/src/components/auto-review-fix/translate.ts +235 -0
- package/src/components/task-guard/index.ts +1077 -0
- package/src/index.ts +71 -0
- package/src/loopback.ts +48 -0
- package/src/namespace.ts +7 -0
- package/src/restart/index.ts +268 -0
- package/src/routes.ts +228 -0
- package/src/schedule.ts +125 -0
- package/src/task-guard/index.ts +52 -0
- package/src/volatile.ts +32 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
2
|
+
import z from '@deepseek-ai/schemastery'
|
|
3
|
+
import * as appearance from './appearance/index.ts'
|
|
4
|
+
import * as autoReviewFix from './auto-review-fix/index.ts'
|
|
5
|
+
import { DEFAULT_AUTO_REVIEW_CONFIG } from './auto-review-fix/index.ts'
|
|
6
|
+
import * as restart from './restart/index.ts'
|
|
7
|
+
import { DEFAULT_RESTART_CONFIG } from './restart/index.ts'
|
|
8
|
+
import * as taskGuard from './task-guard/index.ts'
|
|
9
|
+
import { DEFAULT_TASK_GUARD_CONFIG } from './task-guard/index.ts'
|
|
10
|
+
import { DEFAULT_SCHEDULE_CONFIG } from './schedule.ts'
|
|
11
|
+
import { toPlain } from './volatile.ts'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Master entry Config. DSH composes a package's client half only when a Loader
|
|
15
|
+
* row names the exact package root (subpath rows resolve to no package), so the
|
|
16
|
+
* plugin ships ONE entry and mounts the components as sub-plugins. The
|
|
17
|
+
* Appearance fields stay top-level because the settings bridge addresses them
|
|
18
|
+
* by field name under this entry's namespace.
|
|
19
|
+
*/
|
|
20
|
+
export const Config = z.object({
|
|
21
|
+
enabled: z.boolean().default(DEFAULT_SCHEDULE_CONFIG.enabled).volatile(),
|
|
22
|
+
lightStart: z.string().pattern(/^([01]\d|2[0-3]):[0-5]\d$/).default(DEFAULT_SCHEDULE_CONFIG.lightStart).volatile(),
|
|
23
|
+
lightEnd: z.string().pattern(/^([01]\d|2[0-3]):[0-5]\d$/).default(DEFAULT_SCHEDULE_CONFIG.lightEnd).volatile(),
|
|
24
|
+
autoReviewFix: autoReviewFix.Config,
|
|
25
|
+
taskGuard: taskGuard.Config,
|
|
26
|
+
restart: restart.Config,
|
|
27
|
+
}).default({
|
|
28
|
+
enabled: DEFAULT_SCHEDULE_CONFIG.enabled,
|
|
29
|
+
lightStart: DEFAULT_SCHEDULE_CONFIG.lightStart,
|
|
30
|
+
lightEnd: DEFAULT_SCHEDULE_CONFIG.lightEnd,
|
|
31
|
+
autoReviewFix: DEFAULT_AUTO_REVIEW_CONFIG,
|
|
32
|
+
taskGuard: DEFAULT_TASK_GUARD_CONFIG,
|
|
33
|
+
restart: DEFAULT_RESTART_CONFIG,
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
export interface MasterConfig {
|
|
37
|
+
enabled?: boolean
|
|
38
|
+
lightStart?: string
|
|
39
|
+
lightEnd?: string
|
|
40
|
+
autoReviewFix?: unknown
|
|
41
|
+
taskGuard?: unknown
|
|
42
|
+
restart?: unknown
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Mount one component without letting a missing service fail the master entry. */
|
|
46
|
+
function mount(ctx: Context, component: unknown, config: unknown): void {
|
|
47
|
+
try {
|
|
48
|
+
(ctx.plugin as unknown as (plugin: unknown, config?: unknown) => unknown).call(ctx, component, config)
|
|
49
|
+
} catch (error) {
|
|
50
|
+
const logger = (ctx as unknown as { logger?: { warn?: (value: unknown) => void } }).logger
|
|
51
|
+
logger?.warn?.(new Error('mcviseron: cannot mount a component', { cause: error }))
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Install every component as a sub-plugin. Each child keeps its own `inject`
|
|
57
|
+
* list, so a missing service only holds that component back.
|
|
58
|
+
* @param ctx - the profile entry context.
|
|
59
|
+
* @param rawConfig - the resolved entry Config (volatile refs are unwrapped).
|
|
60
|
+
*/
|
|
61
|
+
export function apply(ctx: Context, rawConfig?: MasterConfig): void {
|
|
62
|
+
const config = (toPlain(rawConfig) ?? {}) as MasterConfig
|
|
63
|
+
mount(ctx, appearance, {
|
|
64
|
+
enabled: config.enabled ?? DEFAULT_SCHEDULE_CONFIG.enabled,
|
|
65
|
+
lightStart: config.lightStart ?? DEFAULT_SCHEDULE_CONFIG.lightStart,
|
|
66
|
+
lightEnd: config.lightEnd ?? DEFAULT_SCHEDULE_CONFIG.lightEnd,
|
|
67
|
+
})
|
|
68
|
+
mount(ctx, autoReviewFix, toPlain(config.autoReviewFix) ?? DEFAULT_AUTO_REVIEW_CONFIG)
|
|
69
|
+
mount(ctx, taskGuard, toPlain(config.taskGuard) ?? DEFAULT_TASK_GUARD_CONFIG)
|
|
70
|
+
mount(ctx, restart, toPlain(config.restart) ?? DEFAULT_RESTART_CONFIG)
|
|
71
|
+
}
|
package/src/loopback.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { IncomingMessage } from 'node:http'
|
|
2
|
+
|
|
3
|
+
function isIPv4Loopback(value: string): boolean {
|
|
4
|
+
const parts = value.split('.')
|
|
5
|
+
return parts.length === 4
|
|
6
|
+
&& parts[0] === '127'
|
|
7
|
+
&& parts.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255)
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function isLoopbackAddress(address: string | undefined): boolean {
|
|
11
|
+
if (address === undefined) return false
|
|
12
|
+
const normalized = address.toLowerCase()
|
|
13
|
+
if (normalized === '::1') return true
|
|
14
|
+
if (normalized.startsWith('::ffff:')) return isIPv4Loopback(normalized.slice('::ffff:'.length))
|
|
15
|
+
return isIPv4Loopback(normalized)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function isLoopbackHostname(hostname: string): boolean {
|
|
19
|
+
if (hostname === 'localhost' || hostname === '[::1]') return true
|
|
20
|
+
return isIPv4Loopback(hostname)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Loopback trust fence: a loopback socket address AND a loopback Host header.
|
|
25
|
+
* X-Forwarded-For is never trusted. When an Origin header is present it must
|
|
26
|
+
* match the Host authority, which is what the browser sends on same-origin
|
|
27
|
+
* POSTs from the settings row.
|
|
28
|
+
*/
|
|
29
|
+
export function isLoopbackRequest(request: IncomingMessage): boolean {
|
|
30
|
+
if (!isLoopbackAddress(request.socket.remoteAddress)) return false
|
|
31
|
+
const host = request.headers.host
|
|
32
|
+
if (typeof host !== 'string') return false
|
|
33
|
+
let hostUrl: URL
|
|
34
|
+
try {
|
|
35
|
+
hostUrl = new URL('http://' + host)
|
|
36
|
+
} catch {
|
|
37
|
+
return false
|
|
38
|
+
}
|
|
39
|
+
if (!isLoopbackHostname(hostUrl.hostname)) return false
|
|
40
|
+
if (request.headers['sec-fetch-site'] === 'cross-site') return false
|
|
41
|
+
const origin = request.headers.origin
|
|
42
|
+
if (origin === undefined) return true
|
|
43
|
+
try {
|
|
44
|
+
return new URL(origin).host === hostUrl.host
|
|
45
|
+
} catch {
|
|
46
|
+
return false
|
|
47
|
+
}
|
|
48
|
+
}
|
package/src/namespace.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Settings namespace of the master entry. On DSH >= 0.2 a plugin's settings
|
|
3
|
+
* namespace IS its profile-entry id, so this constant must stay in sync with
|
|
4
|
+
* the single `mcviseron` entry in `cordis.patch.yml`. Appearance fields live
|
|
5
|
+
* at the top level of that entry's Config.
|
|
6
|
+
*/
|
|
7
|
+
export const MCVISERON_SETTINGS_NAMESPACE = 'mcviseron'
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process'
|
|
2
|
+
import { appendFileSync, existsSync } from 'node:fs'
|
|
3
|
+
import { tmpdir } from 'node:os'
|
|
4
|
+
import { basename, dirname, join, resolve } from 'node:path'
|
|
5
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
6
|
+
import type { ServerResponse } from 'node:http'
|
|
7
|
+
import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'
|
|
8
|
+
import z from '@deepseek-ai/schemastery'
|
|
9
|
+
import { isLoopbackRequest } from '../loopback.ts'
|
|
10
|
+
import { toPlain } from '../volatile.ts'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Restart component.
|
|
14
|
+
*
|
|
15
|
+
* DSH's own tray menu is built inside the Electron main process, so a plugin
|
|
16
|
+
* running in the Host child process cannot add a tray item. This component
|
|
17
|
+
* provides the closest supported equivalent: a Settings row that restarts the
|
|
18
|
+
* desktop application, implemented with a detached helper that closes the
|
|
19
|
+
* Electron main process (the Host then shuts down gracefully over its IPC
|
|
20
|
+
* disconnect) and starts the application again.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
export const DEFAULT_RESTART_CONFIG = { enabled: true, appPath: '' } as const
|
|
24
|
+
|
|
25
|
+
export const Config = z.object({
|
|
26
|
+
enabled: z.boolean().default(DEFAULT_RESTART_CONFIG.enabled).volatile(),
|
|
27
|
+
/** Optional explicit application executable; empty derives it from the Host process. */
|
|
28
|
+
appPath: z.string().default(DEFAULT_RESTART_CONFIG.appPath).volatile(),
|
|
29
|
+
}).default(DEFAULT_RESTART_CONFIG)
|
|
30
|
+
|
|
31
|
+
export interface RestartConfig {
|
|
32
|
+
enabled?: boolean
|
|
33
|
+
appPath?: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The desktop executable and the two PIDs the helper must wait for. */
|
|
37
|
+
export interface RestartTarget {
|
|
38
|
+
mainPid: number
|
|
39
|
+
hostPid: number
|
|
40
|
+
exePath: string
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Loopback endpoints owned by the restart component. */
|
|
44
|
+
export const RESTART_API = {
|
|
45
|
+
status: '/api/dsh-mcviseron/restart/status',
|
|
46
|
+
execute: '/api/dsh-mcviseron/restart/execute',
|
|
47
|
+
} as const
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Resolve the desktop application from the Host process.
|
|
51
|
+
*
|
|
52
|
+
* The desktop Host is a child of the Electron main process and is launched
|
|
53
|
+
* through the application executable in Node mode, so `process.execPath` is the
|
|
54
|
+
* app itself. A plain `dsh web` Host runs under node.exe and is not restartable.
|
|
55
|
+
*
|
|
56
|
+
* @param execPath - the Host's `process.execPath`.
|
|
57
|
+
* @param parentPid - the Host's `process.ppid`.
|
|
58
|
+
* @param exists - file-existence probe (injectable for tests).
|
|
59
|
+
* @param override - configured application path.
|
|
60
|
+
* @param argv - the Host's process.argv.
|
|
61
|
+
* @param platform - host platform (injectable for tests).
|
|
62
|
+
* @returns the restart target, or undefined outside the Windows desktop app.
|
|
63
|
+
*/
|
|
64
|
+
export function resolveRestartTarget(
|
|
65
|
+
execPath: string,
|
|
66
|
+
parentPid: number,
|
|
67
|
+
exists: (path: string) => boolean,
|
|
68
|
+
override = '',
|
|
69
|
+
argv: readonly string[] = [],
|
|
70
|
+
platform: NodeJS.Platform = process.platform,
|
|
71
|
+
): RestartTarget | undefined {
|
|
72
|
+
if (platform !== 'win32') return undefined
|
|
73
|
+
if (!Number.isSafeInteger(parentPid) || parentPid <= 0) return undefined
|
|
74
|
+
const configured = typeof override === 'string' ? override.trim() : ''
|
|
75
|
+
const candidate = configured !== '' ? configured : deriveDesktopAppPath(execPath, argv, exists)
|
|
76
|
+
if (candidate === '' || !exists(candidate)) return undefined
|
|
77
|
+
const name = basename(candidate).toLowerCase()
|
|
78
|
+
if (name === 'node' || name === 'node.exe') return undefined
|
|
79
|
+
return { mainPid: parentPid, hostPid: process.pid, exePath: candidate }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Derive the desktop application executable when the Host itself runs under a
|
|
84
|
+
* plain node.exe: first `argv[0]`, then the application root recovered from the
|
|
85
|
+
* runtime directory (`<app>\resources\app.asar\dsh`).
|
|
86
|
+
*
|
|
87
|
+
* @param execPath - the Host's `process.execPath`.
|
|
88
|
+
* @param argv - the Host's `process.argv`.
|
|
89
|
+
* @param exists - file-existence probe.
|
|
90
|
+
* @returns the application executable, or the original execPath.
|
|
91
|
+
*/
|
|
92
|
+
export function deriveDesktopAppPath(
|
|
93
|
+
execPath: string,
|
|
94
|
+
argv: readonly string[],
|
|
95
|
+
exists: (path: string) => boolean,
|
|
96
|
+
): string {
|
|
97
|
+
const isNode = (value: string): boolean => /^node(\.exe)?$/i.test(basename(value))
|
|
98
|
+
if (!isNode(execPath)) return execPath
|
|
99
|
+
const argv0 = argv[0] ?? ''
|
|
100
|
+
if (argv0 !== '' && argv0 !== execPath && !isNode(argv0) && exists(argv0)) return argv0
|
|
101
|
+
const runtimeDir = argv[2] ?? ''
|
|
102
|
+
if (runtimeDir === '') return execPath
|
|
103
|
+
const candidate = join(resolve(runtimeDir, '../../..'), 'DeepSeek Harness.exe')
|
|
104
|
+
return exists(candidate) ? candidate : execPath
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** One-time task that starts the desktop application directly. */
|
|
108
|
+
const RESTART_TASK_NAME = 'DSH-MCviseron-Restart'
|
|
109
|
+
const RESTART_DELAY_SECONDS = 6
|
|
110
|
+
|
|
111
|
+
/** Shared diagnostic log written by the Host around the scheduled restart. */
|
|
112
|
+
function restartLogPath(): string {
|
|
113
|
+
return join(tmpdir(), 'dsh-mcviseron-restart.log')
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Build the Task Scheduler registration script. The task ACTION is the desktop
|
|
118
|
+
* executable itself, so the relaunch is not a console/terminal child: the
|
|
119
|
+
* hidden PowerShell only registers the task and exits. Task Scheduler then
|
|
120
|
+
* starts the application directly in the interactive user session.
|
|
121
|
+
* @param target - PIDs and executable captured before shutdown.
|
|
122
|
+
* @param taskName - one-time task name, overwritten on every restart.
|
|
123
|
+
* @param delaySeconds - how long the task waits before starting the application.
|
|
124
|
+
* @returns PowerShell registration script text.
|
|
125
|
+
*/
|
|
126
|
+
export function makeTaskScript(target: RestartTarget, taskName: string, delaySeconds: number): string {
|
|
127
|
+
const quote = (value: string): string => "'" + value.replace(/'/g, "''") + "'"
|
|
128
|
+
return [
|
|
129
|
+
'$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name',
|
|
130
|
+
`$action = New-ScheduledTaskAction -Execute ${quote(target.exePath)} -WorkingDirectory ${quote(dirname(target.exePath))}`,
|
|
131
|
+
`$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddSeconds(${delaySeconds})`,
|
|
132
|
+
'$principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited',
|
|
133
|
+
`Register-ScheduledTask -TaskName ${quote(taskName)} -Action $action -Trigger $trigger -Principal $principal -Force | Out-Null`,
|
|
134
|
+
'',
|
|
135
|
+
].join('\n')
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Register the direct-launch task, then close the Electron main process. */
|
|
139
|
+
function launchHelper(target: RestartTarget): void {
|
|
140
|
+
const logFile = restartLogPath()
|
|
141
|
+
try {
|
|
142
|
+
execFileSync('powershell.exe', [
|
|
143
|
+
'-NoProfile',
|
|
144
|
+
'-NonInteractive',
|
|
145
|
+
'-WindowStyle',
|
|
146
|
+
'Hidden',
|
|
147
|
+
'-Command',
|
|
148
|
+
makeTaskScript(target, RESTART_TASK_NAME, RESTART_DELAY_SECONDS),
|
|
149
|
+
], { windowsHide: true, timeout: 20_000, encoding: 'utf8' })
|
|
150
|
+
appendFileSync(logFile, `${new Date().toISOString()} host: scheduled ${target.exePath} in ${RESTART_DELAY_SECONDS}s\n`, 'utf8')
|
|
151
|
+
} catch (error) {
|
|
152
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
153
|
+
appendFileSync(logFile, `${new Date().toISOString()} host: task registration failed: ${message}\n`, 'utf8')
|
|
154
|
+
throw new Error('cannot schedule the restart task: ' + message, { cause: error })
|
|
155
|
+
}
|
|
156
|
+
setTimeout(() => {
|
|
157
|
+
try {
|
|
158
|
+
process.kill(target.mainPid)
|
|
159
|
+
appendFileSync(logFile, `${new Date().toISOString()} host: kill sent to ${target.mainPid}\n`, 'utf8')
|
|
160
|
+
} catch (error) {
|
|
161
|
+
appendFileSync(logFile, `${new Date().toISOString()} host: kill failed: ${error instanceof Error ? error.message : String(error)}\n`, 'utf8')
|
|
162
|
+
}
|
|
163
|
+
}, 700)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function json(res: ServerResponse, status: number, body: unknown): void {
|
|
167
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
168
|
+
res.end(JSON.stringify(body))
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function readJsonBody(req: Parameters<WebRoute['handler']>[0]): Promise<unknown> {
|
|
172
|
+
const chunks: Buffer[] = []
|
|
173
|
+
let size = 0
|
|
174
|
+
for await (const chunk of req) {
|
|
175
|
+
const buffer = chunk as Buffer
|
|
176
|
+
size += buffer.length
|
|
177
|
+
if (size > 8 * 1024) return undefined
|
|
178
|
+
chunks.push(buffer)
|
|
179
|
+
}
|
|
180
|
+
try {
|
|
181
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
182
|
+
} catch {
|
|
183
|
+
return undefined
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Injectable faces so route tests never spawn a real restart. */
|
|
188
|
+
export interface RestartRouteDeps {
|
|
189
|
+
target: () => RestartTarget | undefined
|
|
190
|
+
launch: (target: RestartTarget) => void
|
|
191
|
+
now?: () => number
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Build the status and execute routes.
|
|
196
|
+
* @param deps - target resolution, launcher, and clock.
|
|
197
|
+
* @returns routes for the Host web server.
|
|
198
|
+
*/
|
|
199
|
+
export function makeRestartRoutes(deps: RestartRouteDeps): WebRoute[] {
|
|
200
|
+
let lastLaunch = Number.NEGATIVE_INFINITY
|
|
201
|
+
const now = deps.now ?? (() => Date.now())
|
|
202
|
+
|
|
203
|
+
const status: WebRoute = {
|
|
204
|
+
kind: 'exact',
|
|
205
|
+
path: RESTART_API.status,
|
|
206
|
+
handler: async (req, res): Promise<void> => {
|
|
207
|
+
try {
|
|
208
|
+
if (req.method !== 'GET' && req.method !== 'POST') return json(res, 405, { ok: false, error: 'method-not-allowed' })
|
|
209
|
+
if (!isLoopbackRequest(req)) return json(res, 403, { ok: false, error: 'forbidden' })
|
|
210
|
+
const target = deps.target()
|
|
211
|
+
json(res, 200, target === undefined
|
|
212
|
+
? { ok: true, available: false, reason: 'desktop-app-unavailable' }
|
|
213
|
+
: { ok: true, available: true, appPath: target.exePath, mainPid: target.mainPid })
|
|
214
|
+
} catch (error) {
|
|
215
|
+
json(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) })
|
|
216
|
+
}
|
|
217
|
+
},
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const execute: WebRoute = {
|
|
221
|
+
kind: 'exact',
|
|
222
|
+
path: RESTART_API.execute,
|
|
223
|
+
handler: async (req, res): Promise<void> => {
|
|
224
|
+
try {
|
|
225
|
+
if (req.method !== 'POST') return json(res, 405, { ok: false, error: 'method-not-allowed' })
|
|
226
|
+
if (!isLoopbackRequest(req)) return json(res, 403, { ok: false, error: 'forbidden' })
|
|
227
|
+
const body = await readJsonBody(req)
|
|
228
|
+
if (body === undefined || typeof body !== 'object' || body === null || (body as { confirm?: unknown }).confirm !== true) {
|
|
229
|
+
return json(res, 400, { ok: false, error: 'confirmation-required' })
|
|
230
|
+
}
|
|
231
|
+
const latest = now()
|
|
232
|
+
if (latest - lastLaunch < 5000) return json(res, 429, { ok: false, error: 'restart-already-scheduled' })
|
|
233
|
+
const target = deps.target()
|
|
234
|
+
if (target === undefined) return json(res, 409, { ok: false, error: 'desktop-app-unavailable' })
|
|
235
|
+
deps.launch(target)
|
|
236
|
+
lastLaunch = latest
|
|
237
|
+
json(res, 200, { ok: true, restarting: true, appPath: target.exePath })
|
|
238
|
+
} catch (error) {
|
|
239
|
+
json(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) })
|
|
240
|
+
}
|
|
241
|
+
},
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
return [status, execute]
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export const inject = ['webServer']
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Register the restart routes.
|
|
251
|
+
* @param ctx - the component's plugin context.
|
|
252
|
+
* @param config - the entry Config.
|
|
253
|
+
*/
|
|
254
|
+
export function apply(ctx: Context, config?: RestartConfig): void {
|
|
255
|
+
const plain = (toPlain(config) ?? {}) as RestartConfig
|
|
256
|
+
if (plain.enabled === false) return
|
|
257
|
+
const appPath = typeof plain.appPath === 'string' ? plain.appPath : ''
|
|
258
|
+
const routes = makeRestartRoutes({
|
|
259
|
+
target: () => resolveRestartTarget(process.execPath, process.ppid, existsSync, appPath, process.argv),
|
|
260
|
+
launch: launchHelper,
|
|
261
|
+
})
|
|
262
|
+
ctx.effect(() => {
|
|
263
|
+
const disposers = routes.map(route => ctx.webServer.register(route))
|
|
264
|
+
return () => {
|
|
265
|
+
for (const dispose of disposers) dispose()
|
|
266
|
+
}
|
|
267
|
+
}, 'mcviseron-restart: restart routes')
|
|
268
|
+
}
|
package/src/routes.ts
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import type { ServerResponse } from 'node:http'
|
|
2
|
+
import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'
|
|
3
|
+
import { SettingsConflictError, type SettingsPathOp } from '@deepseek-ai/dsh-settings'
|
|
4
|
+
import { MCVISERON_API } from './api.ts'
|
|
5
|
+
import { MCVISERON_SETTINGS_NAMESPACE } from './namespace.ts'
|
|
6
|
+
import { isLoopbackRequest } from './loopback.ts'
|
|
7
|
+
import { normalizeScheduleConfig, parseTimeOfDay } from './schedule.ts'
|
|
8
|
+
import { toPlain } from './volatile.ts'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* One namespace view as the settings service serializes it. Structural on
|
|
12
|
+
* purpose: DSH 0.2's `SettingsForms` returns these fields, and keeping the
|
|
13
|
+
* face local means the bridge is checked against the live object instead of
|
|
14
|
+
* a package copy that may differ from the running Host.
|
|
15
|
+
*/
|
|
16
|
+
export interface SettingsBridgeView {
|
|
17
|
+
ns: unknown
|
|
18
|
+
value?: unknown
|
|
19
|
+
revision: number
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The provider face this bridge uses; only the two documented calls. */
|
|
23
|
+
export interface SettingsBridge {
|
|
24
|
+
readonly writable?: boolean
|
|
25
|
+
describe: (options?: { redactSecrets?: boolean }) => SettingsBridgeView[]
|
|
26
|
+
mutate: (ns: string, ops: readonly SettingsPathOp[], expectedRevision?: number) => Promise<void>
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const MAX_BODY_BYTES = 8 * 1024
|
|
30
|
+
|
|
31
|
+
/** One writable config path and its runtime validation rule. */
|
|
32
|
+
type FieldRule =
|
|
33
|
+
| { type: 'boolean' }
|
|
34
|
+
| { type: 'time' }
|
|
35
|
+
| { type: 'string' }
|
|
36
|
+
| { type: 'number'; min: number; max: number }
|
|
37
|
+
| { type: 'enum'; values: readonly string[] }
|
|
38
|
+
| { type: 'strings' }
|
|
39
|
+
|
|
40
|
+
/** Paths the settings bridge may write: appearance fields plus component groups. */
|
|
41
|
+
const FIELD_RULES: Record<string, FieldRule> = {
|
|
42
|
+
enabled: { type: 'boolean' },
|
|
43
|
+
lightStart: { type: 'time' },
|
|
44
|
+
lightEnd: { type: 'time' },
|
|
45
|
+
'autoReviewFix.keepPresetGuard': { type: 'boolean' },
|
|
46
|
+
'autoReviewFix.translateApprovalReason': { type: 'boolean' },
|
|
47
|
+
'autoReviewFix.translateTimeoutMs': { type: 'number', min: 500, max: 60000 },
|
|
48
|
+
'autoReviewFix.translateMaxChars': { type: 'number', min: 100, max: 20000 },
|
|
49
|
+
'autoReviewFix.translateProvider': { type: 'string' },
|
|
50
|
+
'autoReviewFix.translateModel': { type: 'string' },
|
|
51
|
+
'taskGuard.enabled': { type: 'boolean' },
|
|
52
|
+
'taskGuard.locale': { type: 'enum', values: ['zh', 'en'] },
|
|
53
|
+
'taskGuard.staleAfterCalls': { type: 'number', min: 1, max: 1000 },
|
|
54
|
+
'taskGuard.repeatEveryCalls': { type: 'number', min: 0, max: 1000 },
|
|
55
|
+
'taskGuard.blockAfterCalls': { type: 'number', min: 0, max: 10000 },
|
|
56
|
+
'taskGuard.rejectMissingActive': { type: 'boolean' },
|
|
57
|
+
'taskGuard.sourceKind': { type: 'enum', values: ['auto', 'v3', 'v4'] },
|
|
58
|
+
'taskGuard.maxListItems': { type: 'number', min: 1, max: 100 },
|
|
59
|
+
'taskGuard.detectStepIntent': { type: 'boolean' },
|
|
60
|
+
'taskGuard.translateTodoContent': { type: 'boolean' },
|
|
61
|
+
'taskGuard.todoTranslationTimeoutMs': { type: 'number', min: 500, max: 15000 },
|
|
62
|
+
'taskGuard.include': { type: 'strings' },
|
|
63
|
+
'taskGuard.exclude': { type: 'strings' },
|
|
64
|
+
'restart.enabled': { type: 'boolean' },
|
|
65
|
+
'restart.appPath': { type: 'string' },
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function ruleFor(path: unknown): FieldRule | undefined {
|
|
69
|
+
if (!Array.isArray(path) || path.length === 0 || path.length > 2) return undefined
|
|
70
|
+
if (!path.every(part => typeof part === 'string')) return undefined
|
|
71
|
+
return FIELD_RULES[path.join('.')]
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function validFieldValue(rule: FieldRule, value: unknown): boolean {
|
|
75
|
+
switch (rule.type) {
|
|
76
|
+
case 'boolean': return typeof value === 'boolean'
|
|
77
|
+
case 'time': return typeof value === 'string' && parseTimeOfDay(value) !== undefined
|
|
78
|
+
case 'string': return typeof value === 'string'
|
|
79
|
+
case 'number':
|
|
80
|
+
return typeof value === 'number' && Number.isFinite(value) && Number.isInteger(value) && value >= rule.min && value <= rule.max
|
|
81
|
+
case 'enum': return typeof value === 'string' && rule.values.includes(value)
|
|
82
|
+
case 'strings': return Array.isArray(value) && value.every(item => typeof item === 'string')
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
87
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function json(res: ServerResponse, status: number, body: unknown): void {
|
|
91
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' })
|
|
92
|
+
res.end(JSON.stringify(body))
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function readJsonBody(req: Parameters<WebRoute['handler']>[0]): Promise<unknown> {
|
|
96
|
+
const chunks: Buffer[] = []
|
|
97
|
+
let size = 0
|
|
98
|
+
for await (const chunk of req) {
|
|
99
|
+
const buffer = chunk as Buffer
|
|
100
|
+
size += buffer.length
|
|
101
|
+
if (size > MAX_BODY_BYTES) return undefined
|
|
102
|
+
chunks.push(buffer)
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
106
|
+
} catch {
|
|
107
|
+
return undefined
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Whether a settings write was refused as stale. Class check plus the stable
|
|
113
|
+
* machine code, because the throwing Host may run a different copy of
|
|
114
|
+
* `@deepseek-ai/dsh-settings` than this plugin's own types.
|
|
115
|
+
*/
|
|
116
|
+
function isSettingsConflict(error: unknown): boolean {
|
|
117
|
+
if (error instanceof SettingsConflictError) return true
|
|
118
|
+
return (error as { code?: unknown } | null)?.code === 'SETTINGS_CONFLICT'
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Unwrap a settings value that may be a schemastery live reference. DSH 0.2
|
|
123
|
+
* hands `.volatile()` fields through as frozen references exposing `get()`;
|
|
124
|
+
* plain values pass through untouched.
|
|
125
|
+
*/
|
|
126
|
+
function unwrapValue(value: unknown): unknown {
|
|
127
|
+
if (value === null || value === undefined) return value
|
|
128
|
+
if (typeof value === 'object' && typeof (value as { get?: unknown }).get === 'function') {
|
|
129
|
+
try {
|
|
130
|
+
return (value as { get: () => unknown }).get()
|
|
131
|
+
} catch {
|
|
132
|
+
return undefined
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return value
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** The browser-facing view: appearance fields plus every component config group. */
|
|
139
|
+
function toPluginView(descriptor: SettingsBridgeView): Record<string, unknown> {
|
|
140
|
+
const plain = toPlain(unwrapValue(descriptor.value))
|
|
141
|
+
const record = isRecord(plain) ? plain : {}
|
|
142
|
+
return {
|
|
143
|
+
ns: String(descriptor.ns),
|
|
144
|
+
value: {
|
|
145
|
+
...normalizeScheduleConfig(plain),
|
|
146
|
+
autoReviewFix: isRecord(record.autoReviewFix) ? record.autoReviewFix : {},
|
|
147
|
+
taskGuard: isRecord(record.taskGuard) ? record.taskGuard : {},
|
|
148
|
+
restart: isRecord(record.restart) ? record.restart : {},
|
|
149
|
+
},
|
|
150
|
+
revision: descriptor.revision,
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function findView(settings: SettingsBridge): SettingsBridgeView | undefined {
|
|
155
|
+
return settings.describe({ redactSecrets: true }).find(descriptor => String(descriptor.ns) === MCVISERON_SETTINGS_NAMESPACE)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Build the two loopback routes the Appearance row uses to read and write its
|
|
160
|
+
* namespace. DSH 0.2's settings apiproxy only serves official namespaces to
|
|
161
|
+
* the browser, so this plugin owns a narrow bridge (same trust fence as the
|
|
162
|
+
* Host web server: loopback socket, loopback Host header, same-origin POST).
|
|
163
|
+
* @param settings - the Host settings service face.
|
|
164
|
+
* @returns routes to register on the Host web server.
|
|
165
|
+
*/
|
|
166
|
+
export function makeSettingsRoutes(settings: SettingsBridge): WebRoute[] {
|
|
167
|
+
const describe: WebRoute = {
|
|
168
|
+
kind: 'exact',
|
|
169
|
+
path: MCVISERON_API.describe,
|
|
170
|
+
handler: async (req, res): Promise<void> => {
|
|
171
|
+
if (req.method !== 'POST') return json(res, 405, { ok: false, error: 'method-not-allowed' })
|
|
172
|
+
if (!isLoopbackRequest(req)) return json(res, 403, { ok: false, error: 'forbidden' })
|
|
173
|
+
const descriptor = findView(settings)
|
|
174
|
+
json(res, 200, {
|
|
175
|
+
ok: true,
|
|
176
|
+
value: {
|
|
177
|
+
namespaces: descriptor === undefined ? [] : [toPluginView(descriptor)],
|
|
178
|
+
writable: settings.writable !== false,
|
|
179
|
+
},
|
|
180
|
+
})
|
|
181
|
+
},
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const mutate: WebRoute = {
|
|
185
|
+
kind: 'exact',
|
|
186
|
+
path: MCVISERON_API.mutate,
|
|
187
|
+
handler: async (req, res): Promise<void> => {
|
|
188
|
+
if (req.method !== 'POST') return json(res, 405, { ok: false, error: 'method-not-allowed' })
|
|
189
|
+
if (!isLoopbackRequest(req)) return json(res, 403, { ok: false, error: 'forbidden' })
|
|
190
|
+
const body = await readJsonBody(req)
|
|
191
|
+
if (body === undefined || typeof body !== 'object' || body === null) {
|
|
192
|
+
return json(res, 400, { ok: false, code: 'settings-rejected', message: 'unreadable JSON body' })
|
|
193
|
+
}
|
|
194
|
+
const record = body as { ns?: unknown; ops?: unknown; expectedRevision?: unknown }
|
|
195
|
+
if (record.ns !== MCVISERON_SETTINGS_NAMESPACE || !Array.isArray(record.ops)) {
|
|
196
|
+
return json(res, 400, { ok: false, code: 'settings-rejected', message: 'malformed settings request' })
|
|
197
|
+
}
|
|
198
|
+
const ops = record.ops as SettingsPathOp[]
|
|
199
|
+
const valid = ops.every((op) => {
|
|
200
|
+
if (op.op !== 'set' && op.op !== 'unset') return false
|
|
201
|
+
const rule = ruleFor(op.path)
|
|
202
|
+
if (rule === undefined) return false
|
|
203
|
+
if (op.op === 'unset') return true
|
|
204
|
+
return validFieldValue(rule, op.value)
|
|
205
|
+
})
|
|
206
|
+
if (!valid) {
|
|
207
|
+
return json(res, 400, { ok: false, code: 'settings-rejected', message: 'malformed settings operation' })
|
|
208
|
+
}
|
|
209
|
+
const expectedRevision = typeof record.expectedRevision === 'number' ? record.expectedRevision : undefined
|
|
210
|
+
try {
|
|
211
|
+
await settings.mutate(MCVISERON_SETTINGS_NAMESPACE, ops, expectedRevision)
|
|
212
|
+
} catch (error) {
|
|
213
|
+
if (isSettingsConflict(error)) {
|
|
214
|
+
return json(res, 200, { ok: false, code: 'settings-conflict', message: error instanceof Error ? error.message : 'settings conflict' })
|
|
215
|
+
}
|
|
216
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
217
|
+
return json(res, 200, { ok: false, code: 'settings-rejected', message })
|
|
218
|
+
}
|
|
219
|
+
const descriptor = findView(settings)
|
|
220
|
+
if (descriptor === undefined) {
|
|
221
|
+
return json(res, 200, { ok: false, code: 'internal', message: 'mcviseron settings namespace was disposed' })
|
|
222
|
+
}
|
|
223
|
+
json(res, 200, { ok: true, value: toPluginView(descriptor) })
|
|
224
|
+
},
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
return [describe, mutate]
|
|
228
|
+
}
|