@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.
Files changed (85) hide show
  1. package/README.md +40 -2
  2. package/client/client.js +273 -0
  3. package/cordis.patch.yml +5 -0
  4. package/icon.svg +5 -0
  5. package/index.js +360 -0
  6. package/lib/environment.mjs +198 -0
  7. package/lib/jobs.mjs +116 -0
  8. package/locale/en.json +6 -0
  9. package/locale/zh.json +6 -0
  10. package/manifest.js +18 -0
  11. package/node_modules/@capyclaw/foundation/README.md +51 -0
  12. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  13. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
  14. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  15. package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
  16. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  17. package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
  18. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  19. package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
  20. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  21. package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
  22. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  23. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  24. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  25. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  26. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  27. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  28. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
  29. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  30. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
  31. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
  32. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  33. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  34. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  35. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  36. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  37. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
  38. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
  39. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
  40. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
  41. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  42. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
  43. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
  44. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  45. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  46. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
  47. package/node_modules/@capyclaw/foundation/package.json +53 -0
  48. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  49. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  50. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  51. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  52. package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  70. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  71. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  72. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  73. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  74. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  75. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  76. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  77. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  78. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
  79. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  80. package/package.json +78 -4
  81. package/test/environment.test.mjs +68 -0
  82. package/test/package.test.mjs +24 -0
  83. package/test/plugin.test.mjs +179 -0
  84. package/test/stability.test.mjs +576 -0
  85. package/test/wizard.test.mjs +219 -0
package/README.md CHANGED
@@ -1,3 +1,41 @@
1
- # Temporary Holding Version
1
+ # CapyClaw environment manager
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
+
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
+
17
+ ## Tools
18
+
19
+ - `capyclaw_manifest`: read the portable starter manifest.
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).
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.
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.
24
+
25
+ ## Safety and compatibility
26
+
27
+ - The plugin uses the host package manager; it does not write profile dependencies directly or invoke npm/pnpm itself.
28
+ - Existing profile packages not named by the selected manifest are left alone.
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.
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.
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.
35
+ - DSH runtime installation/upgrades remain the responsibility of the DSH installer. CapyClaw reports version constraints and never replaces the running DSH executable.
36
+
37
+ ## Tests
38
+
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
+ })
@@ -0,0 +1,5 @@
1
+ # Portable profile environment manager.
2
+ - insert:
3
+ - id: capyclaw
4
+ name: "@capyclaw/capyclaw"
5
+ config: {}
package/icon.svg ADDED
@@ -0,0 +1,5 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
2
+ <rect x="4" y="4" width="56" height="56" rx="12" fill="#1f6feb"/>
3
+ <path d="M32 12l16 6v12c0 10-6.5 17.5-16 22-9.5-4.5-16-12-16-22V18z" fill="#ffffff" opacity="0.95"/>
4
+ <path d="M24 32l6 6 11-12" fill="none" stroke="#1f6feb" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
5
+ </svg>