@capyclaw/capyclaw 0.0.0-stage → 0.2.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 (81) hide show
  1. package/README.md +22 -2
  2. package/cordis.patch.yml +5 -0
  3. package/icon.svg +5 -0
  4. package/index.js +178 -0
  5. package/lib/environment.mjs +122 -0
  6. package/locale/en.json +6 -0
  7. package/locale/zh.json +6 -0
  8. package/manifest.js +18 -0
  9. package/node_modules/@capyclaw/foundation/README.md +51 -0
  10. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  11. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
  12. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  13. package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
  14. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  15. package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
  16. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  17. package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
  18. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  19. package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
  20. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  21. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  22. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  23. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  24. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  25. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  26. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
  27. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  28. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
  29. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
  30. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  31. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  32. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  33. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  34. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  35. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
  36. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
  37. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
  38. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
  39. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  40. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
  41. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
  42. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  43. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  44. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
  45. package/node_modules/@capyclaw/foundation/package.json +53 -0
  46. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  47. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  48. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  49. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  50. package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  70. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  71. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  72. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  73. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  74. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  75. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  76. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
  77. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  78. package/package.json +71 -4
  79. package/test/environment.test.mjs +68 -0
  80. package/test/package.test.mjs +24 -0
  81. package/test/plugin.test.mjs +101 -0
