@capyclaw/windows-control 0.0.0-stage → 0.1.3

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 (99) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +142 -2
  3. package/THIRD_PARTY_NOTICES.md +20 -0
  4. package/cordis.patch.yml +32 -0
  5. package/lib/config.mjs +126 -0
  6. package/lib/mcp-json.mjs +80 -0
  7. package/node_modules/@capyclaw/foundation/README.md +51 -0
  8. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  9. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
  10. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  11. package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
  12. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  13. package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
  14. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  15. package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
  16. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  17. package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
  18. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  19. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  20. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  21. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  22. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  23. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  24. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
  25. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  26. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
  27. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
  28. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  29. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  30. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  31. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  32. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  33. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
  34. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
  35. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
  36. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
  37. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  38. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
  39. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
  40. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  41. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  42. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
  43. package/node_modules/@capyclaw/foundation/package.json +53 -0
  44. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  45. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  46. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  47. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  48. package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
  49. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  50. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  70. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  71. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  72. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  73. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  74. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
  75. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  76. package/node_modules/@capyclaw/portal/README.md +70 -0
  77. package/node_modules/@capyclaw/portal/lib/index.mjs +387 -0
  78. package/node_modules/@capyclaw/portal/lib/ledger.mjs +194 -0
  79. package/node_modules/@capyclaw/portal/lib/portal-agent.ps1 +811 -0
  80. package/node_modules/@capyclaw/portal/lib/portal-darwin.mjs +183 -0
  81. package/node_modules/@capyclaw/portal/package.json +40 -0
  82. package/node_modules/@capyclaw/service-broker/README.md +104 -0
  83. package/node_modules/@capyclaw/service-broker/cordis.patch.yml +8 -0
  84. package/node_modules/@capyclaw/service-broker/dsh-suite.json +21 -0
  85. package/node_modules/@capyclaw/service-broker/lib/control.mjs +209 -0
  86. package/node_modules/@capyclaw/service-broker/lib/discovery.mjs +109 -0
  87. package/node_modules/@capyclaw/service-broker/lib/engine.mjs +1290 -0
  88. package/node_modules/@capyclaw/service-broker/lib/host.mjs +187 -0
  89. package/node_modules/@capyclaw/service-broker/lib/manifest.mjs +262 -0
  90. package/node_modules/@capyclaw/service-broker/lib/recovery.mjs +275 -0
  91. package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +48 -0
  92. package/node_modules/@capyclaw/service-broker/lib/spec.mjs +78 -0
  93. package/node_modules/@capyclaw/service-broker/package.json +65 -0
  94. package/node_modules/@capyclaw/service-broker/server.mjs +81 -0
  95. package/node_modules/@capyclaw/service-broker/service.schema.json +62 -0
  96. package/node_modules/@capyclaw/service-broker/services.json +3 -0
  97. package/package.json +65 -4
  98. package/plugin.mjs +32 -0
  99. package/server/relay.mjs +752 -0
