@capyclaw/capyclaw 0.2.0 → 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 CHANGED
@@ -2,10 +2,23 @@
2
2
 
3
3
  CapyClaw helps set up or migrate a DSH profile across Windows, macOS, and Linux. The published starter manifest contains only portable registry package specs; machine-specific `link:` paths and profile directories are never shipped as defaults.
4
4
 
5
+ ## Setup wizard (GUI)
6
+
7
+ After the plugin is installed and the GUI loads, CapyClaw runs a first-run wizard:
8
+
9
+ 1. **Scanning** — a loading overlay shows “Scanning your environment” while the host detects the OS and builds an install/update/remove plan.
10
+ 2. **Consent** — a dialog lists exactly what will be installed, updated (upgrade/downgrade), or removed. Each item has a checkbox; nothing is applied until you click **Agree & install**. You can dismiss without applying.
11
+ 3. **Progress** — after consent, a panel shows what is being downloaded/installed/removed, a per-item status list, and an overall progress bar. You can cancel a running apply.
12
+
13
+ The wizard is a React component in the `shell.overlay` slot plus a launcher button in `conversation.composer.dock`, so it can be reopened any time. It talks to host routes under `/capyclaw/environment/api/` (state, scan, jobs, apply, cancel, dismiss). Consent is a user action only; the agent cannot click it for you. First-run auto-open happens once per profile (tracked in a plugin-owned marker file); later runs reopen via the dock button.
14
+
15
+ The wizard is optional infrastructure: if the host has no web server (tools-only profile), the plugin still registers all agent tools and simply skips the GUI routes.
16
+
5
17
  ## Tools
6
18
 
7
19
  - `capyclaw_manifest`: read the portable starter manifest.
8
20
  - `capyclaw_status`: detect the host OS and preview the starter or imported manifest without changing the profile.
21
+ - `capyclaw_setup`: read-only scan that returns the install/update/remove plan plus wizard metadata (used by the GUI and by agents to preview setup).
9
22
  - `capyclaw_export_environment`: export the current profile's registry dependencies and enabled bundles to JSON. Local links are omitted because their paths cannot be migrated safely.
10
23
  - `capyclaw_sync`: preview by default; with `apply=true`, install planned packages using DSH `pluginManager`, enable selected bundles, back up the profile package manifest, and rescan the result.
11
24
 
@@ -13,11 +26,16 @@ CapyClaw helps set up or migrate a DSH profile across Windows, macOS, and Linux.
13
26
 
14
27
  - The plugin uses the host package manager; it does not write profile dependencies directly or invoke npm/pnpm itself.
15
28
  - Existing profile packages not named by the selected manifest are left alone.
16
- - Changing an installed package version (upgrade or downgrade) is blocked unless `allowUpgrade=true`. Review the returned plan before applying.
29
+ - Changing an installed package version (upgrade or downgrade) is blocked unless `allowUpgrade=true`. Review the returned plan before applying. Upgrades use the native `updateBundle`; downgrades use `removeBundle` + `installBundle`; explicit removals use `removeBundle`.
30
+ - A manifest may declare an optional `remove` array of package names. Only installed registry packages named there are removed; a name that is also being installed is rejected, and machine-local packages can never be removed.
17
31
  - Imported manifests must use schema version 1 and exact `name@version` registry specs. A package may declare `platforms` as any subset of `windows`, `macos`, and `linux`; local links are intentionally not migrated. Starter entries are all optional and currently form a curated set, not a complete default installation profile.
32
+ - Machine-local profile dependencies (`link:`, `file:`, path specs) are never exported as registry pins and are **never replaced during apply** — they are kept as-is (`action: "keep", local: true`) even with `allowUpgrade=true`, so local development checkouts cannot be overwritten by older registry versions.
33
+ - Registry installs intentionally omit the manager's strict `expected` guard: that guard rejects an install whenever pnpm touches any other direct dependency, which false-positives (`unexpected-package`) on development profiles full of `file:`/`link:` deps. `installBundle`'s own after-read still requires exactly one new, compatible bundle, and the planner's exact pins plus `saveExact` keep the installed version deterministic.
18
34
  - A profile `package.json` backup is made before apply when available. Package install rollback is not automatic; restore the returned backup manually if migration does not pass verification.
