@foggy-projects/deepseek-harness-plugin 0.4.2-rc.3 → 0.4.4-rc.1

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.
Files changed (52) hide show
  1. package/README.md +222 -173
  2. package/THIRD-PARTY-RUNTIME-NOTICES.md +16 -16
  3. package/cordis.patch.yml +6 -6
  4. package/docs/COMMUNITY-MARKETPLACES.md +64 -64
  5. package/docs/PUBLIC-BETA-READINESS.md +109 -109
  6. package/docs/RELEASE-CANDIDATE-0.4.0-RC.2.md +38 -38
  7. package/docs/RELEASE-CANDIDATE-0.4.0-RC.3.md +18 -18
  8. package/docs/RELEASE-CANDIDATE-0.4.1-DSH-0.1.5-RC.1.md +60 -60
  9. package/docs/RELEASE-CANDIDATE-0.4.2-DSH-0.1.7-RC.1.md +62 -62
  10. package/docs/RELEASE-CANDIDATE-0.4.2-DSH-0.1.7-RC.2.md +50 -50
  11. package/docs/RELEASE-CANDIDATE-0.4.2-DSH-0.1.7-RC.3.md +34 -34
  12. package/docs/RELEASE-CANDIDATE-0.4.2-DSH-0.1.7-RC.4.md +32 -0
  13. package/docs/RELEASE-CANDIDATE-0.4.2-DSH-0.1.7-RC.5.md +27 -0
  14. package/docs/RELEASE-CANDIDATE-0.4.3-DSH-0.2.0-RC.1.md +96 -0
  15. package/docs/RELEASE-CANDIDATE-0.4.4-DSH-0.2.1-RC.1.md +135 -0
  16. package/docs/WINDOWS-BETA-ACCEPTANCE.md +113 -113
  17. package/experience/linux/README.md +53 -53
  18. package/experience/linux/prepare.sh +2 -2
  19. package/lib/atomic-json.js +41 -41
  20. package/lib/client.js +1222 -906
  21. package/lib/component-manager.js +164 -0
  22. package/lib/component-releases.js +363 -0
  23. package/lib/diagnostics.js +86 -86
  24. package/lib/index.js +764 -698
  25. package/lib/operation-lock.js +139 -0
  26. package/lib/python-runtime.js +339 -339
  27. package/lib/query-tool.js +134 -104
  28. package/lib/remote-descriptor.js +74 -59
  29. package/lib/remote.js +8 -8
  30. package/lib/runtime-settings.js +89 -89
  31. package/lib/skill-provider.js +116 -116
  32. package/lib/typert.js +9 -9
  33. package/lib/version.js +20 -20
  34. package/lib/viewer-preview.js +44 -27
  35. package/package.json +25 -15
  36. package/skills/foggy-deepseek-onboarding/SKILL.md +149 -143
  37. package/skills/foggy-deepseek-onboarding/assets/connection.schema.json +48 -48
  38. package/skills/foggy-deepseek-onboarding/assets/datasource.example.json +14 -14
  39. package/skills/foggy-deepseek-onboarding/assets/env.example +14 -14
  40. package/skills/foggy-deepseek-onboarding/assets/onboarding-state.schema.json +71 -71
  41. package/skills/foggy-deepseek-onboarding/assets/semantic-plan.example.json +8 -8
  42. package/skills/foggy-deepseek-onboarding/assets/semantic-plan.schema.json +21 -21
  43. package/skills/foggy-deepseek-onboarding/assets/versions.json +23 -23
  44. package/skills/foggy-deepseek-onboarding/references/onboarding-workflow.md +168 -168
  45. package/skills/foggy-deepseek-onboarding/scripts/doctor.ps1 +4 -4
  46. package/skills/foggy-deepseek-onboarding/scripts/install.ps1 +4 -4
  47. package/skills/foggy-deepseek-onboarding/scripts/invoke-onboarding.ps1 +32 -32
  48. package/skills/foggy-deepseek-onboarding/scripts/onboard.ps1 +4 -4
  49. package/skills/foggy-deepseek-onboarding/scripts/onboarding.py +3721 -3681
  50. package/skills/foggy-deepseek-onboarding/scripts/runtime-start.ps1 +4 -4
  51. package/skills/foggy-deepseek-onboarding/scripts/runtime-stop.ps1 +4 -4
  52. package/skills/foggy-deepseek-onboarding/scripts/uninstall.ps1 +4 -4