@@ -0,0 +1,132 @@
1
+ /* Web Worker:独立线程保持心跳,不受浏览器标签页节流影响
2
+ *
3
+ * 设计原则:
4
+ * 1. 健壮降级:任何失败都通知主线程,主线程决定是否降级
5
+ * 2. 自我监控:内置健康检查,连续失败自动报告
6
+ * 3. 优雅退出:stop 后立即停止,不留残留定时器
7
+ */
8
+
9
+ let active = false;
10
+ let clientId = null;
11
+ let apiBase = null;
12
+ let intervalHandle = null;
13
+ let consecutiveFailures = 0;
14
+ const MAX_FAILURES = 3; // 连续失败 3 次后通知主线程降级
15
+
16
+ self.onmessage = function(e) {
17
+ const { type, data } = e.data;
18
+
19
+ if (type === 'start') {
20
+ active = true;
21
+ clientId = data.clientId;
22
+ apiBase = data.apiBase;
23
+ consecutiveFailures = 0;
24
+ startHeartbeat();
25
+ self.postMessage({ type: 'started', clientId });
26
+ } else if (type === 'stop') {
27
+ active = false;
28
+ if (intervalHandle) {
29
+ clearInterval(intervalHandle);
30
+ intervalHandle = null;
31
+ }
32
+ self.postMessage({ type: 'stopped' });
33
+ } else if (type === 'ping') {
34
+ // 主线程健康检查:返回当前状态
35
+ self.postMessage({
36
+ type: 'pong',
37
+ active,
38
+ clientId,
39
+ consecutiveFailures,
40
+ timestamp: Date.now()
41
+ });
42
+ }
43
+ };
44
+
45
+ function startHeartbeat() {
46
+ if (intervalHandle) clearInterval(intervalHandle);
47
+
48
+ // 心跳节奏统一为 3s:单一真源是 editor/heartbeat.mjs 的 HEARTBEAT_INTERVAL_MS。
49
+ // 本文件是原样拷贝的经典 Worker,运行时不能 import npm 模块,故以字面量承载节奏,
50
+ // 由 test/heartbeat-constants.test.mjs 钉死与常量一致,防止再次漂移。
51
+ // 心跳对象是编辑器「在场租约」(editor-host /claim);两层租约语义见 heartbeat.mjs 头注。
52
+ intervalHandle = setInterval(() => {
53
+ if (!active) return;
54
+
55
+ sendClaim().catch(err => {
56
+ consecutiveFailures++;
57
+ self.postMessage({
58
+ type: 'error',
59
+ message: err.message,
60
+ consecutiveFailures,
61
+ fatal: consecutiveFailures >= MAX_FAILURES
62
+ });
63
+
64
+ // 连续失败达到阈值,建议主线程降级
65
+ if (consecutiveFailures >= MAX_FAILURES) {
66
+ self.postMessage({
67
+ type: 'fatal',
68
+ message: `连续 ${MAX_FAILURES} 次心跳失败,建议降级到主线程`
69
+ });
70
+ }
71
+ });
72
+ }, 3000);
73
+
74
+ // 立即发送第一次
75
+ sendClaim().catch(() => {});
76
+ }
77
+
78
+ async function sendClaim() {
79
+ if (!apiBase || !clientId) {
80
+ throw new Error('Worker 未初始化:缺少 apiBase 或 clientId');
81
+ }
82
+
83
+ const url = `${apiBase}/claim`;
84
+ const controller = new AbortController();
85
+ const timeoutId = setTimeout(() => controller.abort(), 8000); // 8 秒超时
86
+
87
+ try {
88
+ const response = await fetch(url, {
89
+ method: 'POST',
90
+ headers: { 'content-type': 'application/json' },
91
+ body: JSON.stringify({ id: clientId }),
92
+ signal: controller.signal,
93
+ });
94
+
95
+ clearTimeout(timeoutId);
96
+
97
+ if (!response.ok) {
98
+ throw new Error(`HTTP ${response.status}`);
99
+ }
100
+
101
+ const data = await response.json();
102
+
103
+ /* HTTP 200 但 ok:false = 租约已被其他窗口抢走(claim 被拒)。
104
+ * 不能当成功:停止心跳并通知主线程回到待命,否则被抢占的窗口会一直
105
+ * 以为自己还是 owner,继续写共享画面。 */
106
+ if (data && data.ok === false) {
107
+ active = false;
108
+ if (intervalHandle) {
109
+ clearInterval(intervalHandle);
110
+ intervalHandle = null;
111
+ }
112
+ self.postMessage({ type: 'lost', owner: data.owner, epoch: data.epoch });
113
+ return;
114
+ }
115
+
116
+ // 成功:重置失败计数
117
+ if (consecutiveFailures > 0) {
118
+ consecutiveFailures = 0;
119
+ self.postMessage({ type: 'recovered' }); // 通知主线程已恢复
120
+ }
121
+
122
+ self.postMessage({
123
+ type: 'heartbeat',
124
+ timestamp: Date.now(),
125
+ response: data,
126
+ consecutiveFailures: 0
127
+ });
128
+ } catch (err) {
129
+ clearTimeout(timeoutId);
130
+ throw err;
131
+ }
132
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * 编辑器「在场租约」心跳节奏常量单一真源(P2-13b)。
3
+ *
4
+ * 背景:心跳节奏曾在两处手工对齐而漂移——plugin-kit 的 heartbeat-worker.js 写死
5
+ * 4000ms(还留着「避免 5 秒判过期」的过期注释),document-workbench 客户端却是
6
+ * 3000ms。两者必须同拍,否则编辑器判活与文档 owner 判活快慢不一。这里把节奏收敛
7
+ * 成一个常量,客户端直接 import;worker 是原样拷贝的经典 Web Worker(运行时不能
8
+ * import npm 模块),其 setInterval 字面量由 test/heartbeat-constants.test.mjs 钉死
9
+ * 等于本常量,防止再次漂移。统一取架构审查建议的 3s。
10
+ *
11
+ * 两层租约语义不同,都要保留(本常量只统一「心跳节奏」,不合并两层租约):
12
+ * 1. 在场租约(presence)——@capyclaw/plugin-kit/editor/lease.mjs 的 createEditorLease,
13
+ * 由 editor-host 的 /claim 消费,「显示即连接」:新窗口强制抢占、旧窗口静默待命;
14
+ * TTL 10s、无 epoch,靠客户端每 HEARTBEAT_INTERVAL_MS 心跳续租。
15
+ * 2. 所有权租约(owner)——@capyclaw/document-workbench/session 的 claimOwner/OWNER_TTL,
16
+ * deck/文档级所有权,带 epoch fencing(换人 +1、旧 owner 回执被丢弃)。PPT 的
17
+ * A/projects/ppt/src/server/store/lease.mjs 只是它的兼容再导出。此为套件领域件,
18
+ * 不在本次改造范围,仅在此说清两层,避免误把在场租约当成所有权租约。
19
+ * 两条租约线共用「心跳 3s、TTL 10s」的并发协议;TTL 的运行时真源仍是 lease.mjs 的
20
+ * DEFAULT_TTL 与 document-workbench 的 OWNER_TTL(均已为 10s,未漂移,不在本次改动范围)。
21
+ *
22
+ * 本文件零依赖、browser-safe(无 node:*),可被编辑器客户端 bundle 直接 import。
23
+ */
24
+
25
+ /** 心跳间隔(毫秒):在场租约与文档 owner 租约共用的续租节奏,单一真源。 */
26
+ export const HEARTBEAT_INTERVAL_MS = 3000
@@ -0,0 +1,60 @@
1
+ /**
2
+ * 「显示即连接」编辑器租约标准模块。
3
+ *
4
+ * 活动权(claim)只存在于内部仲裁;不要把它渲染成 UI 状态。
5
+ * 新打开的窗口强制抢占,旧窗口静默转入待命。
6
+ */
7
+ import { tuning } from '../tuning.mjs'
8
+
9
+ /* 与文档 owner 租约(document-workbench OWNER_TTL)对齐为 10s:
10
+ * 两条租约线共用「心跳 3s、TTL 10s」的并发协议,避免编辑器判活比文档慢半拍。 */
11
+ const DEFAULT_TTL = 10 // 秒
12
+
13
+ /**
14
+ * 创建编辑器租约仲裁器。
15
+ * @param {{ ttl?: number }} [opts]
16
+ */
17
+ export function createEditorLease(opts = {}) {
18
+ const ttl = Number(opts.ttl) || DEFAULT_TTL
19
+ let owner = null // { id, ts }
20
+
21
+ return {
22
+ claim(id, force = false) {
23
+ const now = Date.now() / 1000
24
+ if (force || !owner || owner.id === id || now - owner.ts > ttl) {
25
+ owner = { id, ts: now }
26
+ return { ok: true, owner: id }
27
+ }
28
+ return { ok: false, owner: owner.id }
29
+ },
30
+
31
+ release(id) {
32
+ if (owner && owner.id === id) owner = null
33
+ return { ok: true }
34
+ },
35
+
36
+ isLive() {
37
+ return !!owner && Date.now() / 1000 - owner.ts <= ttl
38
+ },
39
+
40
+ status() {
41
+ return owner
42
+ ? { owner: owner.id, age: Math.round((Date.now() / 1000 - owner.ts) * 100) / 100 }
43
+ : null
44
+ },
45
+
46
+ async wait(o = {}) {
47
+ const { leaseWaitPollMs: pollMs, leaseWaitTimeoutMs: defaultTimeoutMs } = tuning()
48
+ const deadline = Date.now() + (o.timeoutMs || defaultTimeoutMs)
49
+ while (true) {
50
+ if (this.isLive()) return this.status()
51
+ if (Date.now() >= deadline) {
52
+ const hint = o.openHint ? `(打开 ${o.openHint})` : ''
53
+ const panel = o.panelHint || '编辑器面板'
54
+ throw new Error(`${panel}尚未连接${hint}。页面加载后会自动连接,无需其他操作。`)
55
+ }
56
+ await new Promise((resolve) => setTimeout(resolve, pollMs))
57
+ }
58
+ },
59
+ }
60
+ }
@@ -0,0 +1,219 @@
1
+ /**
2
+ * 影子显示器(shadow display)——平台级「保证有显示器」的兜底责任方。
3
+ *
4
+ * 背景:这套基建的实时像素/截图依赖一个连着租约心跳的编辑器页面("显示即连接")。
5
+ * 真实用户窗口由 GUI 自动挂载;但窗口被关掉、或纯 headless 场景下就没有显示器,
6
+ * editorConnected 永远 false,工具静默退离线渲染——用户被迫手动开窗/刷新。
7
+ *
8
+ * 影子显示器把这件事接管过来:服务端在「有稿件但没有真实窗口」时,自动拉起一个
9
+ * 无头 Chromium 页加载编辑器(?shadow=1),以**礼貌 claim(force=false)**持租约、
10
+ * 渲染真像素。真实用户窗口到来时 force 抢占,影子经 worker 'lost' 让位并被关停;
11
+ * 用户离开后影子再自动补位。用户全程无感。
12
+ *
13
+ * 设计约束(生产级稳定):
14
+ * - **fail-safe**:解析不到 playwright-core 或 Chromium 可执行文件 → 永久禁用并
15
+ * 只记一条日志,reconcile 变 no-op;工具退回离线渲染(与改造前行为一致),绝不
16
+ * 因为影子模块而让桥起不来或报错。
17
+ * - **不抢占**:影子永远 force=false;真实窗口(ownerLive && !ownerShadow)在场时
18
+ * 影子立即关停让位。
19
+ * - **平台无关语义**:本模块不认 ppt/canvas 业务字段,hasContent/ownerLive/
20
+ * ownerShadow 由桥(已 import document-workbench/session)算好传入,避免 kit 反向
21
+ * 依赖 document-workbench 造成环。
22
+ * - 资源回收:beforeStop/dispose 关停所有 browser;页面崩溃下次 reconcile 自动重建。
23
+ */
24
+ import fs from 'node:fs'
25
+ import os from 'node:os'
26
+ import path from 'node:path'
27
+
28
+ const noop = () => {}
29
+
30
+ /** 在一个 chromium-* 目录里按平台找可执行文件(优先 headless shell)。 */
31
+ function findChromeIn(dir) {
32
+ const headlessNames = new Set(['chrome-headless-shell.exe', 'chrome-headless-shell'])
33
+ const fullNames = new Set(['chrome.exe', 'chrome', 'Chromium'])
34
+ let headless = null
35
+ let full = null
36
+ const walk = (d, depth) => {
37
+ if (depth > 4) return
38
+ let entries = []
39
+ try { entries = fs.readdirSync(d, { withFileTypes: true }) } catch { return }
40
+ for (const entry of entries) {
41
+ const p = path.join(d, entry.name)
42
+ if (entry.isDirectory()) walk(p, depth + 1)
43
+ else if (entry.isFile()) {
44
+ if (headlessNames.has(entry.name) && !headless) headless = p
45
+ else if (fullNames.has(entry.name) && !full) full = p
46
+ }
47
+ }
48
+ }
49
+ walk(dir, 0)
50
+ return headless || full
51
+ }
52
+
53
+ /** 发现本机 Chromium 可执行文件:显式 env 优先,其次 ms-playwright 缓存(取最高修订)。 */
54
+ export function resolveChromiumExecutable(env = process.env) {
55
+ const explicit = env.SHADOW_CHROMIUM_PATH || env.PLAYWRIGHT_CHROMIUM_EXECUTABLE || env.PUPPETEER_EXECUTABLE_PATH
56
+ if (explicit) {
57
+ try { if (fs.existsSync(explicit)) return explicit } catch { /* ignore */ }
58
+ }
59
+ const roots = []
60
+ if (env.PLAYWRIGHT_BROWSERS_PATH && env.PLAYWRIGHT_BROWSERS_PATH !== '0') roots.push(env.PLAYWRIGHT_BROWSERS_PATH)
61
+ if (process.platform === 'win32') {
62
+ roots.push(path.join(env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'ms-playwright'))
63
+ } else if (process.platform === 'darwin') {
64
+ roots.push(path.join(os.homedir(), 'Library', 'Caches', 'ms-playwright'))
65
+ } else {
66
+ roots.push(path.join(os.homedir(), '.cache', 'ms-playwright'))
67
+ }
68
+ let best = null
69
+ let bestRev = -1
70
+ let bestHeadless = false
71
+ for (const root of roots) {
72
+ let entries = []
73
+ try { entries = fs.readdirSync(root) } catch { continue }
74
+ for (const name of entries) {
75
+ const m = /^chromium(_headless_shell)?-(\d+)$/.exec(name)
76
+ if (!m) continue
77
+ const rev = Number(m[2]) || 0
78
+ const isHeadless = !!m[1]
79
+ const exe = findChromeIn(path.join(root, name))
80
+ if (!exe) continue
81
+ /* 优先 headless shell(更轻),同级取最高修订。 */
82
+ const better = isHeadless !== bestHeadless
83
+ ? isHeadless
84
+ : rev > bestRev
85
+ if (!best || better) { best = exe; bestRev = rev; bestHeadless = isHeadless }
86
+ }
87
+ }
88
+ return best
89
+ }
90
+
91
+ /**
92
+ * 创建影子管理器。
93
+ * @param {object} opts
94
+ * @param {(msg:string)=>void} [opts.log]
95
+ * @param {()=>Promise<{chromium:any}>} [opts.importPlaywright] 默认动态 import playwright-core
96
+ * @param {()=>string|null} [opts.resolveExecutable]
97
+ */
98
+ export function createShadowManager({
99
+ log = noop,
100
+ importPlaywright = async () => import('playwright-core'),
101
+ resolveExecutable = () => resolveChromiumExecutable(),
102
+ maxConcurrent = 4,
103
+ } = {}) {
104
+ /** sid -> { browser, page, url, launching, dead } */
105
+ const entries = new Map()
106
+ let disabled = false
107
+ let disposed = false
108
+ let chromiumPromise = null
109
+
110
+ async function getChromium() {
111
+ if (!chromiumPromise) {
112
+ chromiumPromise = (async () => {
113
+ const mod = await importPlaywright()
114
+ const chromium = mod && (mod.chromium || (mod.default && mod.default.chromium))
115
+ if (!chromium || typeof chromium.launch !== 'function') throw new Error('playwright-core 未导出 chromium')
116
+ return chromium
117
+ })().catch((error) => {
118
+ disabled = true
119
+ log(`[shadow] 无头浏览器不可用,影子显示器禁用(工具退回离线渲染):${error.message}`)
120
+ return null
121
+ })
122
+ }
123
+ return chromiumPromise
124
+ }
125
+
126
+ async function closeEntry(sid) {
127
+ const entry = entries.get(sid)
128
+ if (!entry) return
129
+ entries.delete(sid)
130
+ try { await entry.page?.close() } catch { /* ignore */ }
131
+ try { await entry.browser?.close() } catch { /* ignore */ }
132
+ }
133
+
134
+ async function launch(sid, url) {
135
+ const chromium = await getChromium()
136
+ if (!chromium || disabled || disposed) return
137
+ const executablePath = resolveExecutable()
138
+ if (!executablePath) {
139
+ disabled = true
140
+ log('[shadow] 未找到 Chromium 可执行文件,影子显示器禁用(工具退回离线渲染)')
141
+ return
142
+ }
143
+ let browser = null
144
+ try {
145
+ browser = await chromium.launch({
146
+ headless: true,
147
+ executablePath,
148
+ args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
149
+ })
150
+ const page = await browser.newPage()
151
+ const target = url + (url.includes('?') ? '&' : '?') + 'shadow=1'
152
+ await page.goto(target, { waitUntil: 'domcontentloaded', timeout: 30000 })
153
+ const entry = { browser, page, url, launching: false, dead: false, since: Date.now() }
154
+ /* 页面崩溃/被关 → 标死,下一轮 reconcile 重建(不让影子静默失效)。 */
155
+ page.on('close', () => { entry.dead = true })
156
+ browser.on('disconnected', () => { entry.dead = true })
157
+ entries.set(sid, entry)
158
+ log(`[shadow] 影子显示器已就位:${sid}`)
159
+ } catch (error) {
160
+ try { await browser?.close() } catch { /* ignore */ }
161
+ log(`[shadow] 影子显示器启动失败(${sid}):${error.message}`)
162
+ }
163
+ }
164
+
165
+ /**
166
+ * 对账一个会话的影子状态。桥周期性调用(带上该会话的 doc 派生旗标)。
167
+ * @param {string} sid
168
+ * @param {string} url 该会话编辑器页基址(不含 ?shadow=1)
169
+ * @param {{hasContent:boolean, ownerLive:boolean, ownerShadow:boolean}} flags
170
+ */
171
+ async function reconcile(sid, url, { hasContent, ownerLive, ownerShadow }) {
172
+ if (disposed || disabled) return
173
+ try {
174
+ /* 没有稿件,或真实用户窗口在场 → 影子让位/不启动。 */
175
+ if (!hasContent || (ownerLive && !ownerShadow)) {
176
+ await closeEntry(sid)
177
+ return
178
+ }
179
+ const entry = entries.get(sid)
180
+ if (entry && entry.launching) return
181
+ if (entry && !entry.dead) {
182
+ /* 影子页活着却长时间没认领租约(引导失败/卡死)→ 超宽限重建,避免静默失效。
183
+ * 真实窗口在场或影子已正常认领时不会进这里。 */
184
+ const stuck = hasContent && !ownerLive && !ownerShadow && entry.since && (Date.now() - entry.since > 45000)
185
+ if (!stuck) return /* 已在渲染 */
186
+ await closeEntry(sid)
187
+ } else if (entry) {
188
+ await closeEntry(sid) /* 崩了 → 重建 */
189
+ }
190
+ /* 资源闸:并发影子上限,避免多会话场景拉起过多 Chromium。 */
191
+ const realCount = [...entries.values()].filter((e) => !e.launching).length
192
+ if (!entries.has(sid) && realCount >= maxConcurrent) return
193
+ const placeholder = { launching: true }
194
+ entries.set(sid, placeholder)
195
+ try {
196
+ await launch(sid, url)
197
+ } finally {
198
+ if (entries.get(sid) === placeholder) entries.delete(sid)
199
+ }
200
+ } catch (error) {
201
+ log(`[shadow] reconcile 异常(${sid}):${error.message}`)
202
+ }
203
+ }
204
+
205
+ async function dispose() {
206
+ disposed = true
207
+ for (const sid of [...entries.keys()]) await closeEntry(sid)
208
+ }
209
+
210
+ function state() {
211
+ return {
212
+ disabled,
213
+ disposed,
214
+ sessions: [...entries.entries()].map(([sid, e]) => ({ sid, launching: !!e.launching, dead: !!e.dead })),
215
+ }
216
+ }
217
+
218
+ return { reconcile, dispose, state }
219
+ }
@@ -0,0 +1,13 @@
1
+ /** 编辑器 → relay 的最小传输层;页面逻辑不关心 fetch/JSON 细节。 */
2
+ export function createTransport(basePath, fetchImpl = (...args) => fetch(...args)) {
3
+ const api = (path, options) => fetchImpl(basePath + path, options).then((response) => response.json())
4
+ return {
5
+ api,
6
+ get: (path) => api(path),
7
+ post: (path, body) => api(path, {
8
+ method: 'POST',
9
+ headers: { 'content-type': 'application/json' },
10
+ body: JSON.stringify(body),
11
+ }),
12
+ }
13
+ }
@@ -0,0 +1,13 @@
1
+ export * from './service/http.mjs'
2
+ export * from './service/server.mjs'
3
+ export * from './service/mcp-http.mjs'
4
+ export * from './service/api.mjs'
5
+ export * from './cli.mjs'
6
+ export * from './zip.mjs'
7
+ export * from './tools/validate.mjs'
8
+ export * from './skills/provider.mjs'
9
+ export * from './editor/lease.mjs'
10
+ export * from './store/journal-store.mjs'
11
+ export * from './store/blob-store.mjs'
12
+ export * from './workspace/manager.mjs'
13
+ export * from './runtime/context.mjs'