@@ -0,0 +1,181 @@
1
+ /**
2
+ * 极简跨平台 ZIP 读写(store + deflate 读,store 写;无外部依赖)——全仓单一真源。
3
+ *
4
+ * 之前三处实现各持一份(plugin-development 写 / tools-plugin-release 读 /
5
+ * @capyclaw/suite-kit zip-read 读),本模块合并之。旧位置保留兼容 shim。
6
+ *
7
+ * 写入:store 模式(内容不压缩,跨平台稳定,产物可被任何标准读取器读)。
8
+ * 读取:支持 store(0) 与 deflate(8);接受 Buffer 或文件路径——本地文件与
9
+ * 远端下载源共用同一条校验/解包路径。
10
+ */
11
+ import fs from 'node:fs'
12
+ import path from 'node:path'
13
+ import zlib from 'node:zlib'
14
+
15
+ /* ------------------------------------------------------------------ 写入 */
16
+
17
+ const CRC_TABLE = (() => {
18
+ const table = new Uint32Array(256)
19
+ for (let n = 0; n < 256; n++) {
20
+ let c = n
21
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1)
22
+ table[n] = c >>> 0
23
+ }
24
+ return table
25
+ })()
26
+
27
+ function crc32(buffer) {
28
+ let crc = 0xffffffff
29
+ for (let i = 0; i < buffer.length; i++) crc = CRC_TABLE[(crc ^ buffer[i]) & 0xff] ^ (crc >>> 8)
30
+ return (crc ^ 0xffffffff) >>> 0
31
+ }
32
+
33
+ function dosDateTime(date = new Date()) {
34
+ const year = Math.max(1980, date.getFullYear())
35
+ const time = ((date.getHours() & 0x1f) << 11) | ((date.getMinutes() & 0x3f) << 5) | (Math.floor(date.getSeconds() / 2) & 0x1f)
36
+ const day = (((year - 1980) & 0x7f) << 9) | (((date.getMonth() + 1) & 0x0f) << 5) | (date.getDate() & 0x1f)
37
+ return { time, day }
38
+ }
39
+
40
+ function walkFiles(dir, base = dir) {
41
+ const out = []
42
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
43
+ const full = path.join(dir, entry.name)
44
+ if (entry.isDirectory()) out.push(...walkFiles(full, base))
45
+ else if (entry.isFile()) out.push(path.relative(base, full).replace(/\\/g, '/'))
46
+ }
47
+ return out.sort()
48
+ }
49
+
50
+ /** 把目录写成 store 模式 ZIP。返回打包的相对路径列表。 */
51
+ export function writeZipFromDir(sourceDir, outFile) {
52
+ const files = walkFiles(sourceDir)
53
+ const now = dosDateTime()
54
+ const localParts = []
55
+ const centralParts = []
56
+ let offset = 0
57
+
58
+ for (const name of files) {
59
+ const data = fs.readFileSync(path.join(sourceDir, name))
60
+ const nameBytes = Buffer.from(name, 'utf8')
61
+ const crc = crc32(data)
62
+
63
+ const local = Buffer.alloc(30)
64
+ local.writeUInt32LE(0x04034b50, 0)
65
+ local.writeUInt16LE(20, 4)
66
+ local.writeUInt16LE(0x0800, 6)
67
+ local.writeUInt16LE(0, 8)
68
+ local.writeUInt16LE(now.time, 10)
69
+ local.writeUInt16LE(now.day, 12)
70
+ local.writeUInt32LE(crc, 14)
71
+ local.writeUInt32LE(data.length, 18)
72
+ local.writeUInt32LE(data.length, 22)
73
+ local.writeUInt16LE(nameBytes.length, 26)
74
+ local.writeUInt16LE(0, 28)
75
+ localParts.push(local, nameBytes, data)
76
+
77
+ const central = Buffer.alloc(46)
78
+ central.writeUInt32LE(0x02014b50, 0)
79
+ central.writeUInt16LE(20, 4)
80
+ central.writeUInt16LE(20, 6)
81
+ central.writeUInt16LE(0x0800, 8)
82
+ central.writeUInt16LE(0, 10)
83
+ central.writeUInt16LE(now.time, 12)
84
+ central.writeUInt16LE(now.day, 14)
85
+ central.writeUInt32LE(crc, 16)
86
+ central.writeUInt32LE(data.length, 20)
87
+ central.writeUInt32LE(data.length, 24)
88
+ central.writeUInt16LE(nameBytes.length, 28)
89
+ central.writeUInt16LE(0, 30)
90
+ central.writeUInt16LE(0, 32)
91
+ central.writeUInt16LE(0, 34)
92
+ central.writeUInt16LE(0, 36)
93
+ central.writeUInt32LE(0, 38)
94
+ central.writeUInt32LE(offset, 42)
95
+ centralParts.push(central, nameBytes)
96
+
97
+ offset += local.length + nameBytes.length + data.length
98
+ }
99
+
100
+ const centralBuffer = Buffer.concat(centralParts)
101
+ const eocd = Buffer.alloc(22)
102
+ eocd.writeUInt32LE(0x06054b50, 0)
103
+ eocd.writeUInt16LE(0, 4)
104
+ eocd.writeUInt16LE(0, 6)
105
+ eocd.writeUInt16LE(files.length, 8)
106
+ eocd.writeUInt16LE(files.length, 10)
107
+ eocd.writeUInt32LE(centralBuffer.length, 12)
108
+ eocd.writeUInt32LE(offset, 16)
109
+ eocd.writeUInt16LE(0, 20)
110
+
111
+ fs.mkdirSync(path.dirname(outFile), { recursive: true })
112
+ fs.writeFileSync(outFile, Buffer.concat([...localParts, centralBuffer, eocd]))
113
+ return files
114
+ }
115
+
116
+ /* ------------------------------------------------------------------ 读取 */
117
+
118
+ function locateEocd(data, label) {
119
+ for (let i = data.length - 22; i >= 0; i--) {
120
+ if (data.readUInt32LE(i) === 0x06054b50) return i
121
+ }
122
+ throw new Error(`不是有效的 ZIP: ${label}`)
123
+ }
124
+
125
+ /**
126
+ * 列出 ZIP 全部条目名。
127
+ * @param {Buffer|string} input - ZIP 字节或文件路径
128
+ */
129
+ export function listZipEntryNames(input, label = 'zip') {
130
+ const data = Buffer.isBuffer(input) ? input : fs.readFileSync(input)
131
+ const eocd = locateEocd(data, label)
132
+ const count = data.readUInt16LE(eocd + 10)
133
+ let offset = data.readUInt32LE(eocd + 16)
134
+ const names = []
135
+ for (let i = 0; i < count; i++) {
136
+ if (data.readUInt32LE(offset) !== 0x02014b50) throw new Error(`ZIP 中央目录损坏: ${label}`)
137
+ const nameLength = data.readUInt16LE(offset + 28)
138
+ const extraLength = data.readUInt16LE(offset + 30)
139
+ const commentLength = data.readUInt16LE(offset + 32)
140
+ names.push(data.subarray(offset + 46, offset + 46 + nameLength).toString('utf8'))
141
+ offset += 46 + nameLength + extraLength + commentLength
142
+ }
143
+ return names
144
+ }
145
+
146
+ /**
147
+ * 从 ZIP 读单个条目的原始字节;不存在返回 undefined。
148
+ * @param {Buffer|string} input - ZIP 字节或文件路径
149
+ */
150
+ export function readZipEntryBuffer(input, entryName, label = 'zip') {
151
+ const data = Buffer.isBuffer(input) ? input : fs.readFileSync(input)
152
+ const eocd = locateEocd(data, label)
153
+ const count = data.readUInt16LE(eocd + 10)
154
+ let offset = data.readUInt32LE(eocd + 16)
155
+ for (let i = 0; i < count; i++) {
156
+ if (data.readUInt32LE(offset) !== 0x02014b50) throw new Error(`ZIP 中央目录损坏: ${label}`)
157
+ const method = data.readUInt16LE(offset + 10)
158
+ const compSize = data.readUInt32LE(offset + 20)
159
+ const nameLength = data.readUInt16LE(offset + 28)
160
+ const extraLength = data.readUInt16LE(offset + 30)
161
+ const commentLength = data.readUInt16LE(offset + 32)
162
+ const localOffset = data.readUInt32LE(offset + 42)
163
+ const name = data.subarray(offset + 46, offset + 46 + nameLength).toString('utf8')
164
+ if (name === entryName) {
165
+ const localNameLength = data.readUInt16LE(localOffset + 26)
166
+ const localExtraLength = data.readUInt16LE(localOffset + 28)
167
+ const start = localOffset + 30 + localNameLength + localExtraLength
168
+ const body = data.subarray(start, start + compSize)
169
+ if (method === 0) return body
170
+ if (method === 8) return zlib.inflateRawSync(body)
171
+ throw new Error(`不支持的 ZIP 压缩方式 ${method}: ${label}`)
172
+ }
173
+ offset += 46 + nameLength + extraLength + commentLength
174
+ }
175
+ return undefined
176
+ }
177
+
178
+ /** 读取 ZIP 中央目录条目名(文件路径版;打包自检/测试用)。 */
179
+ export function listZipEntries(file) {
180
+ return listZipEntryNames(fs.readFileSync(file), file)
181
+ }
@@ -0,0 +1,70 @@
1
+ # @capyclaw/portal
2
+
3
+ DSH 基础设施标准件:**服务就绪那一刻,把它的页面弹成一扇置顶小窗**。
4
+
5
+ 业务插件不写窗口代码,只在 `services.json` 里声明就行;端口分配、进程拉起、健康检查仍然归
6
+ `@capyclaw/service-host`(端口)与 `@capyclaw/service-broker`(进程),这个包只管「窗口」。
7
+
8
+ ## 用法
9
+
10
+ 业务侧(`services.json`):
11
+
12
+ ```jsonc
13
+ {
14
+ "id": "ppt-workbench",
15
+ "cmd": "node ${PACKAGE_DIR}/node_modules/@capyclaw/ppt-workbench/server/relay.mjs --port ${PORT} --dir ${PACKAGE_DIR}/.host",
16
+ "ports": { "main": "auto" },
17
+ "url": "http://127.0.0.1:${PORT}",
18
+ "healthPath": "/healthz",
19
+ "window": { "title": "PPT 工作台", "width": 820, "height": 940, "anchor": "right" }
20
+ }
21
+ ```
22
+
23
+ 基建侧(broker / 桥在服务就绪后调用一次):
24
+
25
+ ```js
26
+ import { openServiceWindow, closeServiceWindow } from '@capyclaw/portal'
27
+
28
+ await openServiceWindow({
29
+ id: spec.id, // 窗口身份,同一 id 复用同一扇窗
30
+ url: `http://127.0.0.1:${port}`, // 服务首页
31
+ window: spec.window, // 上面的声明
32
+ })
33
+ ```
34
+
35
+ ## `window` 声明
36
+
37
+ | 字段 | 默认 | 说明 |
38
+ |---|---|---|
39
+ | `title` | `工作台` | 窗口标题(Chromium 会按页面 `<title>` 覆盖,这里会反复纠正) |
40
+ | `width` / `height` | `820` × `940`(DIP) | 窗口尺寸 |
41
+ | `anchor` | `right` | `right` / `left` / `center` |
42
+ | `margin` | `24` | 贴边留白(DIP) |
43
+ | `topmost` | `true` | 置顶 |
44
+ | `frameless` | `false` | 拆原生边框(实测会多出一条 Chromium 自绘标题栏,不建议) |
45
+
46
+ `window: false` 或省略 → 不弹窗,服务行为完全不变。
47
+
48
+ ## 行为约定
49
+
50
+ - **只在服务就绪那一刻弹一次**:被最小化或关掉之后不会自己弹回来;窗口复用按 `id` 判定,
51
+ 端口变了(`ports.main: "auto"` 重启换端口)会关掉旧窗、开新窗,避免停在死端口。
52
+ - **不抢焦点**:开窗不调 `SetForegroundWindow`,用户正在聊天框打字时不会被打断。
53
+ - **失败不影响服务**:任何异常都只是返回值里的 `skipped` / 抛给调用方的日志,启动流程照走。
54
+ - 窗口 = Edge/Chrome 的 `--app` 窗口(无地址栏、无标签栏),顶部只有系统那一行标题栏 + `— □ ✕`。
55
+
56
+ ## 开关
57
+
58
+ | 环境变量 | 作用 |
59
+ |---|---|
60
+ | `DSH_PORTAL=0` | 全局关闭弹窗 |
61
+ | `DSH_PORTAL_BROWSER` | 指定浏览器可执行文件(默认找 Edge,其次 Chrome) |
62
+ | `DSH_PORTAL_HOME` | 浏览器 profile 根目录(默认 `%LOCALAPPDATA%\capyclaw\portal`) |
63
+ | `DSH_PORTAL_DEBUG=1` | 打印行协议收发,排查「弹窗没出现」 |
64
+ | `DSH_PORTAL_POWERSHELL` | 指定 powershell.exe 路径 |
65
+
66
+ ## 平台
67
+
68
+ - **Windows**:`lib/portal-agent.ps1`,常驻 PowerShell 子进程,JSON 行协议;支持置顶/几何校正。
69
+ - **macOS**:`lib/portal-darwin.mjs`,每扇窗一个独立的 Chromium `--app` 进程(detached,宿主退出不连带杀窗)。需要装 Chrome/Edge/Chromium/Brave 之一。**有意降级**:`topmost`/`frameless` 按普通 app 窗处理(macOS 无可靠对应),不跟踪最小化态,`focus` 走 System Events(需辅助功能权限,失败静默)。
70
+ - **其它平台**:`openServiceWindow` 返回 `{ skipped }`,调用方按「没有弹窗」处理。
@@ -0,0 +1,387 @@
1
+ /**
2
+ * @capyclaw/portal — 基础设施能力:服务就绪后,把它的页面「弹」到桌面上给人看。
3
+ *
4
+ * 由来:套件里的服务一直是后台静默起(端口自动分配 → 拉起 → 轮询 /healthz),
5
+ * 人只能在浏览器里自己找地址。这里补上后半截:**服务就绪那一刻**开一个置顶、
6
+ * 无浏览器顶栏的小窗,内容实时跟着服务走;关掉窗口不影响服务。
7
+ *
8
+ * 边界(很重要):
9
+ * - 端口分配、单实例、健康检查、进程生命周期都不归这里,归 service-host / service-broker。
10
+ * - 业务插件不写任何窗口代码,只在 services.json 里声明 `window`(见 README)。
11
+ * - 本文件只负责「窗口」:Edge/Chromium 的 app 窗口(--app,无地址栏无标签栏),
12
+ * Win32 部分交给同目录 portal-agent.ps1(常驻子进程,JSON 行协议)。
13
+ *
14
+ * 平台:win32 走 portal-agent.ps1;darwin 走 portal-darwin.mjs(每窗一个独立
15
+ * Chromium --app 进程,topmost/frameless 降级为普通窗,见该文件头注)。
16
+ * 其它平台 openServiceWindow 返回 { skipped },调用方按「没有弹窗」处理,
17
+ * 绝不影响服务本身。
18
+ */
19
+
20
+ import { spawn } from 'node:child_process'
21
+ import fs from 'node:fs'
22
+ import os from 'node:os'
23
+ import path from 'node:path'
24
+ import { fileURLToPath } from 'node:url'
25
+ import { DarwinPortalAgent, DARWIN_BROWSERS } from './portal-darwin.mjs'
26
+
27
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
28
+ const AGENT_SCRIPT = path.join(HERE, 'portal-agent.ps1')
29
+
30
+ /** 默认窗口尺寸(DIP):竖长条,贴在屏幕右侧,够看一页内容又不挡主窗。 */
31
+ const DEFAULT_SIZE = { width: 820, height: 940 }
32
+
33
+ /** 浏览器候选:app 窗口只需要 Chromium 内核 + --app。 */
34
+ const WIN32_BROWSERS = [
35
+ path.join(process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)', 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
36
+ path.join(process.env.PROGRAMFILES || 'C:\\Program Files', 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
37
+ path.join(process.env.LOCALAPPDATA || '', 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
38
+ path.join(process.env.PROGRAMFILES || 'C:\\Program Files', 'Google', 'Chrome', 'Application', 'chrome.exe'),
39
+ path.join(process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)', 'Google', 'Chrome', 'Application', 'chrome.exe'),
40
+ ]
41
+ const BROWSER_CANDIDATES = [
42
+ process.env.DSH_PORTAL_BROWSER,
43
+ ...(process.platform === 'darwin' ? DARWIN_BROWSERS : WIN32_BROWSERS),
44
+ ].filter(Boolean)
45
+
46
+ export function findPortalBrowser(explicit) {
47
+ for (const candidate of [explicit, ...BROWSER_CANDIDATES]) {
48
+ if (!candidate) continue
49
+ try {
50
+ if (fs.statSync(candidate).isFile()) return candidate
51
+ } catch { /* 继续找下一个 */ }
52
+ }
53
+ return null
54
+ }
55
+
56
+ /** 不可用原因;null 表示可弹窗。 */
57
+ export function portalDisabled() {
58
+ const flag = process.env.DSH_PORTAL
59
+ if (flag === '0' || flag === 'off' || flag === 'false') return 'DSH_PORTAL 已关闭'
60
+ if (process.platform === 'win32') {
61
+ if (!fs.existsSync(AGENT_SCRIPT)) return '缺少 portal-agent.ps1(安装不完整)'
62
+ if (!findPortalBrowser()) return '没有找到 Edge/Chrome'
63
+ return null
64
+ }
65
+ if (process.platform === 'darwin') {
66
+ if (!findPortalBrowser()) return '没有找到 Chrome/Edge/Chromium'
67
+ return null
68
+ }
69
+ return `平台 ${process.platform} 暂不支持弹窗`
70
+ }
71
+
72
+ /** 每个服务一个独立浏览器 profile:互不干扰,也不会污染用户自己的浏览器。 */
73
+ export function portalProfileDir(key) {
74
+ const base = process.env.DSH_PORTAL_HOME
75
+ || (process.platform === 'darwin'
76
+ ? path.join(os.homedir(), 'Library', 'Application Support', 'capyclaw', 'portal')
77
+ : path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'capyclaw', 'portal'))
78
+ const dir = path.join(base, String(key || 'default').replace(/[^\w.-]+/g, '-'))
79
+ fs.mkdirSync(dir, { recursive: true })
80
+ return dir
81
+ }
82
+
83
+ /** DSH_PORTAL_DEBUG=1 时把行协议逐条打出来,排查「弹窗没出现」用。 */
84
+ const DEBUG = /^(1|true|on|yes)$/i.test(String(process.env.DSH_PORTAL_DEBUG || ''))
85
+ function debug(...args) {
86
+ if (DEBUG) console.error('[portal:debug]', ...args)
87
+ }
88
+
89
+ /** JSON.stringify 的纯 ASCII 版本:PowerShell 5.1 的控制台编码只认这个。 */
90
+ function asciiJson(value) {
91
+ return JSON.stringify(value).replace(
92
+ /[^\x20-\x7e]/g,
93
+ (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`,
94
+ )
95
+ }
96
+
97
+ /** 常驻 Win32 助手:一个进程管所有窗口,JSON 行协议。 */
98
+ class PortalAgent {
99
+ constructor() {
100
+ this.child = null
101
+ this.seq = 0
102
+ this.pending = new Map()
103
+ this.buffer = ''
104
+ this.starting = null
105
+ // 0 = healthy. Bumped on unexpected exits / spawn failures, reset as soon as the agent
106
+ // answers again, so a crashed or killed agent is respawned on the next request instead of
107
+ // staying dead forever. `stop()` is a deliberate shutdown and must NOT count as a failure —
108
+ // otherwise three normal restarts poison the counter and every later call throws
109
+ // "portal-agent 连续启动失败" until the host process restarts.
110
+ this.failures = 0
111
+ this.stopping = false
112
+ }
113
+
114
+ /** 有没有活着的助手(darwin 后端用窗口账本判空,接口对齐)。 */
115
+ get active() { return !!this.child }
116
+
117
+ /** 宿主退出钩子:win32 杀掉常驻助手;darwin 后端是空操作(窗口 detached)。 */
118
+ dispose() { try { this.child?.kill() } catch { /* 忽略 */ } }
119
+
120
+ async start() {
121
+ if (this.child && this.child.exitCode !== null) this.child = null
122
+ if (this.child) return this.child
123
+ if (this.starting) return this.starting
124
+ if (this.failures >= 3) throw new Error('portal-agent 连续启动失败')
125
+ this.starting = new Promise((resolve, reject) => {
126
+ const child = spawn(
127
+ process.env.DSH_PORTAL_POWERSHELL || 'powershell.exe',
128
+ ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', AGENT_SCRIPT],
129
+ { windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] },
130
+ )
131
+ child.stdout.setEncoding('utf8')
132
+ child.stdout.on('data', (chunk) => this.onData(chunk))
133
+ child.stderr.setEncoding('utf8')
134
+ child.stderr.on('data', (chunk) => {
135
+ const text = String(chunk).trim()
136
+ if (text) console.error('[portal] agent:', text)
137
+ })
138
+ child.on('error', (error) => {
139
+ this.failures += 1
140
+ this.child = null
141
+ for (const [, entry] of this.pending) entry.reject(error)
142
+ this.pending.clear()
143
+ reject(error)
144
+ })
145
+ child.on('exit', () => {
146
+ // `child.__stopping` 由 stop() 打标:那是我们自己结束的,不算失败。
147
+ if (!this.stopping && !child.__stopping) this.failures += 1
148
+ this.child = null
149
+ for (const [, entry] of this.pending) entry.reject(new Error('portal-agent 已退出'))
150
+ this.pending.clear()
151
+ })
152
+ // 管道对端消失是常态(助手被结束、用户关窗后助手退出)。这些流上的 'error'
153
+ // 若没人接就会变成 uncaughtException,把宿主进程整体带下去。
154
+ child.stdin.on('error', (error) => debug('agent stdin 关闭:', error?.code || error?.message))
155
+ child.stdout.on('error', (error) => debug('agent stdout 关闭:', error?.code || error?.message))
156
+ child.stderr.on('error', () => { /* 忽略 */ })
157
+ this.child = child
158
+ debug('agent 启动 pid=', child.pid)
159
+ resolve(child)
160
+ }).finally(() => { this.starting = null })
161
+ return this.starting
162
+ }
163
+
164
+ onData(chunk) {
165
+ this.buffer += chunk
166
+ let index
167
+ while ((index = this.buffer.indexOf('\n')) >= 0) {
168
+ const line = this.buffer.slice(0, index).trim()
169
+ this.buffer = this.buffer.slice(index + 1)
170
+ if (!line) continue
171
+ let message
172
+ try {
173
+ message = JSON.parse(line)
174
+ } catch {
175
+ console.error('[portal] agent 输出无法解析:', line.slice(0, 200))
176
+ continue
177
+ }
178
+ debug('agent →', line.length > 300 ? `${line.slice(0, 300)}…` : line)
179
+ const entry = this.pending.get(String(message.id))
180
+ if (!entry) {
181
+ if (!message.ok) console.error('[portal] agent 报错(无对应请求):', message.error || line.slice(0, 200))
182
+ continue
183
+ }
184
+ this.pending.delete(String(message.id))
185
+ clearTimeout(entry.timer)
186
+ if (message.ok) {
187
+ this.failures = 0
188
+ entry.resolve(message)
189
+ } else entry.reject(new Error(message.error || 'portal-agent 失败'))
190
+ }
191
+ }
192
+
193
+ async request(op, payload = {}, timeoutMs = 30000) {
194
+ const child = await this.start()
195
+ if (!child) throw new Error('portal-agent 不可用')
196
+ const id = String(++this.seq)
197
+ // 行协议要穿过 Windows 控制台代码页:非 ASCII 一律转成 \uXXXX,
198
+ // 否则中文标题(marker)会在 PowerShell 侧被解码成乱码,甚至破坏 JSON。
199
+ const message = `${asciiJson({ id, op, ...payload })}\n`
200
+ debug('node →', op, payload.key || '', message.length > 400 ? `${message.length}B` : '')
201
+ return new Promise((resolve, reject) => {
202
+ const timer = setTimeout(() => {
203
+ this.pending.delete(id)
204
+ reject(new Error(`portal-agent 超时(${op})`))
205
+ }, timeoutMs)
206
+ this.pending.set(id, { resolve, reject, timer })
207
+ try {
208
+ child.stdin.write(message)
209
+ } catch (error) {
210
+ clearTimeout(timer)
211
+ this.pending.delete(id)
212
+ reject(error)
213
+ }
214
+ })
215
+ }
216
+
217
+ async stop() {
218
+ if (!this.child) return
219
+ // exit 事件是异步到达的:必须给“这一只进程”打标,而不是靠一个稍微提前复位的时间窗。
220
+ this.stopping = true
221
+ this.child.__stopping = true
222
+ try { await this.request('shutdown', {}, 3000) } catch { /* 忽略 */ }
223
+ try { this.child?.stdin.end() } catch { /* 忽略 */ }
224
+ try { this.child?.kill() } catch { /* 忽略 */ }
225
+ this.child = null
226
+ // 主动关停不动 failures;标记复位,下一次意外退出照常计数。
227
+ this.stopping = false
228
+ }
229
+ }
230
+
231
+ const agent = process.platform === 'darwin' ? new DarwinPortalAgent() : new PortalAgent()
232
+ let exitHookInstalled = false
233
+ function installExitHook() {
234
+ if (exitHookInstalled) return
235
+ exitHookInstalled = true
236
+ process.once('exit', () => {
237
+ try { agent.dispose() } catch { /* 忽略 */ }
238
+ })
239
+ }
240
+
241
+ /** 声明归一化:services.json 里的 `window` 只要写想要的,其余取默认。 */
242
+ export function normalizeWindow(decl = {}) {
243
+ const source = decl && typeof decl === 'object' ? decl : {}
244
+ return {
245
+ title: source.title || '工作台',
246
+ width: Number(source.width) > 0 ? Number(source.width) : DEFAULT_SIZE.width,
247
+ height: Number(source.height) > 0 ? Number(source.height) : DEFAULT_SIZE.height,
248
+ anchor: source.anchor === 'left' || source.anchor === 'center' ? source.anchor : 'right',
249
+ margin: Number.isFinite(Number(source.margin)) ? Number(source.margin) : 24,
250
+ topmost: source.topmost !== false,
251
+ // Chromium app 窗口自带一条 25dip 的标题栏,拆掉原生边框只会多出一条,默认保留。
252
+ frameless: source.frameless === true,
253
+ }
254
+ }
255
+
256
+ /**
257
+ * 打开(或复用)一个弹窗。
258
+ * @returns {Promise<{skipped?:string, key?:string, hwnd?:number, pid?:number, reused?:boolean}>}
259
+ */
260
+ export async function openPortalWindow(options = {}) {
261
+ const blocked = portalDisabled()
262
+ if (blocked) return { skipped: blocked }
263
+ const decl = normalizeWindow(options)
264
+ const key = String(options.key || 'default')
265
+ if (!options.url) throw new Error('openPortalWindow 需要 url')
266
+ installExitHook()
267
+ const result = await agent.request('open', {
268
+ key,
269
+ url: String(options.url),
270
+ marker: decl.title,
271
+ title: decl.title,
272
+ w: decl.width,
273
+ h: decl.height,
274
+ anchor: decl.anchor,
275
+ margin: decl.margin,
276
+ topmost: decl.topmost,
277
+ frameless: decl.frameless,
278
+ // A summon (HUD click) raises the window; programmatic reuse stays silent.
279
+ activate: options.activate !== false,
280
+ profile: portalProfileDir(key),
281
+ browser: findPortalBrowser(options.browser),
282
+ }, 40000)
283
+ // Chromium 会在页面首次绘制后(约 1–2s)再按自己的口径重放一次窗口 bounds,把上面
284
+ // 定好的几何顶掉。开窗是一次性的后台动作,这里在它落定后补两拍;传 stale 让 agent
285
+ // 见到「用户已经在用这个窗」就放手。刻意不带 allowRestore:用户把窗最小化之后,
286
+ // 这几拍绝不能把它复活(那是用户的选择,不是我们该纠正的漂移)。
287
+ // 延迟补拍的 nudge 默认关闭:powerShell 侧 Ensure-Placement 已经覆盖了 Chromium 的
288
+ // 「加载完再重放一次 bounds」那段,而外部补拍会让窗口在用户面前被重新定位/闪一下
289
+ //(实测还会把窗口带成最小化)。需要时用 DSH_PORTAL_NUDGE=1 打开再排查。
290
+ const nudges = [
291
+ { delay: 2200, allowRestore: false },
292
+ { delay: 5200, allowRestore: false },
293
+ ]
294
+ for (const { delay, allowRestore } of process.env.DSH_PORTAL_NUDGE === '1' ? nudges : []) {
295
+ const timer = setTimeout(() => {
296
+ agent.request('move', { key, stale: true, allowRestore }, 8000).catch(() => {})
297
+ }, delay)
298
+ if (typeof timer.unref === 'function') timer.unref()
299
+ }
300
+ return { key, hwnd: result.hwnd, pid: result.pid, rect: result.rect, reused: !!result.reused }
301
+ }
302
+
303
+ export async function focusPortalWindow(key = 'default') {
304
+ if (portalDisabled()) return { skipped: true }
305
+ return agent.request('focus', { key }, 8000)
306
+ }
307
+
308
+ export async function closePortalWindow(key = 'default') {
309
+ if (!agent.active) return { closed: false }
310
+ try {
311
+ return await agent.request('close', { key }, 10000)
312
+ } catch {
313
+ return { closed: false }
314
+ }
315
+ }
316
+
317
+ export async function portalWindowState() {
318
+ if (!agent.active) return { windows: [] }
319
+ try {
320
+ return await agent.request('state', {}, 8000)
321
+ } catch {
322
+ return { windows: [] }
323
+ }
324
+ }
325
+
326
+ export async function shutdownPortalAgent() {
327
+ await agent.stop()
328
+ }
329
+
330
+ /** 已经开着就什么都不做,没开才开。 */
331
+ export async function ensurePortalWindow(options = {}) {
332
+ const blocked = portalDisabled()
333
+ if (blocked) return { skipped: blocked }
334
+ const key = String(options.key || 'default')
335
+ if (!agent.active) return openPortalWindow(options)
336
+ const state = await portalWindowState()
337
+ const hit = (state.windows || []).find((window) => window.key === key)
338
+ if (hit) {
339
+ if (hit.iconic) {
340
+ try { await agent.request('restore', { key }, 8000) } catch { /* 忽略 */ }
341
+ } else {
342
+ /* 每次"改内容"都会走这里:顺手把置顶位补回来(不动位置/尺寸、不抢焦点)。 */
343
+ try { await agent.request('ping', { key }, 5000) } catch { /* 忽略 */ }
344
+ }
345
+ return { key, hwnd: hit.hwnd, pid: hit.pid, rect: hit.rect, reused: true, alive: true, restored: !!hit.iconic }
346
+ }
347
+ return openPortalWindow(options)
348
+ }
349
+
350
+ /**
351
+ * 服务就绪后的入口:把 services.json 里的 `window` 声明变成一扇窗。
352
+ *
353
+ * { "id": "ppt-workbench", "url": "http://127.0.0.1:${PORT}", "window": { "title": "PPT 工作台" } }
354
+ *
355
+ * healthUrl 通常是 `.../healthz`,这里去掉健康路径后再开窗,窗口落在服务首页。
356
+ */
357
+ export async function openServiceWindow({ id, url, healthUrl, window: decl, path: suffix } = {}) {
358
+ const blocked = portalDisabled()
359
+ if (blocked) return { skipped: blocked }
360
+ const key = String(id || 'service')
361
+ const base = String(url || healthUrl || '').replace(/\/(healthz|health)\/?$/, '')
362
+ if (!base) return { skipped: '声明里没有 url' }
363
+ const target = `${base.replace(/\/+$/, '')}${suffix ? `/${String(suffix).replace(/^\/+/, '')}` : '/'}`
364
+ return openPortalWindow({ key, url: target, ...normalizeWindow(decl) })
365
+ }
366
+
367
+ export async function ensureServiceWindow(options = {}) {
368
+ const blocked = portalDisabled()
369
+ if (blocked) return { skipped: blocked }
370
+ const key = String(options.id || 'service')
371
+ const base = String(options.url || options.healthUrl || '').replace(/\/(healthz|health)\/?$/, '')
372
+ if (!base) return { skipped: '声明里没有 url' }
373
+ const target = `${base.replace(/\/+$/, '')}${options.path ? `/${String(options.path).replace(/^\/+/, '')}` : '/'}`
374
+ return ensurePortalWindow({ key, url: target, ...normalizeWindow(options.window) })
375
+ }
376
+
377
+ /**
378
+ * 记一次端口活动(见 lib/ledger.mjs)。
379
+ *
380
+ * 和开窗解耦:**调用只记账,不弹窗**。DSH 界面的浮动图标读这份台账,
381
+ * 用户点了某个端口才真正开窗(openServiceWindow)。
382
+ */
383
+ export { ledgerPath, readLedger, recordActivity, resetLedger, servicePort } from './ledger.mjs'
384
+
385
+ export async function closeServiceWindow(id) {
386
+ return closePortalWindow(String(id || 'service'))
387
+ }