@capyclaw/capyclaw 0.0.0-stage → 0.3.0
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/README.md +40 -2
- package/client/client.js +273 -0
- package/cordis.patch.yml +5 -0
- package/icon.svg +5 -0
- package/index.js +360 -0
- package/lib/environment.mjs +198 -0
- package/lib/jobs.mjs +116 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/manifest.js +18 -0
- package/node_modules/@capyclaw/foundation/README.md +51 -0
- package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
- package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
- package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
- package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
- package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
- package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
- package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
- package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
- package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
- package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
- package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
- package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
- package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
- package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
- package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
- package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
- package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
- package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
- package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
- package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
- package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
- package/node_modules/@capyclaw/foundation/package.json +53 -0
- package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
- package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
- package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
- package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
- package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
- package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
- package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
- package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
- package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
- package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
- package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
- package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
- package/package.json +78 -4
- package/test/environment.test.mjs +68 -0
- package/test/package.test.mjs +24 -0
- package/test/plugin.test.mjs +179 -0
- package/test/stability.test.mjs +576 -0
- package/test/wizard.test.mjs +219 -0
package/index.js
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { MANIFEST } from './manifest.js'
|
|
4
|
+
import { createEnvironmentManifest, detectPlatform, normalizeEnvironmentManifest, planEnvironment } from './lib/environment.mjs'
|
|
5
|
+
import { createJobEngine } from './lib/jobs.mjs'
|
|
6
|
+
|
|
7
|
+
export const name = '@capyclaw/capyclaw'
|
|
8
|
+
export const inject = ['pluginManager', 'tools', 'profileContext']
|
|
9
|
+
|
|
10
|
+
const outputSchema = { type: 'object', additionalProperties: true }
|
|
11
|
+
const render = (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }]
|
|
12
|
+
|
|
13
|
+
function readJson(file) {
|
|
14
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return undefined }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function profileDirectory(ctx) {
|
|
18
|
+
return ctx.profileContext?.dir || process.env.DSH_PROFILE_DIR || null
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function dshVersion(ctx) {
|
|
22
|
+
const installDir = process.env.DSH_INSTALL_DIR
|
|
23
|
+
const manifest = installDir ? readJson(path.join(installDir, 'package.json')) : null
|
|
24
|
+
if (manifest?.name === '@deepseek-ai/dsh') return manifest.version || null
|
|
25
|
+
const anchor = ctx.profileContext?.installAnchor
|
|
26
|
+
const anchored = anchor ? readJson(anchor) : null
|
|
27
|
+
return anchored?.version || null
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Only registry specs are portable. link:/file:/workspace:/git/protocol/path
|
|
31
|
+
// dependencies are machine-local and must never be reported as registry installs.
|
|
32
|
+
function isRegistrySpec(spec) {
|
|
33
|
+
return typeof spec === 'string' && spec.length > 0 && !spec.includes(':') && !/[\\/]/.test(spec) && !spec.startsWith('.')
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function readInstalled(ctx) {
|
|
37
|
+
const dir = profileDirectory(ctx)
|
|
38
|
+
const profile = dir ? readJson(path.join(dir, 'package.json')) : null
|
|
39
|
+
const deps = profile?.dependencies || {}
|
|
40
|
+
const installed = {}
|
|
41
|
+
const local = {}
|
|
42
|
+
for (const [packageName, spec] of Object.entries(deps)) {
|
|
43
|
+
if (!isRegistrySpec(spec)) { installed[packageName] = null; local[packageName] = String(spec); continue }
|
|
44
|
+
const pkgPath = dir ? path.join(dir, 'node_modules', packageName, 'package.json') : null
|
|
45
|
+
const pkg = pkgPath ? readJson(pkgPath) : null
|
|
46
|
+
installed[packageName] = pkg?.version ? `${packageName}@${pkg.version}` : null
|
|
47
|
+
}
|
|
48
|
+
let bundles = []
|
|
49
|
+
try { bundles = await ctx.pluginManager.listBundles() } catch { /* report bundle inventory unavailable below */ }
|
|
50
|
+
return { installed, bundles, local }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function readImport(file) {
|
|
54
|
+
if (!file || typeof file !== 'string') throw new TypeError('manifestPath must be a file path')
|
|
55
|
+
const absolute = path.resolve(file)
|
|
56
|
+
return { absolute, manifest: normalizeEnvironmentManifest(JSON.parse(fs.readFileSync(absolute, 'utf8'))) }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function inspect(ctx, manifest = MANIFEST, options = {}) {
|
|
60
|
+
const { installed, bundles, local } = await readInstalled(ctx)
|
|
61
|
+
const plan = planEnvironment({
|
|
62
|
+
manifest,
|
|
63
|
+
platform: options.platform || detectPlatform(),
|
|
64
|
+
installed,
|
|
65
|
+
local,
|
|
66
|
+
dshVersion: dshVersion(ctx),
|
|
67
|
+
allowUpgrade: options.allowUpgrade === true,
|
|
68
|
+
})
|
|
69
|
+
return { ...plan, installedBundles: bundles.map(({ name, enabled }) => ({ name, enabled })) }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const API_PREFIX = '/capyclaw/environment/api/'
|
|
73
|
+
|
|
74
|
+
function onboardingFile(ctx) {
|
|
75
|
+
const dir = profileDirectory(ctx)
|
|
76
|
+
return dir ? path.join(dir, '.capyclaw-environment.json') : null
|
|
77
|
+
}
|
|
78
|
+
function readOnboarding(ctx) {
|
|
79
|
+
const file = onboardingFile(ctx)
|
|
80
|
+
return (file && readJson(file)) || {}
|
|
81
|
+
}
|
|
82
|
+
function writeOnboarding(ctx, patch) {
|
|
83
|
+
const file = onboardingFile(ctx)
|
|
84
|
+
if (!file) return
|
|
85
|
+
try {
|
|
86
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
87
|
+
fs.writeFileSync(file, `${JSON.stringify({ ...readOnboarding(ctx), ...patch }, null, 2)}\n`, 'utf8')
|
|
88
|
+
} catch { /* onboarding marker is best-effort */ }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function wizardHandler({ ctx, engine }) {
|
|
92
|
+
const send = (res, code, obj) => {
|
|
93
|
+
res.writeHead(code, { 'content-type': 'application/json', 'cache-control': 'no-store' })
|
|
94
|
+
res.end(JSON.stringify(obj))
|
|
95
|
+
}
|
|
96
|
+
const readBody = (req) => new Promise((resolve, reject) => {
|
|
97
|
+
let data = ''
|
|
98
|
+
req.on('data', (chunk) => {
|
|
99
|
+
data += chunk
|
|
100
|
+
if (data.length > 1e6) { reject(new Error('request body too large')); req.destroy() }
|
|
101
|
+
})
|
|
102
|
+
req.on('end', () => { try { resolve(data ? JSON.parse(data) : {}) } catch (error) { reject(error) } })
|
|
103
|
+
req.on('error', reject)
|
|
104
|
+
})
|
|
105
|
+
return async (req, res) => {
|
|
106
|
+
try {
|
|
107
|
+
const pathname = new URL(req.url, 'http://localhost').pathname
|
|
108
|
+
const route = pathname.startsWith(API_PREFIX) ? pathname.slice(API_PREFIX.length) : ''
|
|
109
|
+
if (route === 'state' && req.method === 'GET') {
|
|
110
|
+
const ob = readOnboarding(ctx)
|
|
111
|
+
return send(res, 200, {
|
|
112
|
+
ok: true, platform: detectPlatform(), dshVersion: dshVersion(ctx),
|
|
113
|
+
onboarded: Boolean(ob.onboarded), running: engine.isRunning(),
|
|
114
|
+
jobs: engine.list().map((j) => ({ id: j.id, kind: j.kind, status: j.status, percent: j.percent })),
|
|
115
|
+
})
|
|
116
|
+
}
|
|
117
|
+
if (route === 'scan' && req.method === 'POST') {
|
|
118
|
+
const body = await readBody(req)
|
|
119
|
+
return send(res, 200, { ok: true, job: engine.startScan({ manifestPath: body.manifestPath, platform: body.platform }) })
|
|
120
|
+
}
|
|
121
|
+
if (route.startsWith('jobs/') && req.method === 'GET') {
|
|
122
|
+
const job = engine.get(route.slice('jobs/'.length))
|
|
123
|
+
return job ? send(res, 200, { ok: true, job }) : send(res, 404, { ok: false, error: 'job not found' })
|
|
124
|
+
}
|
|
125
|
+
if (route === 'apply' && req.method === 'POST') {
|
|
126
|
+
const body = await readBody(req)
|
|
127
|
+
const job = engine.startApply({ scanId: body.scanId, allowVersionChange: body.allowVersionChange !== false, exclude: body.exclude })
|
|
128
|
+
writeOnboarding(ctx, { onboarded: true, at: Date.now() })
|
|
129
|
+
return send(res, 200, { ok: true, job })
|
|
130
|
+
}
|
|
131
|
+
if (route === 'cancel' && req.method === 'POST') {
|
|
132
|
+
const body = await readBody(req)
|
|
133
|
+
return send(res, 200, { ok: true, result: await engine.cancel(body.jobId) })
|
|
134
|
+
}
|
|
135
|
+
if (route === 'dismiss' && req.method === 'POST') {
|
|
136
|
+
writeOnboarding(ctx, { onboarded: true, dismissed: true, at: Date.now() })
|
|
137
|
+
return send(res, 200, { ok: true })
|
|
138
|
+
}
|
|
139
|
+
return send(res, 404, { ok: false, error: 'unknown route' })
|
|
140
|
+
} catch (error) {
|
|
141
|
+
return send(res, 400, { ok: false, error: String(error?.message || error) })
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export async function executeEnvironmentPlan(ctx, plan, { onProgress = () => {}, requestId } = {}) {
|
|
147
|
+
const results = []
|
|
148
|
+
const manager = ctx.pluginManager
|
|
149
|
+
const emit = (ev) => { try { onProgress(ev) } catch { /* progress is best-effort */ } }
|
|
150
|
+
const versionOf = (item) => (item.spec && item.spec.startsWith(`${item.name}@`) ? item.spec.slice(item.name.length + 1) : undefined)
|
|
151
|
+
// Deliberately do NOT pass `expected` to installBundle. The manager's expected-guard
|
|
152
|
+
// (plugin-manager lib/index.js ~871) rejects the whole install when ANY other direct
|
|
153
|
+
// dependency is "touched" by pnpm. Development profiles are full of file:/link: deps
|
|
154
|
+
// that pnpm re-processes on every `add`, so the guard false-positives with
|
|
155
|
+
// `unexpected-package` even though the target package installed correctly (proven by
|
|
156
|
+
// the manager's own pnpm.log). installBundle's after-read still enforces "exactly one
|
|
157
|
+
// new dependency, and it is a compatible bundle"; combined with the planner's exact
|
|
158
|
+
// `name@version` registry pins + saveExact, that is the meaningful verification.
|
|
159
|
+
const installOptions = () => ({ saveExact: true, requestId })
|
|
160
|
+
for (const item of plan.actions) {
|
|
161
|
+
if (item.action === 'keep') continue
|
|
162
|
+
const phase = item.action === 'remove' ? 'removing'
|
|
163
|
+
: item.action === 'version-change' ? (item.direction === 'downgrade' ? 'replacing' : 'updating')
|
|
164
|
+
: 'installing'
|
|
165
|
+
emit({ name: item.name, action: item.action, state: 'running', phase })
|
|
166
|
+
try {
|
|
167
|
+
let result
|
|
168
|
+
if (item.action === 'remove') {
|
|
169
|
+
result = await manager.removeBundle(item.name)
|
|
170
|
+
} else if (item.action === 'version-change' && item.direction === 'upgrade') {
|
|
171
|
+
// Native update path: HMR-aware remove+install with automatic rollback.
|
|
172
|
+
const update = await manager.updateBundle(item.name, versionOf(item), { requestId })
|
|
173
|
+
result = update?.result || update || {}
|
|
174
|
+
if (update?.restore) result = { ...result, restored: true }
|
|
175
|
+
} else if (item.action === 'version-change' && item.direction === 'downgrade') {
|
|
176
|
+
const removed = await manager.removeBundle(item.name)
|
|
177
|
+
result = removed.application === 'failed'
|
|
178
|
+
? removed
|
|
179
|
+
: await manager.installBundle(item.spec, installOptions())
|
|
180
|
+
} else {
|
|
181
|
+
result = await manager.installBundle(item.spec, installOptions())
|
|
182
|
+
}
|
|
183
|
+
const ok = result.application !== 'failed' && result.application !== 'cancelled'
|
|
184
|
+
results.push({ name: item.name, action: item.action, application: result.application, ok, error: result.error || null })
|
|
185
|
+
emit({ name: item.name, action: item.action, state: ok ? 'done' : 'failed', application: result.application, error: result.error || null })
|
|
186
|
+
} catch (error) {
|
|
187
|
+
results.push({ name: item.name, action: item.action, ok: false, error: String(error?.message || error) })
|
|
188
|
+
emit({ name: item.name, action: item.action, state: 'failed', error: String(error?.message || error) })
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
let installedBundles
|
|
192
|
+
try { installedBundles = await manager.listBundles() } catch (error) {
|
|
193
|
+
results.push({ name: '*', action: 'enable', ok: false, error: `Bundle inventory unavailable after install: ${String(error?.message || error)}` })
|
|
194
|
+
return results
|
|
195
|
+
}
|
|
196
|
+
const enabledNames = new Set(installedBundles.filter((item) => item.enabled).map((item) => item.name))
|
|
197
|
+
for (const bundle of plan.manifest.bundles) {
|
|
198
|
+
if (enabledNames.has(bundle)) continue
|
|
199
|
+
emit({ name: bundle, action: 'enable', state: 'running', phase: 'enabling' })
|
|
200
|
+
try {
|
|
201
|
+
const result = await manager.setBundleEnabled(bundle, true)
|
|
202
|
+
const ok = result.application !== 'failed'
|
|
203
|
+
results.push({ name: bundle, action: 'enable', application: result.application, ok, error: result.error || null })
|
|
204
|
+
emit({ name: bundle, action: 'enable', state: ok ? 'done' : 'failed', application: result.application, error: result.error || null })
|
|
205
|
+
} catch (error) {
|
|
206
|
+
results.push({ name: bundle, action: 'enable', ok: false, error: String(error?.message || error) })
|
|
207
|
+
emit({ name: bundle, action: 'enable', state: 'failed', error: String(error?.message || error) })
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return results
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// The desktop host provides webServer in a different Cordis isolation branch, so a
|
|
214
|
+
// plain ctx.get('webServer')/ctx.inject can miss it even while the service is live.
|
|
215
|
+
// Scan the root store by service name (same approach as @capyclaw/foundation) to find
|
|
216
|
+
// the real instance, falling back to ctx.get and direct access for simpler hosts.
|
|
217
|
+
function findWebServer(ctx) {
|
|
218
|
+
try { if (typeof ctx.get === 'function') { const s = ctx.get('webServer'); if (s?.register) return s } } catch { /* not in this branch */ }
|
|
219
|
+
try {
|
|
220
|
+
const store = ctx?.root?.store
|
|
221
|
+
if (store && typeof store === 'object') {
|
|
222
|
+
for (const key of Reflect.ownKeys(store)) {
|
|
223
|
+
const impl = store[key]
|
|
224
|
+
if (impl?.name === 'webServer' && impl.value?.register) return impl.value
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
} catch { /* store shape differs */ }
|
|
228
|
+
try { const s = ctx.webServer; if (s?.register) return s } catch { /* undeclared service */ }
|
|
229
|
+
return null
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export function apply(ctx) {
|
|
233
|
+
const disposers = []
|
|
234
|
+
const register = (definition) => disposers.push(ctx.tools.register({ output: { schema: outputSchema, render }, ...definition }))
|
|
235
|
+
|
|
236
|
+
const engine = createJobEngine({
|
|
237
|
+
runScan: async (opts) => {
|
|
238
|
+
const imported = opts.manifestPath ? readImport(opts.manifestPath) : null
|
|
239
|
+
// Surface version changes for explicit user consent in the wizard.
|
|
240
|
+
return inspect(ctx, imported?.manifest || MANIFEST, { platform: opts.platform, allowUpgrade: true })
|
|
241
|
+
},
|
|
242
|
+
runApply: (plan, opts) => executeEnvironmentPlan(ctx, plan, opts),
|
|
243
|
+
cancelInstall: (requestId) => (typeof ctx.pluginManager.cancelInstall === 'function'
|
|
244
|
+
? ctx.pluginManager.cancelInstall(requestId)
|
|
245
|
+
: Promise.resolve({ status: 'not-running' })),
|
|
246
|
+
})
|
|
247
|
+
|
|
248
|
+
// The GUI wizard is optional: profiles without a webServer still get the tools.
|
|
249
|
+
// Register once, whichever lookup finds the live webServer first (immediate store
|
|
250
|
+
// scan for the desktop host, or a deferred inject for hosts that start it later).
|
|
251
|
+
let routeOff = null
|
|
252
|
+
const attachRoutes = (webServer) => {
|
|
253
|
+
if (routeOff || !webServer?.register) return
|
|
254
|
+
try {
|
|
255
|
+
const off = webServer.register({ kind: 'prefix', path: API_PREFIX, handler: wizardHandler({ ctx, engine }) })
|
|
256
|
+
routeOff = typeof off === 'function' ? off : null
|
|
257
|
+
} catch { /* web server present but registration failed; tools still work */ }
|
|
258
|
+
}
|
|
259
|
+
attachRoutes(findWebServer(ctx))
|
|
260
|
+
if (typeof ctx.inject === 'function') {
|
|
261
|
+
try {
|
|
262
|
+
const fork = ctx.inject(['webServer'], (scoped) => { attachRoutes(scoped.webServer); return () => {} })
|
|
263
|
+
if (typeof fork === 'function') disposers.push(fork)
|
|
264
|
+
else if (fork && typeof fork.dispose === 'function') disposers.push(() => fork.dispose())
|
|
265
|
+
} catch { /* inject unavailable; immediate lookup already covered it */ }
|
|
266
|
+
}
|
|
267
|
+
disposers.push(() => { if (routeOff) { try { routeOff() } catch { /* already removed */ } routeOff = null } })
|
|
268
|
+
|
|
269
|
+
register({
|
|
270
|
+
name: 'capyclaw_setup',
|
|
271
|
+
description: 'Scan this profile against the portable environment manifest and return the setup plan for the user to review. Read-only; the user confirms installs/removals in the CapyClaw wizard GUI. Does not apply changes.',
|
|
272
|
+
parameters: {
|
|
273
|
+
manifestPath: { type: 'string', description: 'Optional imported JSON manifest path.' },
|
|
274
|
+
platform: { type: 'string', description: 'Override platform for planning/tests: windows, macos, or linux.' },
|
|
275
|
+
},
|
|
276
|
+
async execute(args) {
|
|
277
|
+
const imported = args.manifestPath ? readImport(args.manifestPath) : null
|
|
278
|
+
const plan = await inspect(ctx, imported?.manifest || MANIFEST, { platform: args.platform, allowUpgrade: true })
|
|
279
|
+
return { mode: 'scan', ...plan, manifestPath: imported?.absolute || null, wizard: { apiPrefix: API_PREFIX, onboarded: Boolean(readOnboarding(ctx).onboarded) } }
|
|
280
|
+
},
|
|
281
|
+
})
|
|
282
|
+
|
|
283
|
+
register({
|
|
284
|
+
name: 'capyclaw_manifest',
|
|
285
|
+
description: 'Show the portable starter environment manifest. Read-only.',
|
|
286
|
+
parameters: {},
|
|
287
|
+
async execute() { return MANIFEST },
|
|
288
|
+
})
|
|
289
|
+
|
|
290
|
+
register({
|
|
291
|
+
name: 'capyclaw_status',
|
|
292
|
+
description: 'Detect this operating system and compare the current DSH profile with a portable environment manifest. Read-only.',
|
|
293
|
+
parameters: {
|
|
294
|
+
manifestPath: { type: 'string', description: 'Optional path to an exported CapyClaw JSON manifest.' },
|
|
295
|
+
},
|
|
296
|
+
async execute(args) {
|
|
297
|
+
const imported = args.manifestPath ? readImport(args.manifestPath) : null
|
|
298
|
+
const plan = await inspect(ctx, imported?.manifest || MANIFEST)
|
|
299
|
+
return { ...plan, manifestPath: imported?.absolute || null }
|
|
300
|
+
},
|
|
301
|
+
})
|
|
302
|
+
|
|
303
|
+
register({
|
|
304
|
+
name: 'capyclaw_export_environment',
|
|
305
|
+
description: 'Export the current profile package and enabled-bundle selection to a portable JSON environment manifest.',
|
|
306
|
+
parameters: { outputPath: { type: 'string', description: 'Destination JSON file path.' } },
|
|
307
|
+
async execute(args) {
|
|
308
|
+
if (!args.outputPath) throw new TypeError('outputPath is required')
|
|
309
|
+
const { installed, bundles } = await readInstalled(ctx)
|
|
310
|
+
const packages = Object.entries(installed).map(([packageName, installedSpec]) => ({
|
|
311
|
+
name: packageName,
|
|
312
|
+
spec: installedSpec,
|
|
313
|
+
platforms: ['windows', 'macos', 'linux'],
|
|
314
|
+
})).filter((item) => item.spec && item.spec.startsWith(`${item.name}@`) && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.test(item.spec.slice(item.name.length + 1)))
|
|
315
|
+
const manifest = createEnvironmentManifest({
|
|
316
|
+
name: 'Exported CapyClaw environment',
|
|
317
|
+
dshVersion: dshVersion(ctx),
|
|
318
|
+
packages,
|
|
319
|
+
bundles: bundles.filter((b) => b.enabled).map((b) => b.name),
|
|
320
|
+
})
|
|
321
|
+
const destination = path.resolve(args.outputPath)
|
|
322
|
+
fs.mkdirSync(path.dirname(destination), { recursive: true })
|
|
323
|
+
fs.writeFileSync(destination, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8')
|
|
324
|
+
return { ok: true, path: destination, packageCount: manifest.packages.length, bundleCount: manifest.bundles.length, omittedLocalLinks: Object.keys(installed).length - packages.length }
|
|
325
|
+
},
|
|
326
|
+
})
|
|
327
|
+
|
|
328
|
+
register({
|
|
329
|
+
name: 'capyclaw_sync',
|
|
330
|
+
description: 'Preview or apply a cross-platform profile setup from the portable starter manifest or an imported manifest. Preview is read-only. Package version changes (upgrade or downgrade) require allowUpgrade=true; machine-local link/file/path dependencies are never replaced; unrelated packages are never removed.',
|
|
331
|
+
parameters: {
|
|
332
|
+
manifestPath: { type: 'string', description: 'Optional imported JSON manifest path.' },
|
|
333
|
+
apply: { type: 'boolean', description: 'Install packages and enable selected bundles. Default false (preview only).' },
|
|
334
|
+
allowUpgrade: { type: 'boolean', description: 'Permit any installed package version change, including downgrade. Default false.' },
|
|
335
|
+
platform: { type: 'string', description: 'Override platform for planning/tests: windows, macos, or linux.' },
|
|
336
|
+
},
|
|
337
|
+
async execute(args) {
|
|
338
|
+
const imported = args.manifestPath ? readImport(args.manifestPath) : null
|
|
339
|
+
const manifest = imported?.manifest || MANIFEST
|
|
340
|
+
const initial = await inspect(ctx, manifest, args)
|
|
341
|
+
if (!args.apply) return { mode: 'preview', ...initial }
|
|
342
|
+
if (!initial.ready) return { mode: 'blocked', ok: false, ...initial }
|
|
343
|
+
const installingNames = new Set(initial.actions.filter((item) => item.action === 'install').map((item) => item.name))
|
|
344
|
+
const missingBundles = manifest.bundles.filter((bundle) => !initial.installedBundles.some((item) => item.name === bundle) && !installingNames.has(bundle))
|
|
345
|
+
if (missingBundles.length) return { mode: 'blocked', ok: false, ...initial, blockers: [...initial.blockers, ...missingBundles.map((bundle) => `Bundle is not installed: ${bundle}`)] }
|
|
346
|
+
|
|
347
|
+
const profileDir = profileDirectory(ctx)
|
|
348
|
+
const profileFile = profileDir ? path.join(profileDir, 'package.json') : null
|
|
349
|
+
const backup = profileFile && fs.existsSync(profileFile) ? `${profileFile}.capyclaw-backup-${Date.now()}` : null
|
|
350
|
+
if (backup) fs.copyFileSync(profileFile, backup)
|
|
351
|
+
const results = await executeEnvironmentPlan(ctx, initial)
|
|
352
|
+
const final = await inspect(ctx, manifest, args)
|
|
353
|
+
const ok = results.every((item) => item.ok) && final.actions.every((item) => item.action === 'keep')
|
|
354
|
+
if (ok) writeOnboarding(ctx, { onboarded: true, at: Date.now() })
|
|
355
|
+
return { mode: 'applied', ok, results, final, profileBackup: backup, restartRequired: results.some((r) => r.application === 'restart-required') }
|
|
356
|
+
},
|
|
357
|
+
})
|
|
358
|
+
|
|
359
|
+
return () => { for (const dispose of disposers) { try { dispose() } catch { /* already disposed */ } } }
|
|
360
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import os from 'node:os'
|
|
2
|
+
|
|
3
|
+
export function detectPlatform(platform = process.platform) {
|
|
4
|
+
if (platform === 'win32') return 'windows'
|
|
5
|
+
if (platform === 'darwin') return 'macos'
|
|
6
|
+
if (platform === 'linux') return 'linux'
|
|
7
|
+
return 'unsupported'
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function normalizeEnvironmentManifest(raw) {
|
|
11
|
+
if (!raw || raw.schemaVersion !== 1 || !Array.isArray(raw.packages)) {
|
|
12
|
+
throw new TypeError('Environment manifest must use schemaVersion 1 and include packages')
|
|
13
|
+
}
|
|
14
|
+
const names = new Set()
|
|
15
|
+
const packages = raw.packages.map((item) => {
|
|
16
|
+
if (!item || typeof item.name !== 'string' || !item.name.trim()) {
|
|
17
|
+
throw new TypeError('Every environment package must have a name')
|
|
18
|
+
}
|
|
19
|
+
if (names.has(item.name)) throw new TypeError(`Duplicate environment package: ${item.name}`)
|
|
20
|
+
names.add(item.name)
|
|
21
|
+
if (typeof item.spec !== 'string' || !item.spec.trim()) {
|
|
22
|
+
throw new TypeError(`Environment package ${item.name} must have an install spec`)
|
|
23
|
+
}
|
|
24
|
+
const platforms = item.platforms ?? ['windows', 'macos', 'linux']
|
|
25
|
+
if (!Array.isArray(platforms) || platforms.some((p) => !['windows', 'macos', 'linux'].includes(p))) {
|
|
26
|
+
throw new TypeError(`Invalid platform list for ${item.name}`)
|
|
27
|
+
}
|
|
28
|
+
return { name: item.name, spec: item.spec, platforms: [...new Set(platforms)], required: item.required !== false }
|
|
29
|
+
})
|
|
30
|
+
const removeRaw = raw.remove === undefined ? [] : raw.remove
|
|
31
|
+
if (!Array.isArray(removeRaw) || removeRaw.some((n) => typeof n !== 'string' || !n.trim())) {
|
|
32
|
+
throw new TypeError('remove must be an array of package names')
|
|
33
|
+
}
|
|
34
|
+
const remove = [...new Set(removeRaw.map((n) => n.trim()))]
|
|
35
|
+
return {
|
|
36
|
+
schemaVersion: 1,
|
|
37
|
+
name: String(raw.name || 'Imported environment'),
|
|
38
|
+
dsh: raw.dsh && typeof raw.dsh === 'object' ? { ...raw.dsh } : {},
|
|
39
|
+
packages,
|
|
40
|
+
bundles: Array.isArray(raw.bundles) ? raw.bundles.filter((x) => typeof x === 'string') : [],
|
|
41
|
+
remove,
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function exactVersion(version) {
|
|
46
|
+
const match = typeof version === 'string' && version.match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/)
|
|
47
|
+
if (!match) return false
|
|
48
|
+
const prerelease = match[4]
|
|
49
|
+
return !prerelease || prerelease.split('.').every((part) => !/^\d+$/.test(part) || part === '0' || !part.startsWith('0'))
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function requestedVersion(spec, name) {
|
|
53
|
+
if (typeof spec !== 'string') return null
|
|
54
|
+
const prefix = `${name}@`
|
|
55
|
+
if (!spec.startsWith(prefix)) return null
|
|
56
|
+
const version = spec.slice(prefix.length)
|
|
57
|
+
return exactVersion(version) ? version : null
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function installedPackageVersion(spec) {
|
|
61
|
+
if (typeof spec !== 'string') return null
|
|
62
|
+
const separator = spec.startsWith('@') ? spec.lastIndexOf('@') : spec.indexOf('@')
|
|
63
|
+
if (separator <= 0 || separator === spec.length - 1) return null
|
|
64
|
+
const version = spec.slice(separator + 1)
|
|
65
|
+
return exactVersion(version) ? version : null
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function isInstalled(spec, desiredSpec, name) {
|
|
69
|
+
if (typeof spec !== 'string') return false
|
|
70
|
+
const version = installedPackageVersion(spec)
|
|
71
|
+
const desired = requestedVersion(desiredSpec, name)
|
|
72
|
+
if (version && desired) return version === desired
|
|
73
|
+
return spec === desiredSpec
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function parseVersion(version) {
|
|
77
|
+
const dash = version.indexOf('-')
|
|
78
|
+
const core = (dash === -1 ? version : version.slice(0, dash)).split('.').map(Number)
|
|
79
|
+
const pre = dash === -1 ? null : version.slice(dash + 1).split('.')
|
|
80
|
+
return { core, pre }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Semver precedence for exact pins (no build metadata). Returns -1, 0, or 1. */
|
|
84
|
+
export function compareVersions(a, b) {
|
|
85
|
+
const left = parseVersion(a)
|
|
86
|
+
const right = parseVersion(b)
|
|
87
|
+
for (let i = 0; i < 3; i += 1) {
|
|
88
|
+
if (left.core[i] !== right.core[i]) return left.core[i] < right.core[i] ? -1 : 1
|
|
89
|
+
}
|
|
90
|
+
if (left.pre === null && right.pre === null) return 0
|
|
91
|
+
if (left.pre === null) return 1
|
|
92
|
+
if (right.pre === null) return -1
|
|
93
|
+
const len = Math.max(left.pre.length, right.pre.length)
|
|
94
|
+
for (let i = 0; i < len; i += 1) {
|
|
95
|
+
const x = left.pre[i]
|
|
96
|
+
const y = right.pre[i]
|
|
97
|
+
if (x === undefined) return -1
|
|
98
|
+
if (y === undefined) return 1
|
|
99
|
+
const xNum = /^\d+$/.test(x)
|
|
100
|
+
const yNum = /^\d+$/.test(y)
|
|
101
|
+
if (xNum && yNum) {
|
|
102
|
+
const diff = Number(x) - Number(y)
|
|
103
|
+
if (diff !== 0) return diff < 0 ? -1 : 1
|
|
104
|
+
} else if (xNum !== yNum) {
|
|
105
|
+
return xNum ? -1 : 1
|
|
106
|
+
} else if (x !== y) {
|
|
107
|
+
return x < y ? -1 : 1
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return 0
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function planEnvironment({ manifest, platform = detectPlatform(), installed = {}, local = {}, dshVersion, allowUpgrade = false }) {
|
|
114
|
+
const normalized = normalizeEnvironmentManifest(manifest)
|
|
115
|
+
const actions = []
|
|
116
|
+
const skipped = []
|
|
117
|
+
for (const item of normalized.packages) {
|
|
118
|
+
// Machine-local development dependencies (link:/file:/path) are sacred:
|
|
119
|
+
// never replace them with registry versions, even with allowUpgrade=true.
|
|
120
|
+
if (Object.prototype.hasOwnProperty.call(local, item.name)) {
|
|
121
|
+
actions.push({ ...item, current: local[item.name], action: 'keep', local: true, destructive: false })
|
|
122
|
+
continue
|
|
123
|
+
}
|
|
124
|
+
if (!item.platforms.includes(platform)) {
|
|
125
|
+
skipped.push({ name: item.name, reason: 'unsupported-platform', platforms: item.platforms })
|
|
126
|
+
continue
|
|
127
|
+
}
|
|
128
|
+
const current = installed[item.name]
|
|
129
|
+
const action = current == null ? 'install' : isInstalled(current, item.spec, item.name) ? 'keep' : 'version-change'
|
|
130
|
+
const entry = { ...item, current: current ?? null, action, destructive: action === 'version-change' }
|
|
131
|
+
if (action === 'version-change') {
|
|
132
|
+
const from = installedPackageVersion(current)
|
|
133
|
+
const to = requestedVersion(item.spec, item.name)
|
|
134
|
+
entry.direction = from && to && compareVersions(to, from) > 0 ? 'upgrade' : 'downgrade'
|
|
135
|
+
}
|
|
136
|
+
actions.push(entry)
|
|
137
|
+
}
|
|
138
|
+
// Explicit removals: only installed registry packages, never machine-local dev links,
|
|
139
|
+
// and never anything the manifest did not name.
|
|
140
|
+
const removeBlockers = []
|
|
141
|
+
for (const name of normalized.remove) {
|
|
142
|
+
if (Object.prototype.hasOwnProperty.call(local, name)) {
|
|
143
|
+
removeBlockers.push(`Cannot remove machine-local development package ${name}`)
|
|
144
|
+
continue
|
|
145
|
+
}
|
|
146
|
+
if (normalized.packages.some((p) => p.name === name)) {
|
|
147
|
+
removeBlockers.push(`${name} cannot be both installed and removed`)
|
|
148
|
+
continue
|
|
149
|
+
}
|
|
150
|
+
const current = installed[name]
|
|
151
|
+
if (current == null) {
|
|
152
|
+
skipped.push({ name, reason: 'not-installed', action: 'remove' })
|
|
153
|
+
continue
|
|
154
|
+
}
|
|
155
|
+
actions.push({ name, current, action: 'remove', destructive: true })
|
|
156
|
+
}
|
|
157
|
+
const invalidPackages = normalized.packages.filter((item) => {
|
|
158
|
+
if (!item.spec.startsWith(`${item.name}@`)) return true
|
|
159
|
+
return !requestedVersion(item.spec, item.name)
|
|
160
|
+
}).map((item) => item.name)
|
|
161
|
+
const requiredDsh = normalized.dsh.version || null
|
|
162
|
+
const dshMismatch = Boolean(requiredDsh && dshVersion && requiredDsh !== dshVersion)
|
|
163
|
+
const missingDshVersion = Boolean(requiredDsh && !dshVersion)
|
|
164
|
+
const unsupportedRequired = platform === 'unsupported' && normalized.packages.some((p) => p.required)
|
|
165
|
+
return {
|
|
166
|
+
manifest: normalized,
|
|
167
|
+
platform,
|
|
168
|
+
dsh: { required: requiredDsh, current: dshVersion ?? null, mismatch: dshMismatch },
|
|
169
|
+
actions,
|
|
170
|
+
skipped,
|
|
171
|
+
localPackages: Object.entries(local).map(([name, spec]) => ({ name, spec })),
|
|
172
|
+
ready: !unsupportedRequired && !invalidPackages.length && !dshMismatch && !missingDshVersion && !removeBlockers.length && !actions.some((a) => a.action === 'version-change' && !allowUpgrade),
|
|
173
|
+
blockers: [
|
|
174
|
+
...(unsupportedRequired ? ['Unsupported operating system'] : []),
|
|
175
|
+
...invalidPackages.map((name) => `${name} must use an exact package@version registry spec`),
|
|
176
|
+
...(dshMismatch ? [`DSH ${requiredDsh} required, found ${dshVersion}`] : []),
|
|
177
|
+
...(missingDshVersion ? [`Cannot verify required DSH version ${requiredDsh}`] : []),
|
|
178
|
+
...removeBlockers,
|
|
179
|
+
...actions.filter((a) => a.action === 'version-change' && !allowUpgrade).map((a) => `${a.name} requires an explicit version change confirmation`),
|
|
180
|
+
],
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function createEnvironmentManifest({ name, dshVersion, packages, bundles = [], platform = detectPlatform() }) {
|
|
185
|
+
if (!Array.isArray(packages)) throw new TypeError('packages must be an array')
|
|
186
|
+
return normalizeEnvironmentManifest({
|
|
187
|
+
schemaVersion: 1,
|
|
188
|
+
name: name || 'Exported DSH profile',
|
|
189
|
+
dsh: dshVersion ? { version: dshVersion } : {},
|
|
190
|
+
packages: packages.map((p) => ({
|
|
191
|
+
name: p.name,
|
|
192
|
+
spec: p.spec,
|
|
193
|
+
platforms: p.platforms || ['windows', 'macos', 'linux'],
|
|
194
|
+
required: p.required !== false,
|
|
195
|
+
})),
|
|
196
|
+
bundles,
|
|
197
|
+
})
|
|
198
|
+
}
|
package/lib/jobs.mjs
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* In-memory job engine for the setup wizard. A scan produces a plan; an apply
|
|
5
|
+
* consumes a completed scan (server-side consent binding) and reports per-item
|
|
6
|
+
* progress. Jobs launch asynchronously and are polled by id; only one apply runs
|
|
7
|
+
* at a time. Jobs are pruned to the last `maxJobs`.
|
|
8
|
+
*/
|
|
9
|
+
export function createJobEngine({ runScan, runApply, cancelInstall, maxJobs = 20 }) {
|
|
10
|
+
const jobs = new Map()
|
|
11
|
+
const order = []
|
|
12
|
+
let running = null
|
|
13
|
+
|
|
14
|
+
function remember(job) {
|
|
15
|
+
jobs.set(job.id, job)
|
|
16
|
+
order.push(job.id)
|
|
17
|
+
while (order.length > maxJobs) jobs.delete(order.shift())
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function publicJob(job) {
|
|
21
|
+
return job ? { ...job, items: job.items ? { ...job.items } : undefined } : null
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function get(id) { return publicJob(jobs.get(id)) }
|
|
25
|
+
function list() { return order.map((id) => publicJob(jobs.get(id))).filter(Boolean) }
|
|
26
|
+
|
|
27
|
+
function startScan(opts = {}) {
|
|
28
|
+
const job = { id: randomUUID(), kind: 'scan', status: 'running', phase: 'scanning', percent: 0, createdAt: Date.now() }
|
|
29
|
+
remember(job)
|
|
30
|
+
;(async () => {
|
|
31
|
+
try {
|
|
32
|
+
const plan = await runScan(opts)
|
|
33
|
+
job.plan = plan
|
|
34
|
+
job.status = 'done'
|
|
35
|
+
job.phase = 'ready'
|
|
36
|
+
job.percent = 100
|
|
37
|
+
job.finishedAt = Date.now()
|
|
38
|
+
} catch (error) {
|
|
39
|
+
job.status = 'failed'
|
|
40
|
+
job.phase = 'error'
|
|
41
|
+
job.error = String(error?.message || error)
|
|
42
|
+
job.finishedAt = Date.now()
|
|
43
|
+
}
|
|
44
|
+
})()
|
|
45
|
+
return publicJob(job)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function startApply({ scanId, allowVersionChange = true, exclude = [] } = {}) {
|
|
49
|
+
const scan = jobs.get(scanId)
|
|
50
|
+
if (!scan || scan.kind !== 'scan' || scan.status !== 'done' || !scan.plan) {
|
|
51
|
+
throw new Error('A completed scan is required before applying')
|
|
52
|
+
}
|
|
53
|
+
if (running) throw new Error('Another apply is already running')
|
|
54
|
+
const plan = scan.plan
|
|
55
|
+
const excluded = new Set(Array.isArray(exclude) ? exclude : [])
|
|
56
|
+
const filteredPlan = { ...plan, actions: plan.actions.filter((a) => a.action === 'keep' || !excluded.has(a.name)) }
|
|
57
|
+
const actionable = filteredPlan.actions.filter((a) => a.action !== 'keep')
|
|
58
|
+
const total = Math.max(1, actionable.length + (plan.manifest?.bundles?.length || 0))
|
|
59
|
+
const items = {}
|
|
60
|
+
for (const a of actionable) items[a.name] = { name: a.name, action: a.action, state: 'pending', phase: null }
|
|
61
|
+
const requestId = randomUUID()
|
|
62
|
+
const job = {
|
|
63
|
+
id: randomUUID(), kind: 'apply', status: 'running', phase: 'preparing', percent: 0,
|
|
64
|
+
createdAt: Date.now(), scanId, requestId, items, total, completed: 0, allowVersionChange, exclude: [...excluded],
|
|
65
|
+
}
|
|
66
|
+
remember(job)
|
|
67
|
+
running = { jobId: job.id, requestId }
|
|
68
|
+
let completed = 0
|
|
69
|
+
const onProgress = (ev) => {
|
|
70
|
+
const it = items[ev.name] || (items[ev.name] = { name: ev.name, action: ev.action, state: 'pending' })
|
|
71
|
+
if (ev.action) it.action = ev.action
|
|
72
|
+
it.state = ev.state
|
|
73
|
+
it.phase = ev.phase ?? null
|
|
74
|
+
if (ev.error) it.error = ev.error
|
|
75
|
+
if (ev.application) it.application = ev.application
|
|
76
|
+
if (ev.state === 'done' || ev.state === 'failed') {
|
|
77
|
+
completed += 1
|
|
78
|
+
job.completed = completed
|
|
79
|
+
job.percent = Math.min(99, Math.round((completed / total) * 100))
|
|
80
|
+
}
|
|
81
|
+
if (ev.state === 'running') job.phase = ev.phase || 'working'
|
|
82
|
+
}
|
|
83
|
+
;(async () => {
|
|
84
|
+
try {
|
|
85
|
+
const results = await runApply(filteredPlan, { onProgress, requestId, allowVersionChange })
|
|
86
|
+
job.results = results
|
|
87
|
+
const ok = results.every((r) => r.ok)
|
|
88
|
+
job.ok = ok
|
|
89
|
+
job.status = ok ? 'done' : 'failed'
|
|
90
|
+
job.phase = ok ? 'done' : 'error'
|
|
91
|
+
job.percent = 100
|
|
92
|
+
job.restartRequired = results.some((r) => r.application === 'restart-required')
|
|
93
|
+
job.finishedAt = Date.now()
|
|
94
|
+
} catch (error) {
|
|
95
|
+
job.ok = false
|
|
96
|
+
job.status = 'failed'
|
|
97
|
+
job.phase = 'error'
|
|
98
|
+
job.error = String(error?.message || error)
|
|
99
|
+
job.percent = 100
|
|
100
|
+
job.finishedAt = Date.now()
|
|
101
|
+
} finally {
|
|
102
|
+
running = null
|
|
103
|
+
}
|
|
104
|
+
})()
|
|
105
|
+
return publicJob(job)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function cancel(jobId) {
|
|
109
|
+
const job = jobs.get(jobId)
|
|
110
|
+
if (!job || job.kind !== 'apply' || job.status !== 'running' || !cancelInstall) return { status: 'not-running' }
|
|
111
|
+
const result = await cancelInstall(job.requestId)
|
|
112
|
+
return result || { status: 'not-running' }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return { startScan, startApply, cancel, get, list, isRunning: () => Boolean(running) }
|
|
116
|
+
}
|