19
35
  - DSH runtime installation/upgrades remain the responsibility of the DSH installer. CapyClaw reports version constraints and never replaces the running DSH executable.
20
36
 
21
37
  ## Tests
22
38
 
23
- Run `npm test` from this directory. The pure environment planner tests simulate Windows, macOS, and Linux without mutating a DSH profile.
39
+ Run `npm test` from this directory. The pure environment planner tests simulate Windows, macOS, and Linux without mutating a DSH profile. `test/stability.test.mjs` adds a stability suite: fuzzed manifests (300 seeded cases), version/platform edge cases, idempotent apply, concurrent tool calls, 500 apply/dispose leak cycles, and export robustness against corrupt or machine-local profiles. `test/wizard.test.mjs` covers the version comparator, removal planning, native upgrade/downgrade/remove executor paths, the job engine (consent binding, progress, exclusion, single-running guard, cancel, pruning), the wizard HTTP routes, and the client slot registration.
40
+
41
+ For a real-host end-to-end check, run `node scripts/sandbox/verify-capyclaw-dsh.mjs` from the repository root with `DSH_CLI` pointing at an installed dsh CLI. It packs the current source, boots a disposable `DSH_HOME`, and asserts activation, OS detection, preview-only behavior, the wizard API (scan → consent-bound apply → progress), and clean shutdown. It never touches your real profile. Set `CAPYCLAW_STRESS=1` to additionally run 300 sequential + 120 concurrent tool calls and 10 byte-compare exports inside that isolated host. The headless CLI provides no `webServer` (that service belongs to the web/desktop GUI host), so the probe supplies a contract-faithful `webServer` shim backed by a real loopback HTTP server; this proves route registration and real HTTP transport, not desktop GUI rendering. Set `CAPYCLAW_LIVE=1` to additionally exercise a real registry install → upgrade → remove of a clean-peer bundle (`billion-context`) inside that isolated host, asserting the on-disk version at each step (network required; never touches your real profile).
@@ -0,0 +1,273 @@
1
+ /* CapyClaw environment setup wizard.
2
+ * Scan -> user consent -> live progress. Rendered in host slots; no external
3
+ * client packages, no DOM outside the component, theme tokens only. */
4
+ window.__ModuleLoader__.load({
5
+ id: '@capyclaw/capyclaw',
6
+ factory(require) {
7
+ const React = require('react')
8
+ const { useState, useEffect, useRef, useCallback } = React
9
+ const h = React.createElement
10
+ const API = '/capyclaw/environment/api/'
11
+
12
+ const STRINGS = {
13
+ zh: {
14
+ dock: '环境装配', scanning: '正在扫描环境…', scanningHint: '正在识别操作系统并比对当前 profile 与目标环境。',
15
+ consentTitle: '确认环境变更', consentHint: '以下是即将执行的变更。勾选要执行的项目,然后确认。',
16
+ install: '安装', upgrade: '升级', downgrade: '降级', remove: '卸载', keep: '保留', enable: '启用',
17
+ local: '本地开发链接(受保护,不会被替换)', skipped: '跳过', blockers: '无法继续',
18
+ confirm: '同意并安装', cancel: '取消', close: '关闭', dismiss: '暂不设置',
19
+ applying: '正在装配环境…', progress: '进度', done: '环境装配完成', failed: '装配未完全成功',
20
+ restart: '部分变更需要重启 DSH 后生效。', pending: '等待中', installing: '正在下载并安装', updating: '正在升级',
21
+ replacing: '正在替换版本', removing: '正在卸载', enabling: '正在启用', working: '处理中',
22
+ nothing: '当前环境已与目标一致,无需变更。', selectAll: '全选', allowChanges: '允许版本变更',
23
+ error: '错误', retry: '重新扫描', stateDownload: '正在下载并安装',
24
+ },
25
+ en: {
26
+ dock: 'Environment', scanning: 'Scanning environment…', scanningHint: 'Detecting the OS and comparing this profile with the target environment.',
27
+ consentTitle: 'Confirm environment changes', consentHint: 'These changes are about to run. Select the items to execute, then confirm.',
28
+ install: 'Install', upgrade: 'Upgrade', downgrade: 'Downgrade', remove: 'Remove', keep: 'Keep', enable: 'Enable',
29
+ local: 'Local dev link (protected, never replaced)', skipped: 'Skipped', blockers: 'Cannot proceed',
30
+ confirm: 'Agree & install', cancel: 'Cancel', close: 'Close', dismiss: 'Not now',
31
+ applying: 'Setting up environment…', progress: 'Progress', done: 'Environment setup complete', failed: 'Setup did not fully succeed',
32
+ restart: 'Some changes require a DSH restart to take effect.', pending: 'Pending', installing: 'Downloading & installing', updating: 'Upgrading',
33
+ replacing: 'Replacing version', removing: 'Removing', enabling: 'Enabling', working: 'Working',
34
+ nothing: 'This profile already matches the target. Nothing to change.', selectAll: 'Select all', allowChanges: 'Allow version changes',
35
+ error: 'Error', retry: 'Rescan', stateDownload: 'Downloading & installing',
36
+ },
37
+ }
38
+
39
+ const openSubs = new Set()
40
+ function requestOpen() { for (const fn of openSubs) { try { fn() } catch { /* subscriber gone */ } } }
41
+
42
+ async function api(route, opts) {
43
+ const res = await fetch(location.origin + API + route, opts)
44
+ return res.json()
45
+ }
46
+ const post = (route, body) => api(route, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body || {}) })
47
+
48
+ function actionLabel(t, action, direction) {
49
+ if (action === 'version-change') return direction === 'downgrade' ? t.downgrade : t.upgrade
50
+ return t[action] || action
51
+ }
52
+ function phaseLabel(t, phase) {
53
+ return ({ installing: t.installing, updating: t.updating, replacing: t.replacing, removing: t.removing, enabling: t.enabling })[phase] || t.working
54
+ }
55
+
56
+ const css = `
57
+ .cenv-root{position:fixed;inset:0;z-index:1200;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.45);pointer-events:auto;font-family:inherit}
58
+ .cenv-card{width:min(560px,92vw);max-height:82vh;display:flex;flex-direction:column;background:var(--dsw-alias-bg-base,#fff);color:var(--dsw-alias-label-primary,#1f2329);border:1px solid var(--dsw-alias-border,#e5e6eb);border-radius:12px;box-shadow:0 12px 40px rgba(0,0,0,.18);overflow:hidden}
59
+ .cenv-head{display:flex;align-items:center;justify-content:space-between;padding:16px 20px;border-bottom:1px solid var(--dsw-alias-border,#e5e6eb)}
60
+ .cenv-title{font-size:15px;font-weight:600}
61
+ .cenv-x{border:none;background:transparent;color:var(--dsw-alias-label-secondary,#86909c);font-size:18px;cursor:pointer;line-height:1}
62
+ .cenv-body{padding:16px 20px;overflow:auto}
63
+ .cenv-hint{font-size:12px;color:var(--dsw-alias-label-secondary,#86909c);margin:0 0 12px}
64
+ .cenv-row{display:flex;align-items:center;gap:10px;padding:8px 10px;border:1px solid var(--dsw-alias-border,#e5e6eb);border-radius:8px;margin-bottom:8px;font-size:13px}
65
+ .cenv-row input{accent-color:var(--dsw-alias-primary,#3370ff)}
66
+ .cenv-badge{font-size:11px;padding:2px 8px;border-radius:10px;background:var(--dsw-alias-fill-secondary,#f2f3f5);color:var(--dsw-alias-label-secondary,#86909c);white-space:nowrap}
67
+ .cenv-badge.install{background:#e8f3ff;color:#3370ff}
68
+ .cenv-badge.remove{background:#ffece8;color:#f53f3f}
69
+ .cenv-badge.version-change{background:#fff7e8;color:#ff7d00}
70
+ .cenv-name{flex:1;word-break:break-all}
71
+ .cenv-spec{color:var(--dsw-alias-label-secondary,#86909c);font-size:11px}
72
+ .cenv-foot{display:flex;align-items:center;justify-content:flex-end;gap:10px;padding:14px 20px;border-top:1px solid var(--dsw-alias-border,#e5e6eb)}
73
+ .cenv-btn{border:1px solid var(--dsw-alias-border,#e5e6eb);background:var(--dsw-alias-bg-base,#fff);color:var(--dsw-alias-label-primary,#1f2329);border-radius:8px;padding:7px 16px;font-size:13px;cursor:pointer}
74
+ .cenv-btn.primary{background:var(--dsw-alias-primary,#3370ff);border-color:var(--dsw-alias-primary,#3370ff);color:#fff}
75
+ .cenv-btn:disabled{opacity:.5;cursor:not-allowed}
76
+ .cenv-bar{height:8px;border-radius:4px;background:var(--dsw-alias-fill-secondary,#f2f3f5);overflow:hidden;margin:10px 0}
77
+ .cenv-bar>div{height:100%;background:var(--dsw-alias-primary,#3370ff);transition:width .3s}
78
+ .cenv-spin{width:28px;height:28px;border:3px solid var(--dsw-alias-fill-secondary,#f2f3f5);border-top-color:var(--dsw-alias-primary,#3370ff);border-radius:50%;animation:cenv-spin 1s linear infinite;margin:8px auto}
79
+ @keyframes cenv-spin{to{transform:rotate(360deg)}}
80
+ .cenv-center{text-align:center;padding:20px 0}
81
+ .cenv-block{background:#ffece8;color:#f53f3f;border-radius:8px;padding:10px 12px;font-size:12px;margin-bottom:10px}
82
+ .cenv-note{font-size:12px;color:var(--dsw-alias-label-secondary,#86909c);margin-top:8px}
83
+ .cenv-state{font-size:11px;color:var(--dsw-alias-label-secondary,#86909c);white-space:nowrap}
84
+ .cenv-state.failed{color:#f53f3f}
85
+ .cenv-state.done{color:#00b42a}
86
+ .cenv-dock{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--dsw-alias-border,#e5e6eb);background:var(--dsw-alias-bg-base,#fff);color:var(--dsw-alias-label-secondary,#86909c);border-radius:8px;padding:4px 10px;font-size:12px;cursor:pointer}
87
+ .cenv-dock:hover{color:var(--dsw-alias-primary,#3370ff);border-color:var(--dsw-alias-primary,#3370ff)}
88
+ `
89
+
90
+ function Wizard() {
91
+ const lang = (typeof navigator !== 'undefined' && /^zh/i.test(navigator.language || '')) ? 'zh' : 'en'
92
+ const t = STRINGS[lang]
93
+ const [phase, setPhase] = useState('hidden')
94
+ const [job, setJob] = useState(null)
95
+ const [selected, setSelected] = useState({})
96
+ const [error, setError] = useState(null)
97
+ const pollRef = useRef(null)
98
+ const cardRef = useRef(null)
99
+
100
+ const stopPoll = useCallback(() => { if (pollRef.current) { clearInterval(pollRef.current); pollRef.current = null } }, [])
101
+
102
+ const beginScan = useCallback(async () => {
103
+ setError(null); setJob(null); setPhase('scanning')
104
+ try {
105
+ const res = await post('scan', {})
106
+ if (!res.ok) throw new Error(res.error || 'scan failed')
107
+ const id = res.job.id
108
+ stopPoll()
109
+ pollRef.current = setInterval(async () => {
110
+ try {
111
+ const r = await api('jobs/' + id)
112
+ if (!r.ok) return
113
+ setJob(r.job)
114
+ if (r.job.status === 'done') {
115
+ stopPoll()
116
+ const actions = r.job.plan?.actions || []
117
+ const sel = {}
118
+ for (const a of actions) if (a.action !== 'keep') sel[a.name] = true
119
+ setSelected(sel)
120
+ setPhase('consent')
121
+ } else if (r.job.status === 'failed') {
122
+ stopPoll(); setError(r.job.error || 'scan failed'); setPhase('consent')
123
+ }
124
+ } catch { /* transient poll error; keep trying */ }
125
+ }, 600)
126
+ } catch (e) { setError(String(e?.message || e)); setPhase('consent') }
127
+ }, [stopPoll])
128
+
129
+ useEffect(() => {
130
+ const handler = () => { beginScan() }
131
+ openSubs.add(handler)
132
+ let cancelled = false
133
+ api('state').then((s) => { if (!cancelled && s.ok && !s.onboarded && !s.running) beginScan() }).catch(() => {})
134
+ return () => { cancelled = true; openSubs.delete(handler); stopPoll() }
135
+ }, [beginScan, stopPoll])
136
+
137
+ const dismiss = useCallback(async () => {
138
+ stopPoll()
139
+ if (phase === 'consent' || phase === 'scanning') { try { await post('dismiss', {}) } catch { /* best effort */ } }
140
+ setPhase('hidden'); setJob(null); setError(null)
141
+ }, [phase, stopPoll])
142
+
143
+ useEffect(() => {
144
+ if (phase === 'hidden') return
145
+ const onKey = (e) => { if (e.key === 'Escape') dismiss() }
146
+ window.addEventListener('keydown', onKey)
147
+ if (cardRef.current) cardRef.current.focus()
148
+ return () => window.removeEventListener('keydown', onKey)
149
+ }, [phase, dismiss])
150
+
151
+ const startApply = useCallback(async () => {
152
+ const plan = job?.plan
153
+ if (!plan) return
154
+ const exclude = (plan.actions || []).filter((a) => a.action !== 'keep' && !selected[a.name]).map((a) => a.name)
155
+ setPhase('applying'); setError(null)
156
+ try {
157
+ const res = await post('apply', { scanId: job.id, exclude, allowVersionChange: true })
158
+ if (!res.ok) throw new Error(res.error || 'apply failed')
159
+ const id = res.job.id
160
+ stopPoll()
161
+ pollRef.current = setInterval(async () => {
162
+ try {
163
+ const r = await api('jobs/' + id)
164
+ if (!r.ok) return
165
+ setJob(r.job)
166
+ if (r.job.status === 'done' || r.job.status === 'failed') { stopPoll(); setPhase('result') }
167
+ } catch { /* keep polling */ }
168
+ }, 700)
169
+ } catch (e) { setError(String(e?.message || e)); setPhase('result') }
170
+ }, [job, selected, stopPoll])
171
+
172
+ const cancelApply = useCallback(async () => {
173
+ if (job?.id) { try { await post('cancel', { jobId: job.id }) } catch { /* best effort */ } }
174
+ }, [job])
175
+
176
+ if (phase === 'hidden') return null
177
+
178
+ const plan = job?.plan
179
+ const actionable = (plan?.actions || []).filter((a) => a.action !== 'keep')
180
+ const localItems = (plan?.actions || []).filter((a) => a.action === 'keep' && a.local)
181
+ const blockers = plan?.blockers || []
182
+ const selectedCount = actionable.filter((a) => selected[a.name]).length
183
+ const canApply = plan && plan.ready && blockers.length === 0 && selectedCount > 0 && !error
184
+
185
+ const rows = []
186
+ if (phase === 'consent' && plan) {
187
+ for (const a of actionable) {
188
+ rows.push(h('label', { className: 'cenv-row', key: a.name },
189
+ h('input', { type: 'checkbox', checked: Boolean(selected[a.name]), onChange: (e) => setSelected((s) => ({ ...s, [a.name]: e.target.checked })) }),
190
+ h('span', { className: 'cenv-badge ' + a.action }, actionLabel(t, a.action, a.direction)),
191
+ h('span', { className: 'cenv-name' }, a.name, a.spec ? h('span', { className: 'cenv-spec' }, ' ' + a.spec) : null),
192
+ ))
193
+ }
194
+ for (const a of localItems) {
195
+ rows.push(h('div', { className: 'cenv-row', key: 'local-' + a.name },
196
+ h('span', { className: 'cenv-badge' }, t.keep),
197
+ h('span', { className: 'cenv-name' }, a.name, h('span', { className: 'cenv-spec' }, ' ' + t.local)),
198
+ ))
199
+ }
200
+ }
201
+
202
+ let body
203
+ if (phase === 'scanning') {
204
+ body = h('div', { className: 'cenv-center' }, h('div', { className: 'cenv-spin' }), h('div', null, t.scanning), h('p', { className: 'cenv-hint' }, t.scanningHint))
205
+ } else if (phase === 'consent') {
206
+ body = h('div', null,
207
+ h('p', { className: 'cenv-hint' }, t.consentHint),
208
+ error ? h('div', { className: 'cenv-block' }, t.error + ': ' + error) : null,
209
+ blockers.length ? h('div', { className: 'cenv-block' }, t.blockers + ': ' + blockers.join('; ')) : null,
210
+ actionable.length === 0 && !error ? h('div', { className: 'cenv-note' }, t.nothing) : null,
211
+ rows,
212
+ )
213
+ } else if (phase === 'applying') {
214
+ const items = job?.items || {}
215
+ body = h('div', null,
216
+ h('div', null, t.applying),
217
+ h('div', { className: 'cenv-bar' }, h('div', { style: { width: (job?.percent || 0) + '%' } })),
218
+ h('div', { className: 'cenv-hint' }, t.progress + ': ' + (job?.percent || 0) + '%'),
219
+ Object.values(items).map((it) => h('div', { className: 'cenv-row', key: it.name },
220
+ h('span', { className: 'cenv-badge ' + it.action }, actionLabel(t, it.action)),
221
+ h('span', { className: 'cenv-name' }, it.name),
222
+ h('span', { className: 'cenv-state ' + it.state }, it.state === 'running' ? phaseLabel(t, it.phase) : it.state === 'done' ? '✓' : it.state === 'failed' ? '✗ ' + (it.error || '') : t.pending),
223
+ )),
224
+ )
225
+ } else if (phase === 'result') {
226
+ const ok = job?.ok
227
+ const failedResults = (job?.results || []).filter((r) => !r.ok)
228
+ body = h('div', null,
229
+ h('div', { className: 'cenv-title', style: { marginBottom: 8 } }, ok ? t.done : t.failed),
230
+ error ? h('div', { className: 'cenv-block' }, t.error + ': ' + error) : null,
231
+ job?.restartRequired ? h('div', { className: 'cenv-note' }, t.restart) : null,
232
+ failedResults.map((r) => h('div', { className: 'cenv-block', key: r.name }, r.name + ': ' + (typeof r.error === 'string' ? r.error : JSON.stringify(r.error)))),
233
+ )
234
+ }
235
+
236
+ const footer = phase === 'consent'
237
+ ? h('div', { className: 'cenv-foot' },
238
+ h('button', { className: 'cenv-btn', onClick: dismiss }, t.dismiss),
239
+ h('button', { className: 'cenv-btn primary', disabled: !canApply, onClick: startApply }, t.confirm))
240
+ : phase === 'applying'
241
+ ? h('div', { className: 'cenv-foot' }, h('button', { className: 'cenv-btn', onClick: cancelApply }, t.cancel))
242
+ : phase === 'result'
243
+ ? h('div', { className: 'cenv-foot' },
244
+ h('button', { className: 'cenv-btn', onClick: beginScan }, t.retry),
245
+ h('button', { className: 'cenv-btn primary', onClick: dismiss }, t.close))
246
+ : null
247
+
248
+ return h('div', { className: 'cenv-root' },
249
+ h('style', null, css),
250
+ h('div', { className: 'cenv-card', ref: cardRef, tabIndex: -1, role: 'dialog', 'aria-modal': true },
251
+ h('div', { className: 'cenv-head' },
252
+ h('span', { className: 'cenv-title' }, phase === 'consent' ? t.consentTitle : phase === 'result' ? (job?.ok ? t.done : t.failed) : t.scanning),
253
+ h('button', { className: 'cenv-x', onClick: dismiss, 'aria-label': t.close }, '×')),
254
+ h('div', { className: 'cenv-body' }, body),
255
+ footer,
256
+ ))
257
+ }
258
+
259
+ function DockButton() {
260
+ const lang = (typeof navigator !== 'undefined' && /^zh/i.test(navigator.language || '')) ? 'zh' : 'en'
261
+ const t = STRINGS[lang]
262
+ return h('button', { className: 'cenv-dock', onClick: requestOpen, title: t.dock }, '⚙ ', t.dock)
263
+ }
264
+
265
+ return {
266
+ inject: ['slots'],
267
+ apply(ctx) {
268
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({ name: 'shell.overlay', id: 'capyclaw-env-wizard', order: 80 }, Wizard))
269
+ ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register({ name: 'conversation.composer.dock', id: 'capyclaw-env-dock', order: 60 }, DockButton))
270
+ },
271
+ }
272
+ },
273
+ })
package/index.js CHANGED
@@ -2,6 +2,7 @@ import fs from 'node:fs'
2
2
  import path from 'node:path'