package/lib/index.js CHANGED
@@ -1,698 +1,764 @@
1
- import { execFile } from 'node:child_process'
2
- import { access, mkdir, readFile, writeFile } from 'node:fs/promises'
3
- import { constants as fsConstants } from 'node:fs'
4
- import { dirname, join, delimiter } from 'node:path'
5
- import { fileURLToPath } from 'node:url'
6
- import { promisify } from 'node:util'
7
- import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
8
- import { createFoggySkillProvider } from './skill-provider.js'
9
- import { writeJsonAtomic } from './atomic-json.js'
10
- import { ensurePythonRuntime, probePythonRuntime } from './python-runtime.js'
11
- import { compatible, compatibleNode } from './version.js'
12
- import { enrichRuntimeStartFailure } from './diagnostics.js'
13
- import { createFoggyQueryTool, managedConnection } from './query-tool.js'
14
- import { createViewerPreview } from './viewer-preview.js'
15
- import {
16
- DEFAULT_RUNTIME_PORT,
17
- readRuntimeSettings,
18
- writeRuntimeSettings,
19
- } from './runtime-settings.js'
20
-
21
- const execFileAsync = promisify(execFile)
22
- const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)))
23
- const onboardingScript = join(packageRoot, 'skills', 'foggy-deepseek-onboarding', 'scripts', 'onboarding.py')
24
- const versionsFile = join(packageRoot, 'skills', 'foggy-deepseek-onboarding', 'assets', 'versions.json')
25
-
26
- function defaultRoots() {
27
- if (process.platform === 'win32') {
28
- const base = process.env.LOCALAPPDATA
29
- if (!base) throw new Error('LOCALAPPDATA is not set')
30
- return {
31
- installRoot: join(base, 'Foggy', 'DeepSeekHarness'),
32
- dataRoot: join(base, 'Foggy', 'DeepSeekHarnessData'),
33
- profileStore: process.env.FOGGY_RUNTIME_PROFILE_STORE || join(base, 'Foggy', 'DeepSeekHarnessData', 'cli-profiles'),
34
- }
35
- }
36
- const home = process.env.HOME
37
- if (!home) throw new Error('HOME is not set')
38
- const dataRoot = process.env.XDG_STATE_HOME
39
- ? join(process.env.XDG_STATE_HOME, 'foggy', 'deepseek-harness')
40
- : join(home, '.local', 'state', 'foggy', 'deepseek-harness')
41
- return {
42
- installRoot: process.env.XDG_DATA_HOME
43
- ? join(process.env.XDG_DATA_HOME, 'foggy', 'deepseek-harness')
44
- : join(home, '.local', 'share', 'foggy', 'deepseek-harness'),
45
- dataRoot,
46
- profileStore: process.env.FOGGY_RUNTIME_PROFILE_STORE || join(dataRoot, 'cli-profiles'),
47
- }
48
- }
49
-
50
- function componentReleaseState({ installed, installedVersion, targetVersion }) {
51
- const normalizedInstalled = installedVersion || null
52
- const normalizedTarget = targetVersion || null
53
- const updateAvailable = Boolean(installed && normalizedInstalled && normalizedTarget && normalizedInstalled !== normalizedTarget)
54
- return {
55
- installed: Boolean(installed && !updateAvailable),
56
- installedVersion: normalizedInstalled,
57
- targetVersion: normalizedTarget,
58
- updateAvailable,
59
- }
60
- }
61
-
62
- async function exists(path) {
63
- try {
64
- await access(path, fsConstants.F_OK)
65
- return true
66
- } catch {
67
- return false
68
- }
69
- }
70
-
71
- async function readJson(path) {
72
- return JSON.parse(await readFile(path, 'utf8'))
73
- }
74
-
75
- async function readOptionalJson(path) {
76
- try {
77
- return await readJson(path)
78
- } catch {
79
- return null
80
- }
81
- }
82
-
83
- async function runtimeRunningUpdateGuard() {
84
- const roots = defaultRoots()
85
- const runtime = await readOptionalJson(join(roots.dataRoot, 'runtime-state.json'))
86
- if (runtime && processRunning(Number(runtime.pid))) {
87
- return {
88
- success: false,
89
- accepted: false,
90
- error: {
91
- code: 'RUNTIME_RUNNING_UPDATE_REQUIRES_STOP',
92
- message: 'Stop Foggy Runtime before updating or repairing managed components.',
93
- },
94
- }
95
- }
96
- return null
97
- }
98
-
99
- async function commandVersion(command, args) {
100
- try {
101
- const { stdout, stderr } = await execFileAsync(command, args, {
102
- windowsHide: true,
103
- timeout: 15_000,
104
- maxBuffer: 256 * 1024,
105
- })
106
- return { available: true, output: `${stdout}\n${stderr}`.trim().split(/\r?\n/)[0] ?? '' }
107
- } catch (error) {
108
- return { available: false, output: '', error: error.code ?? 'COMMAND_FAILED' }
109
- }
110
- }
111
-
112
- function parseOutput(stdout, stderr) {
113
- const text = String(stdout ?? '').trim()
114
- if (!text) throw new Error(String(stderr ?? '').trim() || 'Foggy onboarding returned no JSON')
115
- try {
116
- return JSON.parse(text)
117
- } catch {
118
- throw new Error(`Foggy onboarding returned invalid JSON: ${text.slice(0, 240)}`)
119
- }
120
- }
121
-
122
- async function runOnboarding(args, timeout = 15 * 60_000, options = {}) {
123
- const roots = defaultRoots()
124
- const manifest = await readJson(versionsFile)
125
- const cacheDirs = (process.env.FOGGY_ASSET_CACHE_DIRS || '').split(delimiter).filter(Boolean)
126
- const python = options.ensurePython
127
- ? await ensurePythonRuntime({
128
- installRoot: roots.installRoot,
129
- manifest,
130
- cacheDirs,
131
- force: options.forcePython,
132
- onProgress: options.onPythonProgress,
133
- })
134
- : await probePythonRuntime({ installRoot: roots.installRoot, manifest })
135
- if (!python.available) {
136
- throw new Error('Foggy managed Python is unavailable; initialize or repair the Python component')
137
- }
138
- await options.flushPythonProgress?.()
139
- try {
140
- const { stdout, stderr } = await execFileAsync(python.path, [onboardingScript, ...args], {
141
- windowsHide: true,
142
- timeout,
143
- maxBuffer: 4 * 1024 * 1024,
144
- cwd: process.env.FOGGY_PROJECT_ROOT || process.cwd(),
145
- env: {
146
- ...process.env,
147
- FOGGY_ONBOARDING_PYTHON: python.path,
148
- FOGGY_ONBOARDING_PYTHON_SOURCE: python.source,
149
- },
150
- })
151
- return parseOutput(stdout, stderr)
152
- } catch (error) {
153
- if (error.stdout) return parseOutput(error.stdout, error.stderr)
154
- throw error
155
- }
156
- }
157
-
158
- async function assertSystemPrerequisites(kind) {
159
- if (kind === 'initialize' && !compatibleNode(process.versions.node)) {
160
- throw new Error(`This DeepSeek Harness plugin requires Node.js >=24.0.0; detected ${process.versions.node}`)
161
- }
162
- if (kind === 'initialize' || kind === 'runtime-start') {
163
- const java = compatible(await commandVersion(process.env.JAVA_EXE || 'java', ['-version']), '17.0')
164
- if (!java.available) throw new Error('Java 17+ is required; install a system JRE/JDK or set JAVA_EXE')
165
- }
166
- }
167
-
168
- function createPythonProgressReporter(operation, path) {
169
- let pending = Promise.resolve()
170
- const runtimeStart = operation.kind === 'runtime-start'
171
- const totalSteps = runtimeStart ? 6 : 7
172
- return {
173
- update(detail) {
174
- const fraction = Math.max(0, Math.min(1, Number(detail.fraction) || 0))
175
- const payload = {
176
- schemaVersion: 'foggy-deepseek-onboarding-progress/v1',
177
- operationId: operation.id,
178
- kind: operation.kind,
179
- state: 'running',
180
- phase: runtimeStart ? 'runtime-preflight' : 'python',
181
- message: runtimeStart ? 'Preparing the Foggy Runtime controller' : detail.message || 'Preparing managed Python',
182
- currentFile: detail.currentFile || null,
183
- percent: runtimeStart ? Math.round(fraction * 3) : Math.round(((1 + fraction) / totalSteps) * 100),
184
- step: { index: runtimeStart ? 1 : 2, total: totalSteps },
185
- startedAt: operation.startedAt,
186
- updatedAt: new Date().toISOString(),
187
- }
188
- if (detail.bytes) payload.bytes = detail.bytes
189
- operation.progress = payload
190
- pending = pending.then(() => writeJsonAtomic(path, payload))
191
- },
192
- flush() {
193
- return pending
194
- },
195
- }
196
- }
197
-
198
- function processRunning(pid) {
199
- if (!Number.isInteger(pid) || pid <= 0) return false
200
- try {
201
- process.kill(pid, 0)
202
- return true
203
- } catch {
204
- return false
205
- }
206
- }
207
-
208
- function operationView(operation) {
209
- if (!operation) return { state: 'idle' }
210
- const { promise: _promise, ...view } = operation
211
- return view
212
- }
213
-
214
- export class FoggyIntegrationGateway extends TypertRemoteService {
215
- static inject = ['skills', 'tools']
216
-
217
- operation = null
218
- skillProviderControl = null
219
-
220
- constructor(ctx) {
221
- super(ctx, 'foggyIntegration')
222
- const roots = defaultRoots()
223
- ctx.skills.registerProvider((control) => {
224
- this.skillProviderControl = control
225
- return createFoggySkillProvider({ installRoot: roots.installRoot, versionsFile })
226
- })
227
- ctx.tools.register(createFoggyQueryTool(roots))
228
- for (const initialize of markerInitializers) initialize.call(this)
229
- }
230
-
231
- async createViewerPreview(input) {
232
- const { runtimeUrl } = await managedConnection(defaultRoots())
233
- return createViewerPreview(input, runtimeUrl)
234
- }
235
-
236
- async status() {
237
- const roots = defaultRoots()
238
- const statePath = join(roots.installRoot, 'install-state.json')
239
- const runtimeStatePath = join(roots.dataRoot, 'runtime-state.json')
240
- const progressPath = join(roots.dataRoot, 'operation-progress.json')
241
- const portConflictPath = join(roots.dataRoot, 'last-runtime-port-conflict.json')
242
- const manifest = await readJson(versionsFile)
243
- const runtimeSettings = await readRuntimeSettings(roots.dataRoot, {
244
- defaultPort: manifest.defaults?.port ?? DEFAULT_RUNTIME_PORT,
245
- })
246
- const python = await probePythonRuntime({ installRoot: roots.installRoot, manifest })
247
- const java = compatible(await commandVersion(process.env.JAVA_EXE || 'java', ['-version']), '17.0')
248
- let state = null
249
- let runtime = null
250
- let lastRuntimePortConflict = null
251
- try { state = await readJson(statePath) } catch {}
252
- try { runtime = await readJson(runtimeStatePath) } catch {}
253
- try { lastRuntimePortConflict = await readJson(portConflictPath) } catch {}
254
- let onboarding = { success: true, profiles: [], profileCount: 0 }
255
- let profileMigration = { success: true, entries: [], pendingCount: 0, conflictCount: 0, profileStore: roots.profileStore }
256
- if (state) {
257
- try { onboarding = await runOnboarding(['onboard-list']) } catch (error) {
258
- onboarding = { success: false, profiles: [], profileCount: 0, error: String(error.message ?? error) }
259
- }
260
- try { profileMigration = await runOnboarding(['profile-migration-status']) } catch (error) {
261
- profileMigration = { success: false, entries: [], pendingCount: 0, conflictCount: 0, profileStore: roots.profileStore, error: String(error.message ?? error) }
262
- }
263
- }
264
- const cliPath = state?.cli?.command
265
- const launcherPath = state?.launcher?.path
266
- const analysisSkillPath = state?.skills?.analysis?.path || join(roots.installRoot, 'skills', 'foggy-ai-analysis')
267
- const semanticQuerySkillPath = state?.skills?.semanticQuery?.path || join(roots.installRoot, 'skills', 'foggy-semantic-query')
268
- const onboardingSkillPath = join(packageRoot, 'skills', 'foggy-deepseek-onboarding')
269
- const analysisMarker = await readOptionalJson(join(analysisSkillPath, '.foggy-managed-skill.json'))
270
- const semanticQueryMarker = await readOptionalJson(join(semanticQuerySkillPath, '.foggy-managed-skill.json'))
271
- const cliPresent = Boolean(cliPath && await exists(cliPath))
272
- const launcherPresent = Boolean(launcherPath && await exists(launcherPath))
273
- const analysisSkillPresent = await exists(join(analysisSkillPath, 'SKILL.md'))
274
- && analysisMarker?.schemaVersion === 'foggy-managed-skill/v1'
275
- const semanticQuerySkillPresent = await exists(join(semanticQuerySkillPath, 'SKILL.md'))
276
- && semanticQueryMarker?.schemaVersion === 'foggy-managed-skill/v1'
277
- const cliRelease = componentReleaseState({
278
- installed: cliPresent,
279
- installedVersion: state?.cli?.version,
280
- targetVersion: manifest.components.cli.version,
281
- })
282
- const launcherRelease = componentReleaseState({
283
- installed: launcherPresent,
284
- installedVersion: state?.launcher?.version,
285
- targetVersion: manifest.components.launcher.version,
286
- })
287
- const analysisRelease = componentReleaseState({
288
- installed: analysisSkillPresent,
289
- installedVersion: analysisMarker?.componentVersion || state?.skills?.analysis?.version,
290
- targetVersion: manifest.components.analysisSkill.version,
291
- })
292
- const semanticQueryRelease = componentReleaseState({
293
- installed: semanticQuerySkillPresent,
294
- installedVersion: semanticQueryMarker?.componentVersion || state?.skills?.semanticQuery?.version,
295
- targetVersion: manifest.components.semanticQuerySkill.version,
296
- })
297
- const components = {
298
- python,
299
- java,
300
- cli: {
301
- ...cliRelease,
302
- version: cliRelease.installedVersion ?? manifest.components.cli.version,
303
- },
304
- launcher: {
305
- ...launcherRelease,
306
- version: launcherRelease.installedVersion ?? manifest.components.launcher.version,
307
- },
308
- analysisSkill: {
309
- ...analysisRelease,
310
- version: analysisRelease.installedVersion ?? manifest.components.analysisSkill.version,
311
- },
312
- semanticQuerySkill: {
313
- ...semanticQueryRelease,
314
- version: semanticQueryRelease.installedVersion ?? manifest.components.semanticQuerySkill.version,
315
- },
316
- onboardingSkill: {
317
- installed: await exists(join(onboardingSkillPath, 'SKILL.md')),
318
- version: manifest.packageVersion,
319
- provider: 'foggy-managed-skills',
320
- },
321
- }
322
- const installed = components.python.available
323
- && components.cli.installed
324
- && components.launcher.installed
325
- && components.analysisSkill.installed
326
- && components.semanticQuerySkill.installed
327
- && components.onboardingSkill.installed
328
- const updateAvailable = Object.values(components).some((component) => component?.updateAvailable)
329
- const running = Boolean(runtime && processRunning(Number(runtime.pid)))
330
- const activePort = running && Number.isInteger(Number(runtime?.port)) ? Number(runtime.port) : null
331
- const progress = await readOptionalJson(progressPath)
332
- let operation = operationView(this.operation)
333
- if (operation.state === 'running' && progress?.operationId === operation.id) {
334
- operation = { ...operation, progress }
335
- } else if (!this.operation && progress?.state === 'running' && progress.operationId) {
336
- operation = {
337
- id: progress.operationId,
338
- kind: progress.kind || 'initialize',
339
- state: 'running',
340
- startedAt: progress.startedAt || null,
341
- finishedAt: null,
342
- result: null,
343
- error: null,
344
- progress,
345
- }
346
- }
347
- return {
348
- success: true,
349
- packageVersion: manifest.packageVersion,
350
- state: running ? 'running' : installed ? 'ready' : state ? 'degraded' : 'not-installed',
351
- installed,
352
- updateAvailable,
353
- running,
354
- runtimeUrl: running ? runtime.runtimeUrl ?? null : null,
355
- runtimeSettings: {
356
- ...runtimeSettings,
357
- activePort,
358
- activeRuntimeUrl: running ? runtime.runtimeUrl ?? null : null,
359
- pendingRestart: Boolean(running && activePort && activePort !== runtimeSettings.port),
360
- lastConflict: lastRuntimePortConflict,
361
- conflictApplies: Number(lastRuntimePortConflict?.port) === runtimeSettings.port,
362
- },
363
- roots,
364
- components,
365
- operation,
366
- onboarding,
367
- profileMigration,
368
- next: !state
369
- ? 'initialize'
370
- : updateAvailable
371
- ? 'update-components'
372
- : installed
373
- ? (running ? 'configure-database' : 'start-runtime')
374
- : 'repair',
375
- }
376
- }
377
-
378
- async plan() {
379
- const roots = defaultRoots()
380
- const manifest = await readJson(versionsFile)
381
- return {
382
- success: true,
383
- roots,
384
- workspaceMode: 'dsh-session-cwd',
385
- versions: Object.fromEntries(Object.entries(manifest.components).map(([name, value]) => [name, value.version])),
386
- operations: [
387
- 'download and verify a pinned private Python runtime',
388
- 'create isolated Python environment',
389
- 'download and verify pinned CLI and Launcher assets',
390
- 'install the Foggy analysis and semantic-query Skills into the global managed component directory',
391
- 'register onboarding, analysis, and semantic-query Skills through the native DSH Skill registry',
392
- 'write global install state; resolve each workspace from the DSH session cwd',
393
- ],
394
- secretsInDshSettings: false,
395
- }
396
- }
397
-
398
- async initialize() {
399
- return this.startOperation('initialize', false)
400
- }
401
-
402
- async initializeAndStart() {
403
- const status = await this.status()
404
- if (status.state !== 'not-installed') {
405
- return {
406
- success: false,
407
- accepted: false,
408
- error: { code: 'FOGGY_ALREADY_INITIALIZED', message: 'Foggy is already initialized; use Start Runtime or Update components.' },
409
- }
410
- }
411
- return this.startOperation('initialize-and-start', false, undefined, async ({ operation, progressPath, pythonProgress }) => {
412
- await assertSystemPrerequisites('initialize')
413
- const cacheArgs = (process.env.FOGGY_ASSET_CACHE_DIRS || '').split(delimiter).filter(Boolean)
414
- .flatMap((cacheDir) => ['--asset-cache-dir', cacheDir])
415
- const install = await runOnboarding([
416
- 'install', '--progress-file', progressPath, '--operation-id', operation.id, '--operation-kind', 'initialize',
417
- ...cacheArgs,
418
- ], 15 * 60_000, {
419
- ensurePython: true,
420
- onPythonProgress: (detail) => pythonProgress?.update(detail),
421
- flushPythonProgress: () => pythonProgress?.flush(),
422
- })
423
- if (install.success === false) return install
424
-
425
- await assertSystemPrerequisites('runtime-start')
426
- const roots = defaultRoots()
427
- const manifest = await readJson(versionsFile)
428
- const settings = await readRuntimeSettings(roots.dataRoot, {
429
- defaultPort: manifest.defaults?.port ?? DEFAULT_RUNTIME_PORT,
430
- })
431
- if (!settings.valid) {
432
- return {
433
- success: false,
434
- error: { code: 'RUNTIME_SETTINGS_INVALID', message: `Runtime settings are invalid: ${settings.error}` },
435
- }
436
- }
437
- return runOnboarding([
438
- 'runtime-start', '--install-root', roots.installRoot, '--data-root', roots.dataRoot,
439
- '--port', String(settings.port), '--progress-file', progressPath, '--operation-id', operation.id,
440
- '--operation-kind', 'runtime-start',
441
- ], 15 * 60_000, { ensurePython: false })
442
- })
443
- }
444
-
445
- async repair() {
446
- const blocked = await runtimeRunningUpdateGuard()
447
- if (blocked) return blocked
448
- return this.startOperation('repair', true)
449
- }
450
-
451
- async updateComponents() {
452
- const blocked = await runtimeRunningUpdateGuard()
453
- if (blocked) return blocked
454
- const status = await this.status()
455
- if (status.state === 'not-installed') {
456
- return {
457
- success: false,
458
- accepted: false,
459
- error: { code: 'FOGGY_NOT_INITIALIZED', message: 'Initialize Foggy before updating managed components.' },
460
- }
461
- }
462
- return this.startOperation('update-components', true)
463
- }
464
-
465
- async repairCli() {
466
- const blocked = await runtimeRunningUpdateGuard()
467
- if (blocked) return blocked
468
- return this.startOperation('repair-cli', false, ['install', '--repair-component', 'cli'])
469
- }
470
-
471
- async repairPython() {
472
- const blocked = await runtimeRunningUpdateGuard()
473
- if (blocked) return blocked
474
- return this.startOperation('repair-python', false, ['install'])
475
- }
476
-
477
- async repairLauncher() {
478
- const blocked = await runtimeRunningUpdateGuard()
479
- if (blocked) return blocked
480
- return this.startOperation('repair-launcher', false, ['install', '--repair-component', 'launcher'])
481
- }
482
-
483
- async repairAnalysisSkill() {
484
- const blocked = await runtimeRunningUpdateGuard()
485
- if (blocked) return blocked
486
- return this.startOperation('repair-analysis-skill', true, ['install', '--repair-component', 'analysis-skill'])
487
- }
488
-
489
- async repairSemanticQuerySkill() {
490
- const blocked = await runtimeRunningUpdateGuard()
491
- if (blocked) return blocked
492
- return this.startOperation('repair-semantic-query-skill', true, ['install', '--repair-component', 'semantic-query-skill'])
493
- }
494
-
495
- async migrateProfiles() {
496
- return this.startOperation('profile-migration', false, ['profile-migrate', '--approve'])
497
- }
498
-
499
- async diagnostics() {
500
- const roots = defaultRoots()
501
- const status = await this.status()
502
- const lastRuntimeStartFailure = await enrichRuntimeStartFailure(
503
- await readOptionalJson(join(roots.dataRoot, 'last-runtime-start-failure.json')),
504
- roots.dataRoot,
505
- )
506
- let doctor
507
- try {
508
- doctor = await runOnboarding(['doctor', '--no-fail'])
509
- } catch (error) {
510
- doctor = { success: false, error: String(error.message ?? error), bootstrapOnly: true }
511
- }
512
- const report = {
513
- schemaVersion: 'foggy-deepseek-diagnostics/v1',
514
- generatedAt: new Date().toISOString(),
515
- packageVersion: status.packageVersion,
516
- state: status.state,
517
- installed: status.installed,
518
- running: status.running,
519
- runtimeUrl: status.runtimeUrl,
520
- roots: status.roots,
521
- components: status.components,
522
- onboarding: status.onboarding,
523
- profileMigration: status.profileMigration,
524
- runtimeSettings: status.runtimeSettings,
525
- lastRuntimeStartFailure,
526
- doctor,
527
- }
528
- const directory = join(roots.dataRoot, 'diagnostics')
529
- await mkdir(directory, { recursive: true })
530
- const path = join(directory, `diagnostics-${Date.now()}.json`)
531
- await writeFile(path, `${JSON.stringify(report, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
532
- return { success: true, path, report }
533
- }
534
-
535
- async runtimeStart() {
536
- const roots = defaultRoots()
537
- const manifest = await readJson(versionsFile)
538
- const settings = await readRuntimeSettings(roots.dataRoot, {
539
- defaultPort: manifest.defaults?.port ?? DEFAULT_RUNTIME_PORT,
540
- })
541
- if (!settings.valid) {
542
- return {
543
- success: false,
544
- accepted: false,
545
- error: {
546
- code: 'RUNTIME_SETTINGS_INVALID',
547
- message: `Runtime settings are invalid: ${settings.error}. Save a valid port in Foggy plugin settings.`,
548
- },
549
- }
550
- }
551
- return this.startOperation('runtime-start', false, [
552
- 'runtime-start', '--install-root', roots.installRoot, '--data-root', roots.dataRoot,
553
- '--port', String(settings.port),
554
- ])
555
- }
556
-
557
- async runtimeStop() {
558
- const roots = defaultRoots()
559
- return this.startOperation('runtime-stop', false, [
560
- 'runtime-stop', '--install-root', roots.installRoot, '--data-root', roots.dataRoot,
561
- ])
562
- }
563
-
564
- async saveRuntimeSettings(input) {
565
- const roots = defaultRoots()
566
- if (this.operation?.state === 'running') {
567
- return {
568
- success: false,
569
- error: { code: 'OPERATION_RUNNING', message: 'Wait for the current Foggy operation to finish before changing the Runtime port.' },
570
- }
571
- }
572
- const runtime = await readOptionalJson(join(roots.dataRoot, 'runtime-state.json'))
573
- if (runtime && processRunning(Number(runtime.pid))) {
574
- return {
575
- success: false,
576
- error: { code: 'RUNTIME_RUNNING', message: 'Stop Foggy Runtime before changing its port.' },
577
- }
578
- }
579
- try {
580
- const settings = await writeRuntimeSettings(roots.dataRoot, input)
581
- if (this.operation?.state === 'failed' && this.operation.result?.error?.code === 'RUNTIME_PORT_UNAVAILABLE') {
582
- this.operation = null
583
- }
584
- return { success: true, settings }
585
- } catch (error) {
586
- return {
587
- success: false,
588
- error: { code: 'RUNTIME_PORT_INVALID', message: String(error?.message ?? error) },
589
- }
590
- }
591
- }
592
-
593
- startOperation(kind, replaceSkill, explicitArgs, runner = null) {
594
- if (this.operation?.state === 'running') {
595
- return { success: false, accepted: false, operation: operationView(this.operation), error: 'another Foggy operation is running' }
596
- }
597
- const id = `${Date.now()}-${Math.random().toString(16).slice(2, 10)}`
598
- const args = explicitArgs ?? ['install']
599
- const reportsProgress = args[0] === 'install' || args[0] === 'runtime-start' || runner !== null
600
- const progressPath = reportsProgress ? join(defaultRoots().dataRoot, 'operation-progress.json') : null
601
- if (reportsProgress) {
602
- args.push('--progress-file', progressPath, '--operation-id', id, '--operation-kind', kind)
603
- }
604
- if (replaceSkill) args.push('--replace-skill')
605
- for (const cacheDir of (process.env.FOGGY_ASSET_CACHE_DIRS || '').split(delimiter).filter(Boolean)) {
606
- args.push('--asset-cache-dir', cacheDir)
607
- }
608
- const runtimeStart = kind === 'runtime-start' || kind.endsWith('-and-start')
609
- const operation = {
610
- id,
611
- kind,
612
- state: 'running',
613
- startedAt: new Date().toISOString(),
614
- finishedAt: null,
615
- result: null,
616
- error: null,
617
- progress: reportsProgress ? {
618
- schemaVersion: 'foggy-deepseek-onboarding-progress/v1',
619
- operationId: id,
620
- kind,
621
- state: 'running',
622
- phase: 'preflight',
623
- message: runtimeStart ? 'Starting Foggy Runtime' : 'Starting Foggy initialization',
624
- currentFile: null,
625
- percent: 0,
626
- step: { index: 1, total: runtimeStart ? 6 : 7 },
627
- } : null,
628
- promise: null,
629
- }
630
- const pythonProgress = reportsProgress
631
- ? createPythonProgressReporter(operation, progressPath)
632
- : null
633
- operation.promise = (async () => {
634
- await assertSystemPrerequisites(kind)
635
- if (runner) return runner({ operation, progressPath, pythonProgress })
636
- return runOnboarding(args, 15 * 60_000, {
637
- ensurePython: true,
638
- forcePython: kind === 'repair-python',
639
- onPythonProgress: (detail) => pythonProgress?.update(detail),
640
- flushPythonProgress: () => pythonProgress?.flush(),
641
- })
642
- })()
643
- .then((result) => {
644
- operation.state = result.success === false ? 'failed' : 'succeeded'
645
- operation.result = result
646
- operation.finishedAt = new Date().toISOString()
647
- this.skillProviderControl?.invalidate()
648
- if (operation.progress) {
649
- operation.progress = {
650
- ...operation.progress,
651
- state: operation.state,
652
- phase: operation.state === 'succeeded' ? (runtimeStart ? 'runtime-complete' : 'complete') : operation.progress.phase,
653
- message: operation.state === 'succeeded'
654
- ? (runtimeStart ? 'Foggy Runtime is ready' : 'Foggy initialization completed')
655
- : (runtimeStart ? 'Foggy Runtime startup failed' : 'Foggy initialization failed'),
656
- percent: operation.state === 'succeeded' ? 100 : operation.progress.percent,
657
- }
658
- }
659
- })
660
- .catch((error) => {
661
- operation.state = 'failed'
662
- operation.error = String(error.message ?? error)
663
- operation.finishedAt = new Date().toISOString()
664
- this.skillProviderControl?.invalidate()
665
- if (operation.progress) {
666
- operation.progress = {
667
- ...operation.progress,
668
- state: 'failed',
669
- message: runtimeStart ? 'Foggy Runtime startup failed' : 'Foggy initialization failed',
670
- }
671
- }
672
- })
673
- this.operation = operation
674
- return { success: true, accepted: true, operation: operationView(operation) }
675
- }
676
- }
677
-
678
- const markerInitializers = []
679
- for (const method of [
680
- 'status', 'plan', 'initialize', 'initializeAndStart', 'repair', 'updateComponents', 'repairPython', 'repairCli', 'repairLauncher', 'repairAnalysisSkill', 'repairSemanticQuerySkill',
681
- 'migrateProfiles', 'diagnostics', 'runtimeStart', 'runtimeStop',
682
- 'saveRuntimeSettings',
683
- 'createViewerPreview',
684
- ]) {
685
- Remote(method)(FoggyIntegrationGateway.prototype[method], {
686
- kind: 'method',
687
- name: method,
688
- static: false,
689
- private: false,
690
- access: {
691
- has: (object) => method in object,
692
- get: (object) => object[method],
693
- },
694
- addInitializer: (initializer) => markerInitializers.push(initializer),
695
- })
696
- }
697
-
698
- export default FoggyIntegrationGateway
1
+ import { execFile } from 'node:child_process'
2
+ import { access, mkdir, readFile, writeFile, rm } from 'node:fs/promises'
3
+ import { randomUUID } from 'node:crypto'
4
+ import { constants as fsConstants } from 'node:fs'
5
+ import { dirname, join, delimiter } from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+ import { promisify } from 'node:util'
8
+ import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
9
+ import { createFoggySkillProvider } from './skill-provider.js'
10
+ import { writeJsonAtomic } from './atomic-json.js'
11
+ import { ensurePythonRuntime, probePythonRuntime } from './python-runtime.js'
12
+ import { compatible, compatibleNode } from './version.js'
13
+ import { enrichRuntimeStartFailure } from './diagnostics.js'
14
+ import { createFoggyQueryTool, managedConnection } from './query-tool.js'
15
+ import { createViewerPreview } from './viewer-preview.js'
16
+ import { componentVersions, effectiveComponentVersions, prepareComponentVersion, rememberInstalledComponents } from './component-manager.js'
17
+ import { withManagedOperationLock } from './operation-lock.js'
18
+ import {
19
+ DEFAULT_RUNTIME_PORT,
20
+ readRuntimeSettings,
21
+ writeRuntimeSettings,
22
+ } from './runtime-settings.js'
23
+
24
+ const execFileAsync = promisify(execFile)
25
+ const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)))
26
+ const onboardingScript = join(packageRoot, 'skills', 'foggy-deepseek-onboarding', 'scripts', 'onboarding.py')
27
+ const versionsFile = join(packageRoot, 'skills', 'foggy-deepseek-onboarding', 'assets', 'versions.json')
28
+
29
+ function defaultRoots() {
30
+ if (process.platform === 'win32') {
31
+ const base = process.env.LOCALAPPDATA
32
+ if (!base) throw new Error('LOCALAPPDATA is not set')
33
+ return {
34
+ installRoot: join(base, 'Foggy', 'DeepSeekHarness'),
35
+ dataRoot: join(base, 'Foggy', 'DeepSeekHarnessData'),
36
+ profileStore: process.env.FOGGY_RUNTIME_PROFILE_STORE || join(base, 'Foggy', 'DeepSeekHarnessData', 'cli-profiles'),
37
+ }
38
+ }
39
+ const home = process.env.HOME
40
+ if (!home) throw new Error('HOME is not set')
41
+ const dataRoot = process.env.XDG_STATE_HOME
42
+ ? join(process.env.XDG_STATE_HOME, 'foggy', 'deepseek-harness')
43
+ : join(home, '.local', 'state', 'foggy', 'deepseek-harness')
44
+ return {
45
+ installRoot: process.env.XDG_DATA_HOME
46
+ ? join(process.env.XDG_DATA_HOME, 'foggy', 'deepseek-harness')
47
+ : join(home, '.local', 'share', 'foggy', 'deepseek-harness'),
48
+ dataRoot,
49
+ profileStore: process.env.FOGGY_RUNTIME_PROFILE_STORE || join(dataRoot, 'cli-profiles'),
50
+ }
51
+ }
52
+
53
+ function componentReleaseState({ installed, installedVersion, targetVersion }) {
54
+ const normalizedInstalled = installedVersion || null
55
+ const normalizedTarget = targetVersion || null
56
+ const updateAvailable = Boolean(installed && normalizedInstalled && normalizedTarget && normalizedInstalled !== normalizedTarget)
57
+ return {
58
+ installed: Boolean(installed && !updateAvailable),
59
+ installedVersion: normalizedInstalled,
60
+ targetVersion: normalizedTarget,
61
+ updateAvailable,
62
+ }
63
+ }
64
+
65
+ async function exists(path) {
66
+ try {
67
+ await access(path, fsConstants.F_OK)
68
+ return true
69
+ } catch {
70
+ return false
71
+ }
72
+ }
73
+
74
+ async function readJson(path) {
75
+ return JSON.parse(await readFile(path, 'utf8'))
76
+ }
77
+
78
+ async function readOptionalJson(path) {
79
+ try {
80
+ return await readJson(path)
81
+ } catch {
82
+ return null
83
+ }
84
+ }
85
+
86
+ async function effectiveVersions(roots = defaultRoots()) {
87
+ return effectiveComponentVersions(await readJson(versionsFile), await readOptionalJson(join(roots.installRoot, 'install-state.json')))
88
+ }
89
+
90
+ async function runtimeRunningUpdateGuard() {
91
+ const roots = defaultRoots()
92
+ const runtime = await readOptionalJson(join(roots.dataRoot, 'runtime-state.json'))
93
+ if (runtime && processRunning(Number(runtime.pid))) {
94
+ return {
95
+ success: false,
96
+ accepted: false,
97
+ error: {
98
+ code: 'RUNTIME_RUNNING_UPDATE_REQUIRES_STOP',
99
+ message: 'Stop Foggy Runtime before updating or repairing managed components.',
100
+ },
101
+ }
102
+ }
103
+ return null
104
+ }
105
+
106
+ async function commandVersion(command, args) {
107
+ try {
108
+ const { stdout, stderr } = await execFileAsync(command, args, {
109
+ windowsHide: true,
110
+ timeout: 15_000,
111
+ maxBuffer: 256 * 1024,
112
+ })
113
+ return { available: true, output: `${stdout}\n${stderr}`.trim().split(/\r?\n/)[0] ?? '' }
114
+ } catch (error) {
115
+ return { available: false, output: '', error: error.code ?? 'COMMAND_FAILED' }
116
+ }
117
+ }
118
+
119
+ function parseOutput(stdout, stderr) {
120
+ const text = String(stdout ?? '').trim()
121
+ if (!text) throw new Error(String(stderr ?? '').trim() || 'Foggy onboarding returned no JSON')
122
+ try {
123
+ return JSON.parse(text)
124
+ } catch {
125
+ throw new Error(`Foggy onboarding returned invalid JSON: ${text.slice(0, 240)}`)
126
+ }
127
+ }
128
+
129
+ export function withAssetCacheArguments(args, cacheDirs) {
130
+ if (args[0] !== 'install') return [...args]
131
+ return [...args, ...cacheDirs.flatMap((directory) => ['--asset-cache-dir', directory])]
132
+ }
133
+
134
+ async function runOnboarding(args, timeout = 15 * 60_000, options = {}) {
135
+ const roots = defaultRoots()
136
+ const manifest = options.manifest || await effectiveVersions(roots)
137
+ const cacheDirs = (process.env.FOGGY_ASSET_CACHE_DIRS || '').split(delimiter).filter(Boolean)
138
+ const python = options.ensurePython
139
+ ? await ensurePythonRuntime({
140
+ installRoot: roots.installRoot,
141
+ manifest,
142
+ cacheDirs,
143
+ force: options.forcePython,
144
+ onProgress: options.onPythonProgress,
145
+ })
146
+ : await probePythonRuntime({ installRoot: roots.installRoot, manifest })
147
+ if (!python.available) {
148
+ throw new Error('Foggy managed Python is unavailable; initialize or repair the Python component')
149
+ }
150
+ await options.flushPythonProgress?.()
151
+ const manifestPath = join(roots.dataRoot, 'operations', `${randomUUID()}.versions.json`)
152
+ await writeJsonAtomic(manifestPath, manifest)
153
+ try {
154
+ const { stdout, stderr } = await execFileAsync(python.path, [onboardingScript, ...args], {
155
+ windowsHide: true,
156
+ timeout,
157
+ maxBuffer: 4 * 1024 * 1024,
158
+ cwd: process.env.FOGGY_PROJECT_ROOT || process.cwd(),
159
+ env: {
160
+ ...process.env,
161
+ FOGGY_ONBOARDING_PYTHON: python.path,
162
+ FOGGY_ONBOARDING_PYTHON_SOURCE: python.source,
163
+ FOGGY_ONBOARDING_VERSIONS_FILE: manifestPath,
164
+ },
165
+ })
166
+ const result = parseOutput(stdout, stderr)
167
+ if (args[0] === 'install' && result.success !== false) {
168
+ const warnings = await rememberInstalledComponents(roots, await readOptionalJson(join(roots.installRoot, 'install-state.json')))
169
+ if (warnings.length) result.warnings = [...(result.warnings || []), ...warnings]
170
+ }
171
+ return result
172
+ } catch (error) {
173
+ if (error.stdout) return parseOutput(error.stdout, error.stderr)
174
+ throw error
175
+ } finally {
176
+ await rm(manifestPath, { force: true }).catch(() => {})
177
+ }
178
+ }
179
+
180
+ async function assertSystemPrerequisites(kind) {
181
+ if (kind === 'initialize' && !compatibleNode(process.versions.node)) {
182
+ throw new Error(`This DeepSeek Harness plugin requires Node.js >=24.0.0; detected ${process.versions.node}`)
183
+ }
184
+ if (kind === 'initialize' || kind === 'runtime-start') {
185
+ const java = compatible(await commandVersion(process.env.JAVA_EXE || 'java', ['-version']), '17.0')
186
+ if (!java.available) throw new Error('Java 17+ is required; install a system JRE/JDK or set JAVA_EXE')
187
+ }
188
+ }
189
+
190
+ function createPythonProgressReporter(operation, path) {
191
+ let pending = Promise.resolve()
192
+ const runtimeStart = operation.kind === 'runtime-start'
193
+ const totalSteps = runtimeStart ? 6 : 7
194
+ return {
195
+ update(detail) {
196
+ const fraction = Math.max(0, Math.min(1, Number(detail.fraction) || 0))
197
+ const payload = {
198
+ schemaVersion: 'foggy-deepseek-onboarding-progress/v1',
199
+ operationId: operation.id,
200
+ kind: operation.kind,
201
+ state: 'running',
202
+ phase: runtimeStart ? 'runtime-preflight' : 'python',
203
+ message: runtimeStart ? 'Preparing the Foggy Runtime controller' : detail.message || 'Preparing managed Python',
204
+ currentFile: detail.currentFile || null,
205
+ percent: runtimeStart ? Math.round(fraction * 3) : Math.round(((1 + fraction) / totalSteps) * 100),
206
+ step: { index: runtimeStart ? 1 : 2, total: totalSteps },
207
+ startedAt: operation.startedAt,
208
+ updatedAt: new Date().toISOString(),
209
+ }
210
+ if (detail.bytes) payload.bytes = detail.bytes
211
+ operation.progress = payload
212
+ pending = pending.then(() => writeJsonAtomic(path, payload))
213
+ },
214
+ flush() {
215
+ return pending
216
+ },
217
+ }
218
+ }
219
+
220
+ function processRunning(pid) {
221
+ if (!Number.isInteger(pid) || pid <= 0) return false
222
+ try {
223
+ process.kill(pid, 0)
224
+ return true
225
+ } catch {
226
+ return false
227
+ }
228
+ }
229
+
230
+ function operationView(operation) {
231
+ if (!operation) return { state: 'idle' }
232
+ const { promise: _promise, ...view } = operation
233
+ return view
234
+ }
235
+
236
+ export class FoggyIntegrationGateway extends TypertRemoteService {
237
+ static inject = ['skills', 'tools']
238
+
239
+ operation = null
240
+ skillProviderControl = null
241
+
242
+ constructor(ctx) {
243
+ super(ctx, 'foggyIntegration')
244
+ this.viewerTools = ctx.tools
245
+ const roots = defaultRoots()
246
+ ctx.skills.registerProvider((control) => {
247
+ this.skillProviderControl = control
248
+ return createFoggySkillProvider({ installRoot: roots.installRoot, versionsFile })
249
+ })
250
+ ctx.tools.register(createFoggyQueryTool(roots))
251
+ for (const initialize of markerInitializers) initialize.call(this)
252
+ }
253
+
254
+ async createViewerPreview(input) {
255
+ const roots = defaultRoots()
256
+ const runtime = await readOptionalJson(join(roots.dataRoot, 'runtime-state.json'))
257
+ const managedRuntime = runtime && processRunning(Number(runtime.pid))
258
+ ? { runtimeUrl: runtime.runtimeUrl, securityMode: runtime.identity?.securityMode } : null
259
+ return createViewerPreview(input, this.viewerTools, managedRuntime)
260
+ }
261
+
262
+ async status() {
263
+ // A completed operation must not be combined with files read before it
264
+ // completed. Keeping the entry snapshot running guarantees one fresh poll.
265
+ let operation = operationView(this.operation)
266
+ const roots = defaultRoots()
267
+ const statePath = join(roots.installRoot, 'install-state.json')
268
+ const runtimeStatePath = join(roots.dataRoot, 'runtime-state.json')
269
+ const progressPath = join(roots.dataRoot, 'operation-progress.json')
270
+ const portConflictPath = join(roots.dataRoot, 'last-runtime-port-conflict.json')
271
+ const manifest = await effectiveVersions(roots)
272
+ const runtimeSettings = await readRuntimeSettings(roots.dataRoot, {
273
+ defaultPort: manifest.defaults?.port ?? DEFAULT_RUNTIME_PORT,
274
+ })
275
+ const python = await probePythonRuntime({ installRoot: roots.installRoot, manifest })
276
+ const java = compatible(await commandVersion(process.env.JAVA_EXE || 'java', ['-version']), '17.0')
277
+ let state = null
278
+ let runtime = null
279
+ let lastRuntimePortConflict = null
280
+ try { state = await readJson(statePath) } catch {}
281
+ try { runtime = await readJson(runtimeStatePath) } catch {}
282
+ try { lastRuntimePortConflict = await readJson(portConflictPath) } catch {}
283
+ let onboarding = { success: true, profiles: [], profileCount: 0 }
284
+ let profileMigration = { success: true, entries: [], pendingCount: 0, conflictCount: 0, profileStore: roots.profileStore }
285
+ if (state) {
286
+ try { onboarding = await runOnboarding(['onboard-list']) } catch (error) {
287
+ onboarding = { success: false, profiles: [], profileCount: 0, error: String(error.message ?? error) }
288
+ }
289
+ try { profileMigration = await runOnboarding(['profile-migration-status']) } catch (error) {
290
+ profileMigration = { success: false, entries: [], pendingCount: 0, conflictCount: 0, profileStore: roots.profileStore, error: String(error.message ?? error) }
291
+ }
292
+ }
293
+ const cliPath = state?.cli?.command
294
+ const launcherPath = state?.launcher?.path
295
+ const analysisSkillPath = state?.skills?.analysis?.path || join(roots.installRoot, 'skills', 'foggy-ai-analysis')
296
+ const semanticQuerySkillPath = state?.skills?.semanticQuery?.path || join(roots.installRoot, 'skills', 'foggy-semantic-query')
297
+ const onboardingSkillPath = join(packageRoot, 'skills', 'foggy-deepseek-onboarding')
298
+ const analysisMarker = await readOptionalJson(join(analysisSkillPath, '.foggy-managed-skill.json'))
299
+ const semanticQueryMarker = await readOptionalJson(join(semanticQuerySkillPath, '.foggy-managed-skill.json'))
300
+ const cliPresent = Boolean(cliPath && await exists(cliPath))
301
+ const launcherPresent = Boolean(launcherPath && await exists(launcherPath))
302
+ const analysisSkillPresent = await exists(join(analysisSkillPath, 'SKILL.md'))
303
+ && analysisMarker?.schemaVersion === 'foggy-managed-skill/v1'
304
+ const semanticQuerySkillPresent = await exists(join(semanticQuerySkillPath, 'SKILL.md'))
305
+ && semanticQueryMarker?.schemaVersion === 'foggy-managed-skill/v1'
306
+ const cliRelease = componentReleaseState({
307
+ installed: cliPresent,
308
+ installedVersion: state?.cli?.version,
309
+ targetVersion: manifest.components.cli.version,
310
+ })
311
+ const launcherRelease = componentReleaseState({
312
+ installed: launcherPresent,
313
+ installedVersion: state?.launcher?.version,
314
+ targetVersion: manifest.components.launcher.version,
315
+ })
316
+ const analysisRelease = componentReleaseState({
317
+ installed: analysisSkillPresent,
318
+ installedVersion: analysisMarker?.componentVersion || state?.skills?.analysis?.version,
319
+ targetVersion: manifest.components.analysisSkill.version,
320
+ })
321
+ const semanticQueryRelease = componentReleaseState({
322
+ installed: semanticQuerySkillPresent,
323
+ installedVersion: semanticQueryMarker?.componentVersion || state?.skills?.semanticQuery?.version,
324
+ targetVersion: manifest.components.semanticQuerySkill.version,
325
+ })
326
+ const components = {
327
+ python,
328
+ java,
329
+ cli: {
330
+ ...cliRelease,
331
+ version: cliRelease.installedVersion ?? manifest.components.cli.version,
332
+ },
333
+ launcher: {
334
+ ...launcherRelease,
335
+ version: launcherRelease.installedVersion ?? manifest.components.launcher.version,
336
+ },
337
+ analysisSkill: {
338
+ ...analysisRelease,
339
+ version: analysisRelease.installedVersion ?? manifest.components.analysisSkill.version,
340
+ },
341
+ semanticQuerySkill: {
342
+ ...semanticQueryRelease,
343
+ version: semanticQueryRelease.installedVersion ?? manifest.components.semanticQuerySkill.version,
344
+ },
345
+ onboardingSkill: {
346
+ installed: await exists(join(onboardingSkillPath, 'SKILL.md')),
347
+ version: manifest.packageVersion,
348
+ provider: 'foggy-managed-skills',
349
+ },
350
+ }
351
+ const installed = components.python.available
352
+ && components.cli.installed
353
+ && components.launcher.installed
354
+ && components.analysisSkill.installed
355
+ && components.semanticQuerySkill.installed
356
+ && components.onboardingSkill.installed
357
+ const updateAvailable = Object.values(components).some((component) => component?.updateAvailable)
358
+ const running = Boolean(runtime && processRunning(Number(runtime.pid)))
359
+ const activePort = running && Number.isInteger(Number(runtime?.port)) ? Number(runtime.port) : null
360
+ const progress = await readOptionalJson(progressPath)
361
+ if (operation.state === 'running' && progress?.operationId === operation.id) {
362
+ operation = { ...operation, progress }
363
+ } else if (operation.state === 'idle' && progress?.state === 'running' && progress.operationId) {
364
+ operation = {
365
+ id: progress.operationId,
366
+ kind: progress.kind || 'initialize',
367
+ state: 'running',
368
+ startedAt: progress.startedAt || null,
369
+ finishedAt: null,
370
+ result: null,
371
+ error: null,
372
+ progress,
373
+ }
374
+ }
375
+ return {
376
+ success: true,
377
+ packageVersion: manifest.packageVersion,
378
+ state: running ? 'running' : installed ? 'ready' : state ? 'degraded' : 'not-installed',
379
+ installed,
380
+ updateAvailable,
381
+ running,
382
+ runtimeUrl: running ? runtime.runtimeUrl ?? null : null,
383
+ runtimeSettings: {
384
+ ...runtimeSettings,
385
+ activePort,
386
+ activeRuntimeUrl: running ? runtime.runtimeUrl ?? null : null,
387
+ pendingRestart: Boolean(running && activePort && activePort !== runtimeSettings.port),
388
+ lastConflict: lastRuntimePortConflict,
389
+ conflictApplies: Number(lastRuntimePortConflict?.port) === runtimeSettings.port,
390
+ },
391
+ roots,
392
+ components,
393
+ operation,
394
+ onboarding,
395
+ profileMigration,
396
+ next: !state
397
+ ? 'initialize'
398
+ : updateAvailable
399
+ ? 'update-components'
400
+ : installed
401
+ ? (running ? 'configure-database' : 'start-runtime')
402
+ : 'repair',
403
+ }
404
+ }
405
+
406
+ async plan() {
407
+ const roots = defaultRoots()
408
+ const manifest = await effectiveVersions(roots)
409
+ return {
410
+ success: true,
411
+ roots,
412
+ workspaceMode: 'dsh-session-cwd',
413
+ versions: Object.fromEntries(Object.entries(manifest.components).map(([name, value]) => [name, value.version])),
414
+ operations: [
415
+ 'download and verify a pinned private Python runtime',
416
+ 'create isolated Python environment',
417
+ 'download and verify pinned CLI and Launcher assets',
418
+ 'install the Foggy analysis and semantic-query Skills into the global managed component directory',
419
+ 'register onboarding, analysis, and semantic-query Skills through the native DSH Skill registry',
420
+ 'write global install state; resolve each workspace from the DSH session cwd',
421
+ ],
422
+ secretsInDshSettings: false,
423
+ }
424
+ }
425
+
426
+ async initialize() {
427
+ const blocked = await runtimeRunningUpdateGuard()
428
+ if (blocked) return blocked
429
+ return this.startOperation('initialize', false)
430
+ }
431
+
432
+ async componentVersions() {
433
+ const roots = defaultRoots()
434
+ return componentVersions({ roots, bundled: await readJson(versionsFile), state: await readOptionalJson(join(roots.installRoot, 'install-state.json')) })
435
+ }
436
+
437
+ async checkComponentVersions() {
438
+ const roots = defaultRoots()
439
+ return componentVersions({ roots, bundled: await readJson(versionsFile), state: await readOptionalJson(join(roots.installRoot, 'install-state.json')), force: true })
440
+ }
441
+
442
+ async useComponentVersion(input) {
443
+ const blocked = await runtimeRunningUpdateGuard()
444
+ if (blocked) return blocked
445
+ const roots = defaultRoots()
446
+ const state = await readOptionalJson(join(roots.installRoot, 'install-state.json'))
447
+ if (!state) return { success: false, accepted: false, error: { code: 'FOGGY_NOT_INITIALIZED', message: 'Initialize Foggy before selecting component versions.' } }
448
+ return this.startOperation('use-component-version', false, undefined, async ({ operation, progressPath, pythonProgress }) => {
449
+ if (!input || !['launcher', 'cli'].includes(input.component) || typeof input.version !== 'string') throw new Error('Select a valid Launcher or CLI version.')
450
+ const current = await readOptionalJson(join(roots.installRoot, 'install-state.json'))
451
+ if (!current) throw new Error('Initialize Foggy before selecting component versions.')
452
+ const manifest = await prepareComponentVersion({ roots, bundled: await readJson(versionsFile), state: current, ...input })
453
+ const running = await runtimeRunningUpdateGuard()
454
+ if (running) return running
455
+ return runOnboarding([
456
+ 'install', '--install-root', roots.installRoot, '--data-root', roots.dataRoot,
457
+ '--progress-file', progressPath, '--operation-id', operation.id, '--operation-kind', operation.kind,
458
+ ], 15 * 60_000, {
459
+ manifest, ensurePython: true,
460
+ onPythonProgress: (detail) => pythonProgress?.update(detail),
461
+ flushPythonProgress: () => pythonProgress?.flush(),
462
+ })
463
+ })
464
+ }
465
+
466
+ async initializeAndStart() {
467
+ const status = await this.status()
468
+ if (status.state !== 'not-installed') {
469
+ return {
470
+ success: false,
471
+ accepted: false,
472
+ error: { code: 'FOGGY_ALREADY_INITIALIZED', message: 'Foggy is already initialized; use Start Runtime or Update components.' },
473
+ }
474
+ }
475
+ return this.startOperation('initialize-and-start', false, undefined, async ({ operation, progressPath, pythonProgress }) => {
476
+ await assertSystemPrerequisites('initialize')
477
+ const cacheArgs = (process.env.FOGGY_ASSET_CACHE_DIRS || '').split(delimiter).filter(Boolean)
478
+ .flatMap((cacheDir) => ['--asset-cache-dir', cacheDir])
479
+ const install = await runOnboarding([
480
+ 'install', '--progress-file', progressPath, '--operation-id', operation.id, '--operation-kind', 'initialize',
481
+ ...cacheArgs,
482
+ ], 15 * 60_000, {
483
+ ensurePython: true,
484
+ onPythonProgress: (detail) => pythonProgress?.update(detail),
485
+ flushPythonProgress: () => pythonProgress?.flush(),
486
+ })
487
+ if (install.success === false) return install
488
+
489
+ await assertSystemPrerequisites('runtime-start')
490
+ const roots = defaultRoots()
491
+ const manifest = await readJson(versionsFile)
492
+ const settings = await readRuntimeSettings(roots.dataRoot, {
493
+ defaultPort: manifest.defaults?.port ?? DEFAULT_RUNTIME_PORT,
494
+ })
495
+ if (!settings.valid) {
496
+ return {
497
+ success: false,
498
+ error: { code: 'RUNTIME_SETTINGS_INVALID', message: `Runtime settings are invalid: ${settings.error}` },
499
+ }
500
+ }
501
+ return runOnboarding([
502
+ 'runtime-start', '--install-root', roots.installRoot, '--data-root', roots.dataRoot,
503
+ '--port', String(settings.port), '--progress-file', progressPath, '--operation-id', operation.id,
504
+ '--operation-kind', 'runtime-start',
505
+ ], 15 * 60_000, { ensurePython: false })
506
+ })
507
+ }
508
+
509
+ async repair() {
510
+ const blocked = await runtimeRunningUpdateGuard()
511
+ if (blocked) return blocked
512
+ return this.startOperation('repair', true)
513
+ }
514
+
515
+ async updateComponents() {
516
+ const blocked = await runtimeRunningUpdateGuard()
517
+ if (blocked) return blocked
518
+ const status = await this.status()
519
+ if (status.state === 'not-installed') {
520
+ return {
521
+ success: false,
522
+ accepted: false,
523
+ error: { code: 'FOGGY_NOT_INITIALIZED', message: 'Initialize Foggy before updating managed components.' },
524
+ }
525
+ }
526
+ return this.startOperation('update-components', true)
527
+ }
528
+
529
+ async repairCli() {
530
+ const blocked = await runtimeRunningUpdateGuard()
531
+ if (blocked) return blocked
532
+ return this.startOperation('repair-cli', false, ['install', '--repair-component', 'cli'])
533
+ }
534
+
535
+ async repairPython() {
536
+ const blocked = await runtimeRunningUpdateGuard()
537
+ if (blocked) return blocked
538
+ return this.startOperation('repair-python', false, ['install'])
539
+ }
540
+
541
+ async repairLauncher() {
542
+ const blocked = await runtimeRunningUpdateGuard()
543
+ if (blocked) return blocked
544
+ return this.startOperation('repair-launcher', false, ['install', '--repair-component', 'launcher'])
545
+ }
546
+
547
+ async repairAnalysisSkill() {
548
+ const blocked = await runtimeRunningUpdateGuard()
549
+ if (blocked) return blocked
550
+ return this.startOperation('repair-analysis-skill', true, ['install', '--repair-component', 'analysis-skill'])
551
+ }
552
+
553
+ async repairSemanticQuerySkill() {
554
+ const blocked = await runtimeRunningUpdateGuard()
555
+ if (blocked) return blocked
556
+ return this.startOperation('repair-semantic-query-skill', true, ['install', '--repair-component', 'semantic-query-skill'])
557
+ }
558
+
559
+ async migrateProfiles() {
560
+ return this.startOperation('profile-migration', false, ['profile-migrate', '--approve'])
561
+ }
562
+
563
+ async diagnostics() {
564
+ const roots = defaultRoots()
565
+ const status = await this.status()
566
+ const lastRuntimeStartFailure = await enrichRuntimeStartFailure(
567
+ await readOptionalJson(join(roots.dataRoot, 'last-runtime-start-failure.json')),
568
+ roots.dataRoot,
569
+ )
570
+ let doctor
571
+ try {
572
+ doctor = await runOnboarding(['doctor', '--no-fail'])
573
+ } catch (error) {
574
+ doctor = { success: false, error: String(error.message ?? error), bootstrapOnly: true }
575
+ }
576
+ const report = {
577
+ schemaVersion: 'foggy-deepseek-diagnostics/v1',
578
+ generatedAt: new Date().toISOString(),
579
+ packageVersion: status.packageVersion,
580
+ state: status.state,
581
+ installed: status.installed,
582
+ running: status.running,
583
+ runtimeUrl: status.runtimeUrl,
584
+ roots: status.roots,
585
+ components: status.components,
586
+ onboarding: status.onboarding,
587
+ profileMigration: status.profileMigration,
588
+ runtimeSettings: status.runtimeSettings,
589
+ lastRuntimeStartFailure,
590
+ doctor,
591
+ }
592
+ const directory = join(roots.dataRoot, 'diagnostics')
593
+ await mkdir(directory, { recursive: true })
594
+ const path = join(directory, `diagnostics-${Date.now()}.json`)
595
+ await writeFile(path, `${JSON.stringify(report, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
596
+ return { success: true, path, report }
597
+ }
598
+
599
+ async runtimeStart() {
600
+ const roots = defaultRoots()
601
+ const manifest = await readJson(versionsFile)
602
+ const settings = await readRuntimeSettings(roots.dataRoot, {
603
+ defaultPort: manifest.defaults?.port ?? DEFAULT_RUNTIME_PORT,
604
+ })
605
+ if (!settings.valid) {
606
+ return {
607
+ success: false,
608
+ accepted: false,
609
+ error: {
610
+ code: 'RUNTIME_SETTINGS_INVALID',
611
+ message: `Runtime settings are invalid: ${settings.error}. Save a valid port in Foggy plugin settings.`,
612
+ },
613
+ }
614
+ }
615
+ return this.startOperation('runtime-start', false, [
616
+ 'runtime-start', '--install-root', roots.installRoot, '--data-root', roots.dataRoot,
617
+ '--port', String(settings.port),
618
+ ])
619
+ }
620
+
621
+ async runtimeStop() {
622
+ const roots = defaultRoots()
623
+ return this.startOperation('runtime-stop', false, [
624
+ 'runtime-stop', '--install-root', roots.installRoot, '--data-root', roots.dataRoot,
625
+ ])
626
+ }
627
+
628
+ async saveRuntimeSettings(input) {
629
+ const roots = defaultRoots()
630
+ if (this.operation?.state === 'running') {
631
+ return {
632
+ success: false,
633
+ error: { code: 'OPERATION_RUNNING', message: 'Wait for the current Foggy operation to finish before changing the Runtime port.' },
634
+ }
635
+ }
636
+ const runtime = await readOptionalJson(join(roots.dataRoot, 'runtime-state.json'))
637
+ if (runtime && processRunning(Number(runtime.pid))) {
638
+ return {
639
+ success: false,
640
+ error: { code: 'RUNTIME_RUNNING', message: 'Stop Foggy Runtime before changing its port.' },
641
+ }
642
+ }
643
+ try {
644
+ const settings = await writeRuntimeSettings(roots.dataRoot, input)
645
+ if (this.operation?.state === 'failed' && this.operation.result?.error?.code === 'RUNTIME_PORT_UNAVAILABLE') {
646
+ this.operation = null
647
+ }
648
+ return { success: true, settings }
649
+ } catch (error) {
650
+ return {
651
+ success: false,
652
+ error: { code: 'RUNTIME_PORT_INVALID', message: String(error?.message ?? error) },
653
+ }
654
+ }
655
+ }
656
+
657
+ startOperation(kind, replaceSkill, explicitArgs, runner = null) {
658
+ if (this.operation?.state === 'running') {
659
+ return { success: false, accepted: false, operation: operationView(this.operation), error: 'another Foggy operation is running' }
660
+ }
661
+ const id = `${Date.now()}-${Math.random().toString(16).slice(2, 10)}`
662
+ const args = withAssetCacheArguments(explicitArgs ?? ['install'], (process.env.FOGGY_ASSET_CACHE_DIRS || '').split(delimiter).filter(Boolean))
663
+ const reportsProgress = args[0] === 'install' || args[0] === 'runtime-start' || runner !== null
664
+ const progressPath = reportsProgress ? join(defaultRoots().dataRoot, 'operation-progress.json') : null
665
+ if (reportsProgress) {
666
+ args.push('--progress-file', progressPath, '--operation-id', id, '--operation-kind', kind)
667
+ }
668
+ if (replaceSkill) args.push('--replace-skill')
669
+ const runtimeStart = kind === 'runtime-start' || kind.endsWith('-and-start')
670
+ const operation = {
671
+ id,
672
+ kind,
673
+ state: 'running',
674
+ startedAt: new Date().toISOString(),
675
+ finishedAt: null,
676
+ result: null,
677
+ error: null,
678
+ progress: reportsProgress ? {
679
+ schemaVersion: 'foggy-deepseek-onboarding-progress/v1',
680
+ operationId: id,
681
+ kind,
682
+ state: 'running',
683
+ phase: 'preflight',
684
+ message: runtimeStart ? 'Starting Foggy Runtime' : 'Starting Foggy initialization',
685
+ currentFile: null,
686
+ percent: 0,
687
+ step: { index: 1, total: runtimeStart ? 6 : 7 },
688
+ } : null,
689
+ promise: null,
690
+ }
691
+ const pythonProgress = reportsProgress
692
+ ? createPythonProgressReporter(operation, progressPath)
693
+ : null
694
+ operation.promise = withManagedOperationLock(defaultRoots().dataRoot, async () => {
695
+ if (args[0] === 'install' || kind === 'initialize-and-start' || kind === 'use-component-version') {
696
+ const blocked = await runtimeRunningUpdateGuard()
697
+ if (blocked) return blocked
698
+ }
699
+ await assertSystemPrerequisites(kind)
700
+ if (runner) return runner({ operation, progressPath, pythonProgress })
701
+ return runOnboarding(args, 15 * 60_000, {
702
+ ensurePython: true,
703
+ forcePython: kind === 'repair-python',
704
+ onPythonProgress: (detail) => pythonProgress?.update(detail),
705
+ flushPythonProgress: () => pythonProgress?.flush(),
706
+ })
707
+ }, { kind })
708
+ .then((result) => {
709
+ operation.state = result.success === false ? 'failed' : 'succeeded'
710
+ operation.result = result
711
+ operation.finishedAt = new Date().toISOString()
712
+ this.skillProviderControl?.invalidate()
713
+ if (operation.progress) {
714
+ operation.progress = {
715
+ ...operation.progress,
716
+ state: operation.state,
717
+ phase: operation.state === 'succeeded' ? (runtimeStart ? 'runtime-complete' : 'complete') : operation.progress.phase,
718
+ message: operation.state === 'succeeded'
719
+ ? (runtimeStart ? 'Foggy Runtime is ready' : 'Foggy initialization completed')
720
+ : (runtimeStart ? 'Foggy Runtime startup failed' : 'Foggy initialization failed'),
721
+ percent: operation.state === 'succeeded' ? 100 : operation.progress.percent,
722
+ }
723
+ }
724
+ })
725
+ .catch((error) => {
726
+ operation.state = 'failed'
727
+ operation.error = String(error.message ?? error)
728
+ operation.finishedAt = new Date().toISOString()
729
+ this.skillProviderControl?.invalidate()
730
+ if (operation.progress) {
731
+ operation.progress = {
732
+ ...operation.progress,
733
+ state: 'failed',
734
+ message: runtimeStart ? 'Foggy Runtime startup failed' : 'Foggy initialization failed',
735
+ }
736
+ }
737
+ })
738
+ this.operation = operation
739
+ return { success: true, accepted: true, operation: operationView(operation) }
740
+ }
741
+ }
742
+
743
+ const markerInitializers = []
744
+ for (const method of [
745
+ 'status', 'plan', 'initialize', 'initializeAndStart', 'repair', 'updateComponents', 'repairPython', 'repairCli', 'repairLauncher', 'repairAnalysisSkill', 'repairSemanticQuerySkill',
746
+ 'migrateProfiles', 'diagnostics', 'runtimeStart', 'runtimeStop',
747
+ 'saveRuntimeSettings',
748
+ 'createViewerPreview',
749
+ 'componentVersions', 'checkComponentVersions', 'useComponentVersion',
750
+ ]) {
751
+ Remote(method)(FoggyIntegrationGateway.prototype[method], {
752
+ kind: 'method',
753
+ name: method,
754
+ static: false,
755
+ private: false,
756
+ access: {
757
+ has: (object) => method in object,
758
+ get: (object) => object[method],
759
+ },
760
+ addInitializer: (initializer) => markerInitializers.push(initializer),
761
+ })
762
+ }
763
+
764
+ export default FoggyIntegrationGateway