@capyclaw/gateway 0.0.0-stage → 0.1.2
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 +89 -2
- package/cordis.patch.yml +4 -0
- package/lib/http.mjs +101 -0
- package/lib/index.mjs +714 -0
- package/lib/paths.mjs +171 -0
- package/lib/store.mjs +193 -0
- package/lib/upstream.mjs +111 -0
- package/node_modules/@capyclaw/foundation/README.md +51 -0
- package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
- package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
- package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
- package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
- package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
- package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
- package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
- package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
- package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
- package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
- package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
- package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
- package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
- package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
- package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
- package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
- package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
- package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
- package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
- package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
- package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
- package/node_modules/@capyclaw/foundation/package.json +53 -0
- package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
- package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
- package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
- package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
- package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
- package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
- package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
- package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
- package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
- package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
- package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
- package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
- package/package.json +61 -4
- package/plugin.mjs +329 -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
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capyclaw/gateway",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"description": "统一入口网关:把本会话产出的静态产物与工作台,挂到 DSH 自带 Web 服务的 /s/<会话id>/ 命名空间下,端口从此不出现在地址里",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./plugin.mjs",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./plugin.mjs",
|
|
9
|
+
"./lib": "./lib/index.mjs",
|
|
10
|
+
"./package.json": "./package.json"
|
|
11
|
+
},
|
|
12
|
+
"dsh": {
|
|
13
|
+
"bundle": {
|
|
14
|
+
"patch": "./cordis.patch.yml"
|
|
15
|
+
},
|
|
16
|
+
"category": "service",
|
|
17
|
+
"platform": "both"
|
|
18
|
+
},
|
|
19
|
+
"meta": {
|
|
20
|
+
"title": "统一入口网关",
|
|
21
|
+
"description": "给每个会话一个 127.0.0.1:10170/s/<会话id>/ 的入口:静态产物直接出链,工作台按会话别名跳转,端口隐身。"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"plugin.mjs",
|
|
25
|
+
"lib/",
|
|
26
|
+
"cordis.patch.yml",
|
|
27
|
+
"README.md"
|
|
28
|
+
],
|
|
29
|
+
"scripts": {
|
|
30
|
+
"test": "node --test \"test/*.test.mjs\""
|
|
31
|
+
},
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@capyclaw/foundation": "^0.1.1",
|
|
34
|
+
"@capyclaw/plugin-kit": "^0.2.5"
|
|
35
|
+
},
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=18",
|
|
38
|
+
"dsh": "^0.2.0-rc.2"
|
|
39
|
+
},
|
|
40
|
+
"publishConfig": {
|
|
41
|
+
"access": "public"
|
|
42
|
+
},
|
|
43
|
+
"license": "MIT",
|
|
44
|
+
"repository": {
|
|
45
|
+
"type": "git",
|
|
46
|
+
"url": "git+https://github.com/Maple496/capyclaw.git",
|
|
47
|
+
"directory": "C/packages/capyclaw-gateway"
|
|
48
|
+
},
|
|
49
|
+
"keywords": [
|
|
50
|
+
"dsh",
|
|
51
|
+
"dsh-plugin",
|
|
52
|
+
"gateway",
|
|
53
|
+
"portal"
|
|
54
|
+
],
|
|
55
|
+
"bugs": {
|
|
56
|
+
"url": "https://github.com/Maple496/capyclaw/issues"
|
|
57
|
+
},
|
|
58
|
+
"homepage": "https://github.com/Maple496/capyclaw/tree/main/C/packages/capyclaw-gateway#readme",
|
|
59
|
+
"bundledDependencies": [
|
|
60
|
+
"@capyclaw/foundation",
|
|
61
|
+
"@capyclaw/plugin-kit"
|
|
62
|
+
]
|
|
63
|
+
}
|
package/plugin.mjs
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @capyclaw/gateway:统一入口网关。
|
|
3
|
+
*
|
|
4
|
+
* 为什么是 raw@1:网关必须挂在 **DSH 自带 Web 服务的同源前缀**下(`/s/...`),
|
|
5
|
+
* 这样浏览器里已经登录的会话直接能打开,产物也不需要额外端口。foundation 的
|
|
6
|
+
* `http-router@1` 走 `os.net` → 独立 server + 独立端口,正好是我们要消灭的东西,
|
|
7
|
+
* 所以这里用 raw@1 逃生舱拿原生 ctx(与 `@capyclaw/publisher` 同一个理由)。
|
|
8
|
+
*
|
|
9
|
+
* 对外三样东西:
|
|
10
|
+
* 1. `/s/<会话id>/`(只读)——静态产物与上游应用的统一地址;
|
|
11
|
+
* 2. `/__gateway__/*`(控制面)——发布/删除/列表/GC,要求 `x-gateway-token`;
|
|
12
|
+
* 3. `gateway_*` 工具——让套件(ppt / canvas / browser)在生成内容后自己登记。
|
|
13
|
+
*/
|
|
14
|
+
import fs from 'node:fs'
|
|
15
|
+
import path from 'node:path'
|
|
16
|
+
import { fileURLToPath } from 'node:url'
|
|
17
|
+
|
|
18
|
+
import { createPlugin, rawPlugin } from '@capyclaw/foundation/abi'
|
|
19
|
+
|
|
20
|
+
import { BASE, CONTROL, deleteEntry, describeSession, handleControl, handleRead, listEntries, publishStaticItem, publishUpstreamItem, recordSession } from './lib/index.mjs'
|
|
21
|
+
import { gatewayTokenPath, resolveToken } from './lib/http.mjs'
|
|
22
|
+
import { normalizeName } from './lib/paths.mjs'
|
|
23
|
+
|
|
24
|
+
const PKG = JSON.parse(fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), 'package.json'), 'utf8'))
|
|
25
|
+
|
|
26
|
+
const TOOL_INSTRUCTIONS = [
|
|
27
|
+
'要把产物给用户看时,调 gateway_publish 登记,然后把返回的 open 直接给他(能点开)。不要自己拼地址。',
|
|
28
|
+
'同一个 name 再发布一次就是覆盖(幂等);换名字会得到一个新地址。',
|
|
29
|
+
'每个会话在 /s/<会话id>/ 有一页;改到一半用 gateway_session 记一句「改到哪了」,下次先 show 就能接上。',
|
|
30
|
+
].join('\n')
|
|
31
|
+
|
|
32
|
+
/** 从工具执行上下文里取会话 id;取不到就回落 shell 环境,再取不到就报错(不猜)。 */
|
|
33
|
+
export function sessionIdOf(exec, explicit) {
|
|
34
|
+
const given = typeof explicit === 'string' ? explicit.trim() : ''
|
|
35
|
+
if (given) return given
|
|
36
|
+
const fromExec = exec?.agent?.session?.id
|
|
37
|
+
if (typeof fromExec === 'string' && fromExec.trim()) return fromExec.trim()
|
|
38
|
+
const fromEnv = process.env.DSH_SESSION_ID
|
|
39
|
+
if (typeof fromEnv === 'string' && fromEnv.trim()) return fromEnv.trim()
|
|
40
|
+
return ''
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export const { name, inject, apply, spec } = createPlugin({
|
|
44
|
+
name: 'gateway',
|
|
45
|
+
/* 只有 raw@1 允许声明额外 inject;这两个都是宿主自带服务的名字。 */
|
|
46
|
+
inject: ['webServer', 'tools'],
|
|
47
|
+
implements: [rawPlugin(({ ctx, log }) => {
|
|
48
|
+
const disposers = []
|
|
49
|
+
|
|
50
|
+
const webServer = ctx.webServer
|
|
51
|
+
if (!webServer?.register) {
|
|
52
|
+
throw new Error('gateway 需要 ctx.webServer:统一入口必须挂在 DSH 自带 Web 服务的同源前缀下')
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const token = resolveToken()
|
|
56
|
+
const tokenFile = gatewayTokenPath()
|
|
57
|
+
|
|
58
|
+
/* 只读面:`/s/<会话id>/...`。挂在 prefix 上,DSH 按路径段边界匹配,
|
|
59
|
+
* 不会被 `/secret` 这类裸字符串前缀误命中。 */
|
|
60
|
+
disposers.push(webServer.register({
|
|
61
|
+
kind: 'prefix',
|
|
62
|
+
path: BASE,
|
|
63
|
+
handler: (req, res) => {
|
|
64
|
+
try {
|
|
65
|
+
handleRead(req, res)
|
|
66
|
+
} catch (error) {
|
|
67
|
+
log?.warn?.(`[gateway] 读取失败:${error && error.message ? error.message : error}`)
|
|
68
|
+
try {
|
|
69
|
+
res.writeHead(500, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
70
|
+
res.end(JSON.stringify({ ok: false, error: String(error?.message || error) }))
|
|
71
|
+
} catch { /* 响应可能已经发出 */ }
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
}))
|
|
75
|
+
|
|
76
|
+
/* 控制面:写入/删除/列表/GC。token 与 loopback 校验都在 handleControl 里。 */
|
|
77
|
+
disposers.push(webServer.register({
|
|
78
|
+
kind: 'prefix',
|
|
79
|
+
path: CONTROL,
|
|
80
|
+
handler: (req, res) => {
|
|
81
|
+
handleControl(req, res, { token }).catch((error) => {
|
|
82
|
+
log?.warn?.(`[gateway] 控制面失败:${error && error.message ? error.message : error}`)
|
|
83
|
+
try {
|
|
84
|
+
res.writeHead(500, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
85
|
+
res.end(JSON.stringify({ ok: false, error: String(error?.message || error) }))
|
|
86
|
+
} catch { /* 已断开 */ }
|
|
87
|
+
})
|
|
88
|
+
},
|
|
89
|
+
}))
|
|
90
|
+
|
|
91
|
+
/* 工具面:让套件在生成内容后自己登记,不必知道 token 文件在哪。 */
|
|
92
|
+
/* 宿主自己的 origin(含端口)。只用来把 `url` 补成能直接点开的 `open`;
|
|
93
|
+
* 落盘的永远是相对会话 id 的 `url`,这样换端口、换机器都不影响「找到上次的改动」。 */
|
|
94
|
+
const origin = typeof webServer.getOrigin === 'function' ? String(webServer.getOrigin() || '').replace(/\/+$/, '') : ''
|
|
95
|
+
|
|
96
|
+
const tools = getService(ctx, 'tools')
|
|
97
|
+
if (tools?.register) {
|
|
98
|
+
for (const tool of createTools({ log, origin })) {
|
|
99
|
+
try {
|
|
100
|
+
disposers.push(tools.register(tool))
|
|
101
|
+
} catch (error) {
|
|
102
|
+
log?.warn?.(`[gateway] 工具 ${tool.name} 注册失败:${error && error.message ? error.message : error}`)
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
} else {
|
|
106
|
+
log?.warn?.('[gateway] tools 服务不可用:gateway_* 工具面未注册(HTTP 面仍可用)')
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
log?.debug?.(`[gateway] 已就绪:${BASE}/<会话id>/ ;控制面 ${CONTROL}(token 文件 ${tokenFile})`)
|
|
110
|
+
|
|
111
|
+
return () => {
|
|
112
|
+
for (const dispose of disposers.reverse()) {
|
|
113
|
+
try {
|
|
114
|
+
if (typeof dispose === 'function') dispose()
|
|
115
|
+
} catch (error) {
|
|
116
|
+
log?.warn?.(`[gateway] 卸载失败:${error && error.message ? error.message : error}`)
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
})],
|
|
121
|
+
}, import.meta.url)
|
|
122
|
+
|
|
123
|
+
/** Cordis 的 ctx 是 Proxy:没在 inject 里声明过的服务要用 ctx.get() 读。 */
|
|
124
|
+
function getService(ctx, serviceName) {
|
|
125
|
+
if (!ctx) return undefined
|
|
126
|
+
if (typeof ctx.get === 'function') {
|
|
127
|
+
try {
|
|
128
|
+
const service = ctx.get(serviceName)
|
|
129
|
+
if (service !== undefined) return service
|
|
130
|
+
} catch { /* 继续尝试属性访问 */ }
|
|
131
|
+
}
|
|
132
|
+
try {
|
|
133
|
+
return ctx[serviceName]
|
|
134
|
+
} catch {
|
|
135
|
+
return undefined
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function textResult(text) {
|
|
140
|
+
const value = typeof text === 'string' ? text : JSON.stringify(text, null, 2)
|
|
141
|
+
return { content: [{ type: 'text', text: value }] }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** `output.render` 的返回值必须是内容块数组(DSH 侧直接拿它当渲染结果)。 */
|
|
145
|
+
function renderResult(_args, value) {
|
|
146
|
+
if (value && Array.isArray(value.content)) return value.content
|
|
147
|
+
return [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }]
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function nameFromPath(filePath, isDir) {
|
|
151
|
+
const base = path.basename(String(filePath).replace(/[\\/]+$/, ''))
|
|
152
|
+
const stem = isDir ? base : base.replace(/\.[^./\\]+$/, '')
|
|
153
|
+
const cleaned = normalizeName(stem || 'artifact')
|
|
154
|
+
/* 原始文件名里可能有中文/空格;normalizeName 会拒掉,这里退成一个中性名字。 */
|
|
155
|
+
return cleaned || 'artifact'
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function createTools({ log, origin = '' }) {
|
|
159
|
+
/** 相对地址 → 能直接点开的完整地址;没有 origin(测试假宿主)就原样返回。 */
|
|
160
|
+
const absolute = (rel) => (origin && typeof rel === 'string' && rel.startsWith('/') ? origin + rel : rel)
|
|
161
|
+
|
|
162
|
+
return [
|
|
163
|
+
{
|
|
164
|
+
name: 'gateway_publish',
|
|
165
|
+
description: [
|
|
166
|
+
'把这个会话产出的内容发布到统一入口,拿到一个不含端口的稳定地址。',
|
|
167
|
+
'三种用法(互斥):path=单个文件(如导出的 html)、dir=整个目录(如带 assets 的导出目录)、serviceId=一个已经在跑的服务(把工作台挂到会话别名下)。',
|
|
168
|
+
'同名重复发布会覆盖(幂等)。返回的 url 直接给用户看。',
|
|
169
|
+
].join('\n'),
|
|
170
|
+
parameters: {
|
|
171
|
+
type: 'object',
|
|
172
|
+
properties: {
|
|
173
|
+
path: { type: 'string', description: '单个文件的绝对路径(html/pdf/png…)' },
|
|
174
|
+
dir: { type: 'string', description: '整个目录的绝对路径(入口默认 index.html)' },
|
|
175
|
+
serviceId: { type: 'string', description: '已注册服务的 id(来自 services.json),不是地址' },
|
|
176
|
+
name: { type: 'string', description: '地址里的名字,可含子路径(如 report.html、deck/index.html);缺省按文件名推' },
|
|
177
|
+
label: { type: 'string', description: '给人看的名字,只影响索引页与浮标' },
|
|
178
|
+
ttl: { type: 'number', description: '有效秒数;0(默认)表示长期有效' },
|
|
179
|
+
sessionId: { type: 'string', description: '一般不用填:缺省取当前会话' },
|
|
180
|
+
},
|
|
181
|
+
additionalProperties: false,
|
|
182
|
+
},
|
|
183
|
+
output: {
|
|
184
|
+
schema: { type: 'object', additionalProperties: true },
|
|
185
|
+
render: renderResult,
|
|
186
|
+
},
|
|
187
|
+
execute: (args, exec) => {
|
|
188
|
+
const sid = sessionIdOf(exec, args?.sessionId)
|
|
189
|
+
if (!sid) return textResult('拿不到会话 id:请显式传 sessionId。')
|
|
190
|
+
const picked = ['path', 'dir', 'serviceId'].filter((key) => typeof args?.[key] === 'string' && args[key].trim())
|
|
191
|
+
if (picked.length !== 1) return textResult('path、dir、serviceId 必须且只能给一个。')
|
|
192
|
+
try {
|
|
193
|
+
if (picked[0] === 'serviceId') {
|
|
194
|
+
const serviceId = String(args.serviceId).trim()
|
|
195
|
+
const name = normalizeName(args.name || serviceId)
|
|
196
|
+
if (!name) return textResult(`名字不合法:${args.name || serviceId}`)
|
|
197
|
+
const out = publishUpstreamItem({
|
|
198
|
+
sid, name, serviceId, label: args.label || '', ttl: Number(args.ttl || 0),
|
|
199
|
+
})
|
|
200
|
+
return textResult({ ok: true, url: out.url, open: absolute(out.url), sessionId: sid, serviceId, created: out.created })
|
|
201
|
+
}
|
|
202
|
+
const isDir = picked[0] === 'dir'
|
|
203
|
+
const target = String(isDir ? args.dir : args.path).trim()
|
|
204
|
+
if (!path.isAbsolute(target)) return textResult(`必须给绝对路径:${target}`)
|
|
205
|
+
const name = normalizeName(args.name || nameFromPath(target, isDir))
|
|
206
|
+
if (!name) return textResult(`名字不合法:${args.name || nameFromPath(target, isDir)}`)
|
|
207
|
+
const out = publishStaticItem({
|
|
208
|
+
sid,
|
|
209
|
+
name,
|
|
210
|
+
absPath: isDir ? '' : target,
|
|
211
|
+
dirPath: isDir ? target : '',
|
|
212
|
+
label: args.label || '',
|
|
213
|
+
expiresAt: Number(args.ttl || 0) ? Date.now() + Number(args.ttl) * 1000 : 0,
|
|
214
|
+
})
|
|
215
|
+
return textResult({ ok: true, url: out.url, open: absolute(out.url), sessionId: sid, kind: isDir ? 'dir' : 'file', created: out.created })
|
|
216
|
+
} catch (error) {
|
|
217
|
+
log?.warn?.(`[gateway] 发布失败:${error && error.message ? error.message : error}`)
|
|
218
|
+
return textResult(`发布失败:${error && error.message ? error.message : error}`)
|
|
219
|
+
}
|
|
220
|
+
},
|
|
221
|
+
},
|
|
222
|
+
{
|
|
223
|
+
name: 'gateway_list',
|
|
224
|
+
description: '列出本会话(或指定会话)已经发布过的地址。用户问「有哪些链接」时用它,不要自己拼。',
|
|
225
|
+
parameters: {
|
|
226
|
+
type: 'object',
|
|
227
|
+
properties: {
|
|
228
|
+
sessionId: { type: 'string', description: '缺省取当前会话;给 all 列出全部会话' },
|
|
229
|
+
},
|
|
230
|
+
additionalProperties: false,
|
|
231
|
+
},
|
|
232
|
+
output: {
|
|
233
|
+
schema: { type: 'object', additionalProperties: true },
|
|
234
|
+
render: renderResult,
|
|
235
|
+
},
|
|
236
|
+
execute: (args, exec) => {
|
|
237
|
+
const want = typeof args?.sessionId === 'string' ? args.sessionId.trim() : ''
|
|
238
|
+
const all = want === 'all' || want === '*'
|
|
239
|
+
const sid = all ? '' : sessionIdOf(exec, want)
|
|
240
|
+
if (!all && !sid) return textResult('拿不到会话 id:请显式传 sessionId(或传 all)。')
|
|
241
|
+
const entries = listEntries()
|
|
242
|
+
const filtered = all ? entries : entries.filter((item) => item.sid === sid)
|
|
243
|
+
if (!filtered.length) {
|
|
244
|
+
return textResult({ ok: true, sessionId: sid || '*', items: [], note: '这个会话还没发布过任何地址。' })
|
|
245
|
+
}
|
|
246
|
+
return textResult({ ok: true, sessionId: sid || '*', items: filtered.map((item) => ({ ...item, open: absolute(item.url) })) })
|
|
247
|
+
},
|
|
248
|
+
},
|
|
249
|
+
{
|
|
250
|
+
name: 'gateway_unpublish',
|
|
251
|
+
description: '撤掉一个已经发布的地址。name 与发布时用的名字一致(如 report.html、preview)。',
|
|
252
|
+
parameters: {
|
|
253
|
+
type: 'object',
|
|
254
|
+
properties: {
|
|
255
|
+
name: { type: 'string', description: '发布时用的名字(不含 f/ 或 app/ 前缀)' },
|
|
256
|
+
kind: { type: 'string', description: 'f(静态产物,默认)或 app(上游应用)' },
|
|
257
|
+
sessionId: { type: 'string', description: '缺省取当前会话' },
|
|
258
|
+
},
|
|
259
|
+
required: ['name'],
|
|
260
|
+
additionalProperties: false,
|
|
261
|
+
},
|
|
262
|
+
output: {
|
|
263
|
+
schema: { type: 'object', additionalProperties: true },
|
|
264
|
+
render: renderResult,
|
|
265
|
+
},
|
|
266
|
+
execute: (args, exec) => {
|
|
267
|
+
const sid = sessionIdOf(exec, args?.sessionId)
|
|
268
|
+
if (!sid) return textResult('拿不到会话 id:请显式传 sessionId。')
|
|
269
|
+
const kind = args?.kind === 'app' ? 'app' : 'f'
|
|
270
|
+
const name = normalizeName(args?.name)
|
|
271
|
+
if (!name) return textResult(`名字不合法:${args?.name}`)
|
|
272
|
+
const removed = deleteEntry(sid, `${kind}/${name}`)
|
|
273
|
+
return textResult({ ok: removed, removed, sessionId: sid, key: `${kind}/${name}` })
|
|
274
|
+
},
|
|
275
|
+
},
|
|
276
|
+
{
|
|
277
|
+
name: 'gateway_session',
|
|
278
|
+
description: [
|
|
279
|
+
'看/记这个会话自己的界面状态:每个会话在 /s/<会话id>/ 有一页,重开还能接着走。',
|
|
280
|
+
'action=show 读回状态与本会话已发布的地址;action=record 记下「改到哪了」。',
|
|
281
|
+
'record 的 state 是键值对(浅合并,值给 null 表示擦掉这个键),别塞大对象。',
|
|
282
|
+
'关窗之后新会话拿不到旧会话上下文时,先 show 一次,就知道上次改到哪了。',
|
|
283
|
+
].join('\n'),
|
|
284
|
+
parameters: {
|
|
285
|
+
type: 'object',
|
|
286
|
+
properties: {
|
|
287
|
+
action: { type: 'string', description: 'show(默认,只读)或 record(写入)' },
|
|
288
|
+
state: { type: 'object', description: 'record 用:要记的状态键值对' },
|
|
289
|
+
label: { type: 'string', description: 'record 用:这一页的标题' },
|
|
290
|
+
workspace: { type: 'string', description: 'record 用:这个会话绑定的工作区绝对路径' },
|
|
291
|
+
sessionId: { type: 'string', description: '一般不用填:缺省取当前会话' },
|
|
292
|
+
},
|
|
293
|
+
required: ['action'],
|
|
294
|
+
additionalProperties: false,
|
|
295
|
+
},
|
|
296
|
+
output: {
|
|
297
|
+
schema: { type: 'object', additionalProperties: true },
|
|
298
|
+
render: renderResult,
|
|
299
|
+
},
|
|
300
|
+
execute: (args, exec) => {
|
|
301
|
+
const sid = sessionIdOf(exec, args?.sessionId)
|
|
302
|
+
if (!sid) return textResult('拿不到会话 id:请显式传 sessionId。')
|
|
303
|
+
if (args?.action === 'record') {
|
|
304
|
+
const patch = {}
|
|
305
|
+
if (typeof args.label === 'string' && args.label) patch.label = args.label
|
|
306
|
+
if (typeof args.workspace === 'string' && args.workspace) patch.workspace = args.workspace
|
|
307
|
+
if (args.state && typeof args.state === 'object' && !Array.isArray(args.state)) patch.state = args.state
|
|
308
|
+
if (!Object.keys(patch).length) return textResult('record 至少要给 label / workspace / state 之一。')
|
|
309
|
+
try {
|
|
310
|
+
return textResult({ ok: true, session: recordSession(sid, patch), open: absolute(`/s/${sid}/`) })
|
|
311
|
+
} catch (error) {
|
|
312
|
+
log?.warn?.(`[gateway] 记录会话状态失败:${error && error.message ? error.message : error}`)
|
|
313
|
+
return textResult(`记录失败:${error && error.message ? error.message : error}`)
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
const session = describeSession(sid)
|
|
317
|
+
if (!session) {
|
|
318
|
+
return textResult({ ok: true, sessionId: sid, url: `/s/${sid}/`, open: absolute(`/s/${sid}/`), state: {}, items: [], note: '这个会话还没有记过状态、也没发布过产物。' })
|
|
319
|
+
}
|
|
320
|
+
return textResult({ ok: true, session, open: absolute(session.url) })
|
|
321
|
+
},
|
|
322
|
+
},
|
|
323
|
+
]
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** 测试注入点(与 portal-hud 的 `__hudInternals` 同一约定)。 */
|
|
327
|
+
export const __gatewayInternals = {
|
|
328
|
+
BASE, CONTROL, sessionIdOf, createTools, getService, PKG_VERSION: PKG.version, TOOL_INSTRUCTIONS,
|
|
329
|
+
}
|