3
3
  import { MANIFEST } from './manifest.js'
4
4
  import { createEnvironmentManifest, detectPlatform, normalizeEnvironmentManifest, planEnvironment } from './lib/environment.mjs'
5
+ import { createJobEngine } from './lib/jobs.mjs'
5
6
 
6
7
  export const name = '@capyclaw/capyclaw'
7
8
  export const inject = ['pluginManager', 'tools', 'profileContext']
@@ -37,15 +38,16 @@ async function readInstalled(ctx) {
37
38
  const profile = dir ? readJson(path.join(dir, 'package.json')) : null
38
39
  const deps = profile?.dependencies || {}
39
40
  const installed = {}
41
+ const local = {}
40
42
  for (const [packageName, spec] of Object.entries(deps)) {
41
- if (!isRegistrySpec(spec)) { installed[packageName] = null; continue }
43
+ if (!isRegistrySpec(spec)) { installed[packageName] = null; local[packageName] = String(spec); continue }
42
44
  const pkgPath = dir ? path.join(dir, 'node_modules', packageName, 'package.json') : null
43
45
  const pkg = pkgPath ? readJson(pkgPath) : null
44
46
  installed[packageName] = pkg?.version ? `${packageName}@${pkg.version}` : null
45
47
  }
46
48
  let bundles = []
47
49
  try { bundles = await ctx.pluginManager.listBundles() } catch { /* report bundle inventory unavailable below */ }
48
- return { installed, bundles }
50
+ return { installed, bundles, local }
49
51
  }
50
52
 
51
53
  function readImport(file) {
@@ -55,50 +57,229 @@ function readImport(file) {
55
57
  }
56
58
 
57
59
  async function inspect(ctx, manifest = MANIFEST, options = {}) {
58
- const { installed, bundles } = await readInstalled(ctx)
60
+ const { installed, bundles, local } = await readInstalled(ctx)
59
61
  const plan = planEnvironment({
60
62
  manifest,
61
63
  platform: options.platform || detectPlatform(),
62
64
  installed,
65
+ local,
63
66
  dshVersion: dshVersion(ctx),
64
67
  allowUpgrade: options.allowUpgrade === true,
65
68
  })
66
69
  return { ...plan, installedBundles: bundles.map(({ name, enabled }) => ({ name, enabled })) }
67
70
  }
68
71
 
69
- export async function executeEnvironmentPlan(ctx, plan) {
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 } = {}) {
70
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 })
71
160
  for (const item of plan.actions) {
72
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 })
73
166
  try {
74
- const version = item.spec.startsWith(`${item.name}@`) ? item.spec.slice(item.name.length + 1) : undefined
75
- const result = await ctx.pluginManager.installBundle(item.spec, {
76
- saveExact: true,
77
- expected: { name: item.name, ...(version ? { version } : {}) },
78
- })
79
- results.push({ name: item.name, action: item.action, application: result.application, ok: result.application !== 'failed', error: result.error || null })
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 })
80
186
  } catch (error) {
81
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) })
82
189
  }
83
190
  }
84
- const installedBundles = await ctx.pluginManager.listBundles()
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
+ }
85
196
  const enabledNames = new Set(installedBundles.filter((item) => item.enabled).map((item) => item.name))
86
197
  for (const bundle of plan.manifest.bundles) {
87
198
  if (enabledNames.has(bundle)) continue
199
+ emit({ name: bundle, action: 'enable', state: 'running', phase: 'enabling' })
88
200
  try {
89
- const result = await ctx.pluginManager.setBundleEnabled(bundle, true)
90
- results.push({ name: bundle, action: 'enable', application: result.application, ok: result.application !== 'failed', error: result.error || null })
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 })
91
205
  } catch (error) {
92
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) })
93
208
  }
94
209
  }
95
210
  return results
96
211
  }
97
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
+
98
232
  export function apply(ctx) {
99
233
  const disposers = []
100
234
  const register = (definition) => disposers.push(ctx.tools.register({ output: { schema: outputSchema, render }, ...definition }))
101
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
+
102
283
  register({
103
284
  name: 'capyclaw_manifest',
104
285
  description: 'Show the portable starter environment manifest. Read-only.',
@@ -128,7 +309,7 @@ export function apply(ctx) {
128
309
  const { installed, bundles } = await readInstalled(ctx)
129
310
  const packages = Object.entries(installed).map(([packageName, installedSpec]) => ({
130
311
  name: packageName,
131
- spec: installedSpec && !/^(?:link:|file:|workspace:)/.test(String(installedSpec)) ? installedSpec : null,
312
+ spec: installedSpec,
132
313
  platforms: ['windows', 'macos', 'linux'],
133
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)))
134
315
  const manifest = createEnvironmentManifest({
@@ -146,7 +327,7 @@ export function apply(ctx) {
146
327
 
147
328
  register({
148
329
  name: 'capyclaw_sync',
149
- 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; unrelated packages are never removed.',
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.',
150
331
  parameters: {
151
332
  manifestPath: { type: 'string', description: 'Optional imported JSON manifest path.' },
152
333
  apply: { type: 'boolean', description: 'Install packages and enable selected bundles. Default false (preview only).' },
@@ -170,6 +351,7 @@ export function apply(ctx) {
170
351
  const results = await executeEnvironmentPlan(ctx, initial)
171
352
  const final = await inspect(ctx, manifest, args)
172
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() })
173
355
  return { mode: 'applied', ok, results, final, profileBackup: backup, restartRequired: results.some((r) => r.application === 'restart-required') }
174
356
  },
175
357
  })