@capyclaw/browser-workbench 0.1.18 → 0.1.20

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "contractVersion": "1.3.0",
3
- "packageVersion": "0.1.18",
3
+ "packageVersion": "0.1.20",
4
4
  "toolCount": 18,
5
5
  "tools": [
6
6
  {
@@ -632,6 +632,7 @@
632
632
  "features": [
633
633
  "browser.contract"
634
634
  ],
635
+ "domain": "",
635
636
  "tools": [
636
637
  {
637
638
  "name": "browser_capabilities",
@@ -651,7 +652,8 @@
651
652
  "additionalProperties": false
652
653
  },
653
654
  "kind": "read",
654
- "since": "1.0.0"
655
+ "since": "1.0.0",
656
+ "domain": ""
655
657
  }
656
658
  ]
657
659
  },
@@ -670,6 +672,7 @@
670
672
  "features": [
671
673
  "browser.navigation"
672
674
  ],
675
+ "domain": "",
673
676
  "tools": [
674
677
  {
675
678
  "name": "browser_navigate",
@@ -694,7 +697,8 @@
694
697
  "additionalProperties": false
695
698
  },
696
699
  "kind": "write",
697
- "since": "1.0.0"
700
+ "since": "1.0.0",
701
+ "domain": ""
698
702
  }
699
703
  ]
700
704
  },
@@ -713,6 +717,7 @@
713
717
  "features": [
714
718
  "browser.snapshot"
715
719
  ],
720
+ "domain": "",
716
721
  "tools": [
717
722
  {
718
723
  "name": "browser_snapshot",
@@ -729,7 +734,8 @@
729
734
  "additionalProperties": false
730
735
  },
731
736
  "kind": "read",
732
- "since": "1.0.0"
737
+ "since": "1.0.0",
738
+ "domain": ""
733
739
  }
734
740
  ]
735
741
  },
@@ -748,6 +754,7 @@
748
754
  "features": [
749
755
  "browser.interaction"
750
756
  ],
757
+ "domain": "",
751
758
  "tools": [
752
759
  {
753
760
  "name": "browser_click",
@@ -779,7 +786,8 @@
779
786
  "additionalProperties": false
780
787
  },
781
788
  "kind": "write",
782
- "since": "1.0.0"
789
+ "since": "1.0.0",
790
+ "domain": ""
783
791
  },
784
792
  {
785
793
  "name": "browser_drag",
@@ -838,7 +846,8 @@
838
846
  "additionalProperties": false
839
847
  },
840
848
  "kind": "write",
841
- "since": "1.2.0"
849
+ "since": "1.2.0",
850
+ "domain": ""
842
851
  },
843
852
  {
844
853
  "name": "browser_fill",
@@ -873,7 +882,8 @@
873
882
  "additionalProperties": false
874
883
  },
875
884
  "kind": "write",
876
- "since": "1.0.0"
885
+ "since": "1.0.0",
886
+ "domain": ""
877
887
  },
878
888
  {
879
889
  "name": "browser_press",
@@ -903,7 +913,8 @@
903
913
  "additionalProperties": false
904
914
  },
905
915
  "kind": "write",
906
- "since": "1.0.0"
916
+ "since": "1.0.0",
917
+ "domain": ""
907
918
  },
908
919
  {
909
920
  "name": "browser_select",
@@ -934,7 +945,8 @@
934
945
  "additionalProperties": false
935
946
  },
936
947
  "kind": "write",
937
- "since": "1.0.0"
948
+ "since": "1.0.0",
949
+ "domain": ""
938
950
  },
939
951
  {
940
952
  "name": "browser_upload",
@@ -973,7 +985,8 @@
973
985
  "additionalProperties": false
974
986
  },
975
987
  "kind": "write",
976
- "since": "1.3.0"
988
+ "since": "1.3.0",
989
+ "domain": ""
977
990
  },
978
991
  {
979
992
  "name": "browser_scroll",
@@ -1002,7 +1015,8 @@
1002
1015
  "additionalProperties": false
1003
1016
  },
1004
1017
  "kind": "write",
1005
- "since": "1.0.0"
1018
+ "since": "1.0.0",
1019
+ "domain": ""
1006
1020
  },
1007
1021
  {
1008
1022
  "name": "browser_act",
@@ -1116,7 +1130,8 @@
1116
1130
  "additionalProperties": false
1117
1131
  },
1118
1132
  "kind": "write",
1119
- "since": "1.1.0"
1133
+ "since": "1.1.0",
1134
+ "domain": ""
1120
1135
  }
1121
1136
  ]
1122
1137
  },
@@ -1135,6 +1150,7 @@
1135
1150
  "features": [
1136
1151
  "browser.tabs"
1137
1152
  ],
1153
+ "domain": "",
1138
1154
  "tools": [
1139
1155
  {
1140
1156
  "name": "browser_tabs",
@@ -1166,7 +1182,8 @@
1166
1182
  "additionalProperties": false
1167
1183
  },
1168
1184
  "kind": "control",
1169
- "since": "1.0.0"
1185
+ "since": "1.0.0",
1186
+ "domain": ""
1170
1187
  }
1171
1188
  ]
1172
1189
  },
@@ -1186,6 +1203,7 @@
1186
1203
  "features": [
1187
1204
  "browser.screenshot"
1188
1205
  ],
1206
+ "domain": "",
1189
1207
  "tools": [
1190
1208
  {
1191
1209
  "name": "browser_screenshot",
@@ -1206,7 +1224,8 @@
1206
1224
  "additionalProperties": false
1207
1225
  },
1208
1226
  "kind": "read",
1209
- "since": "1.0.0"
1227
+ "since": "1.0.0",
1228
+ "domain": ""
1210
1229
  }
1211
1230
  ]
1212
1231
  },
@@ -1225,6 +1244,7 @@
1225
1244
  "features": [
1226
1245
  "browser.session"
1227
1246
  ],
1247
+ "domain": "",
1228
1248
  "tools": [
1229
1249
  {
1230
1250
  "name": "browser_status",
@@ -1235,7 +1255,8 @@
1235
1255
  "additionalProperties": false
1236
1256
  },
1237
1257
  "kind": "read",
1238
- "since": "1.0.0"
1258
+ "since": "1.0.0",
1259
+ "domain": ""
1239
1260
  },
1240
1261
  {
1241
1262
  "name": "browser_wait",
@@ -1261,7 +1282,8 @@
1261
1282
  "additionalProperties": false
1262
1283
  },
1263
1284
  "kind": "control",
1264
- "since": "1.0.0"
1285
+ "since": "1.0.0",
1286
+ "domain": ""
1265
1287
  },
1266
1288
  {
1267
1289
  "name": "browser_history",
@@ -1287,7 +1309,8 @@
1287
1309
  "additionalProperties": false
1288
1310
  },
1289
1311
  "kind": "control",
1290
- "since": "1.0.0"
1312
+ "since": "1.0.0",
1313
+ "domain": ""
1291
1314
  },
1292
1315
  {
1293
1316
  "name": "browser_close",
@@ -1298,7 +1321,8 @@
1298
1321
  "additionalProperties": false
1299
1322
  },
1300
1323
  "kind": "control",
1301
- "since": "1.0.0"
1324
+ "since": "1.0.0",
1325
+ "domain": ""
1302
1326
  }
1303
1327
  ]
1304
1328
  },
@@ -1317,6 +1341,7 @@
1317
1341
  "features": [
1318
1342
  "browser.evaluate"
1319
1343
  ],
1344
+ "domain": "",
1320
1345
  "tools": [
1321
1346
  {
1322
1347
  "name": "browser_evaluate",
@@ -1341,7 +1366,8 @@
1341
1366
  "additionalProperties": false
1342
1367
  },
1343
1368
  "kind": "write",
1344
- "since": "1.0.0"
1369
+ "since": "1.0.0",
1370
+ "domain": ""
1345
1371
  }
1346
1372
  ]
1347
1373
  }
@@ -200,7 +200,12 @@ export function createAssetRoutes({ assetStore, basePath = '', maxUploadBytes =
200
200
  const getPrefix = getPrefixes.find((candidate) => p.startsWith(candidate))
201
201
  if (getPrefix) {
202
202
  if (!assetStore) { send(req, res, 404, { error: 'asset store unavailable' }); return true }
203
- const id = decodeURIComponent(p.slice(getPrefix.length))
203
+ let id
204
+ try { id = decodeURIComponent(p.slice(getPrefix.length)) } catch {
205
+ /* 畸形百分号编码(如 /assets/%zz):decodeURIComponent 抛 URIError,
206
+ * 不包会一路冒成 500。这是客户端错误,回 400。 */
207
+ send(req, res, 400, { error: 'malformed asset id encoding' }); return true
208
+ }
204
209
  if (!validId(id)) { send(req, res, 404, { error: 'asset not found' }); return true }
205
210
  const asset = assetStore.get(id)
206
211
  if (!asset) { send(req, res, 404, { error: 'asset not found' }); return true }
@@ -2,7 +2,7 @@
2
2
  import { ABI_MAJOR, getInterfaceKind } from './kinds.mjs'
3
3
  import { validateInterface } from './validate.mjs'
4
4
  import { AbiError, ERROR_CODES, toAbiError } from './errors.mjs'
5
- import { satisfies } from './version.mjs'
5
+ import { satisfies, isValidRange } from './version.mjs'
6
6
 
7
7
  const thenable = (value) => value && typeof value.then === 'function'
8
8
 
@@ -164,6 +164,13 @@ export function createLoader({ adapters = {}, capabilities = {}, log = null, abi
164
164
  plugins.delete(spec.name)
165
165
  void previous.handle?.dispose?.()
166
166
  }
167
+ /* 非法范围单独报 E_SCHEMA:旧实现把「range 写错」和「能力真缺」都归成
168
+ * E_CAP_MISSING「能力不可用」,误导排障。先区分两者。 */
169
+ const badRanges = spec.requires.filter((need) => need.name.startsWith('os.') && !isValidRange(need.range))
170
+ if (badRanges.length) {
171
+ throw error(ERROR_CODES.E_SCHEMA, `插件 ${spec.name} 能力范围非法:${badRanges.map((r) => r.raw).join(', ')}`,
172
+ { plugin: spec.name, invalid: badRanges })
173
+ }
167
174
  const missing = spec.requires.filter((need) => need.name.startsWith('os.')
168
175
  && !satisfies(capabilityMap()[need.name] || '', need.range))
169
176
  if (missing.length) {
@@ -191,9 +191,12 @@ export function definePlugin(options = {}) {
191
191
  const requiresEntries = requires.map((entry) => parseCapability(entry, 'requires'))
192
192
  const providesEntries = provides.map((entry) => parseCapability(entry, 'provides'))
193
193
  for (const entry of providesEntries) {
194
- if (/^[\^~<>=]/.test(entry.range)) {
194
+ /* 白名单而非黑名单:provides 必须是完整 x.y.z(可带 prerelease)。旧实现只拒
195
+ * ^~<>= 前缀,'1.x' / '1.*' / 裸 '1' 漏网被当成版本发布,消费方 parseVersion
196
+ * 解析不了 → satisfies 恒 false,能力永远「不可用」。 */
197
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(entry.range)) {
195
198
  throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE,
196
- `provides 必须写精确版本,不能写范围:${entry.raw}`, { entry: entry.raw })
199
+ `provides 必须写精确版本(x.y.z),不能写范围:${entry.raw}`, { entry: entry.raw })
197
200
  }
198
201
  }
199
202
 
@@ -2,25 +2,57 @@
2
2
  * 版本与范围:能力声明用 `^1` / `^1.2.0` / `>=1.2` / `1.x` / 精确版本。
3
3
  *
4
4
  * 只实现这份 ABI 需要的语义,不引入 semver 依赖:
5
- * - `^1.2.3` → >=1.2.3 且同主版本;`^0.2.3` → >=0.2.3 且同次版本(0.x 约定)
5
+ * - `^1.2.3` → >=1.2.3 且同主版本;`^0.2.3` → >=0.2.3 且同次版本;
6
+ * `^0.0.3` → >=0.0.3 且同补丁(0.0.x 约定,semver 标准)
6
7
  * - `~1.2.3` → >=1.2.3 且同次版本
7
8
  * - `1.x` / `1.*` → 同主版本
8
9
  * - `>=` `>` `<=` `<` `=` 前缀
9
10
  * - 裸版本 → 精确匹配(比较时忽略末位 0)
11
+ * - prerelease 保留并参与比较:1.0.0-beta < 1.0.0;带 prerelease 的版本只满足
12
+ * 同 [major,minor,patch] 且同样带 prerelease 的范围(semver 标准,避免预发布
13
+ * 版本被当成正式版本放行)。
10
14
  */
11
15
 
12
16
  export function parseVersion(text) {
13
17
  if (typeof text !== 'string') return null
14
- const match = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-[0-9A-Za-z.-]+)?$/.exec(text.trim())
18
+ const match = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?$/.exec(text.trim())
15
19
  if (!match) return null
16
- return [Number(match[1]), Number(match[2] || 0), Number(match[3] || 0)]
20
+ const parts = [Number(match[1]), Number(match[2] || 0), Number(match[3] || 0)]
21
+ parts.prerelease = match[4] || null
22
+ return parts
23
+ }
24
+
25
+ function comparePrerelease(a, b) {
26
+ /* 无 prerelease > 有 prerelease(1.0.0 > 1.0.0-beta)。 */
27
+ if (!a && !b) return 0
28
+ if (!a) return 1
29
+ if (!b) return -1
30
+ const left = a.split('.')
31
+ const right = b.split('.')
32
+ for (let i = 0; i < Math.max(left.length, right.length); i++) {
33
+ const x = left[i]
34
+ const y = right[i]
35
+ if (x === undefined) return -1
36
+ if (y === undefined) return 1
37
+ const xn = /^\d+$/.test(x)
38
+ const yn = /^\d+$/.test(y)
39
+ if (xn && yn) {
40
+ const d = Number(x) - Number(y)
41
+ if (d !== 0) return d < 0 ? -1 : 1
42
+ } else if (xn !== yn) {
43
+ return xn ? -1 : 1 // 数字标识符 < 字母数字标识符
44
+ } else if (x !== y) {
45
+ return x < y ? -1 : 1
46
+ }
47
+ }
48
+ return 0
17
49
  }
18
50
 
19
51
  function compareParts(a, b) {
20
52
  for (let i = 0; i < 3; i++) {
21
53
  if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1
22
54
  }
23
- return 0
55
+ return comparePrerelease(a.prerelease || null, b.prerelease || null)
24
56
  }
25
57
 
26
58
  export function compareVersions(a, b) {
@@ -44,12 +76,23 @@ export function satisfies(version, range) {
44
76
  if (raw.startsWith('^')) {
45
77
  const base = parseVersion(raw.slice(1))
46
78
  if (!base) return false
79
+ /* prerelease 只满足同 [major,minor,patch] 且带 prerelease 的范围(semver 标准),
80
+ * 避免 1.1.0-beta 被 ^1.0.0 当正式版本放行。 */
81
+ if (current.prerelease && (!base.prerelease
82
+ || current[0] !== base[0] || current[1] !== base[1] || current[2] !== base[2])) return false
47
83
  if (compareParts(current, base) < 0) return false
48
- return base[0] === 0 ? current[0] === 0 && current[1] === base[1] : current[0] === base[0]
84
+ if (base[0] === 0) {
85
+ /* 0.0.x caret 收紧到补丁位:^0.0.3 只容 0.0.3,不容 0.0.9。 */
86
+ if (base[1] === 0) return current[0] === 0 && current[1] === 0 && current[2] === base[2]
87
+ return current[0] === 0 && current[1] === base[1]
88
+ }
89
+ return current[0] === base[0]
49
90
  }
50
91
  if (raw.startsWith('~')) {
51
92
  const base = parseVersion(raw.slice(1))
52
93
  if (!base) return false
94
+ if (current.prerelease && (!base.prerelease
95
+ || current[0] !== base[0] || current[1] !== base[1] || current[2] !== base[2])) return false
53
96
  return compareParts(current, base) >= 0 && current[0] === base[0] && current[1] === base[1]
54
97
  }
55
98
  if (raw.startsWith('>=')) {
@@ -80,3 +123,18 @@ export function satisfies(version, range) {
80
123
  const exact = parseVersion(raw)
81
124
  return Boolean(exact) && compareParts(current, exact) === 0
82
125
  }
126
+
127
+ /**
128
+ * 范围是否「语义合法」(区别于「合法但不满足」)。供加载器把非法范围单独报
129
+ * E_SCHEMA,而不是误归因成「能力不可用」误导排障。空范围视为「任意」,合法。
130
+ */
131
+ export function isValidRange(range) {
132
+ const raw = String(range ?? '').trim()
133
+ if (!raw || raw === '*' || raw === 'x') return true
134
+ if (/^[\^~]/.test(raw)) return Boolean(parseVersion(raw.slice(1)))
135
+ if (/^(>=|<=)/.test(raw)) return Boolean(parseVersion(raw.slice(2)))
136
+ if (/^[><]/.test(raw)) return Boolean(parseVersion(raw.slice(1)))
137
+ if (raw.startsWith('=')) return isValidRange(raw.slice(1))
138
+ if (/^(\d+)(?:\.(\d+))?\.[x*]$/.test(raw)) return true
139
+ return Boolean(parseVersion(raw))
140
+ }
@@ -11,6 +11,10 @@ import { BASE_CAPABILITIES } from './caps.mjs'
11
11
 
12
12
  const NOOP_LOG = { debug() {}, info() {}, warn() {}, error() {} }
13
13
 
14
+ /* 内存宿主也要有界:app 不 dispose、asset 只 put 不 delete 的用法会让数组/Map
15
+ * 无限增长。app 提供 dispose() 摘除自己;assets 提供 delete() 与上限 LRU 淘汰。 */
16
+ const DEFAULT_MAX_ASSETS = 1024
17
+
14
18
  export function createMemoryHost(options = {}) {
15
19
  const state = {
16
20
  providers: [],
@@ -24,6 +28,9 @@ export function createMemoryHost(options = {}) {
24
28
  plugins: [],
25
29
  }
26
30
  const log = options.log ?? NOOP_LOG
31
+ const maxAssets = Number(options.maxAssets) > 0 ? Number(options.maxAssets) : DEFAULT_MAX_ASSETS
32
+ /* 单调序号:不能用 size+1 拼 id——淘汰后 size 回落,同毫秒内会撞掉已有资产。 */
33
+ let assetSeq = 0
27
34
 
28
35
  function http() {
29
36
  return {
@@ -41,6 +48,11 @@ export function createMemoryHost(options = {}) {
41
48
  }
42
49
  },
43
50
  async dispatch() {},
51
+ dispose() {
52
+ const index = state.apps.indexOf(app)
53
+ if (index >= 0) state.apps.splice(index, 1)
54
+ routes.length = 0
55
+ },
44
56
  }
45
57
  state.apps.push(app)
46
58
  return app
@@ -149,12 +161,27 @@ export function createMemoryHost(options = {}) {
149
161
  }),
150
162
  assets: () => ({
151
163
  async put(value, contentType = 'application/octet-stream') {
152
- const id = `asset-${state.assets.size + 1}`
153
164
  const buffer = Buffer.isBuffer(value) ? value : Buffer.from(String(value))
165
+ /* Map 保持插入序:超限淘汰最旧(LRU 近似),get 命中会刷新到队尾。 */
166
+ while (state.assets.size >= maxAssets) {
167
+ const oldest = state.assets.keys().next().value
168
+ state.assets.delete(oldest)
169
+ }
170
+ const id = `asset-${++assetSeq}`
154
171
  state.assets.set(id, { data: buffer, contentType })
155
172
  return { id, url: `/assets/${id}`, size: buffer.length, contentType }
156
173
  },
157
- get(id) { return state.assets.get(id) },
174
+ get(id) {
175
+ const entry = state.assets.get(id)
176
+ if (entry) { state.assets.delete(id); state.assets.set(id, entry) }
177
+ return entry
178
+ },
179
+ delete(id) { return state.assets.delete(id) },
180
+ gc() {
181
+ const removed = state.assets.size
182
+ state.assets.clear()
183
+ return { removed }
184
+ },
158
185
  }),
159
186
  }
160
187
  }
@@ -91,7 +91,11 @@ export function createNet(host, config = {}) {
91
91
  }
92
92
  return
93
93
  }
94
- await new Promise((resolve) => setTimeout(resolve, WEB_LATE_POLL_MS))
94
+ await new Promise((resolve) => {
95
+ /* unref:迟到补挂的轮询定时器不得拖住进程退出(最长 60s 的尾延迟)。 */
96
+ const timer = setTimeout(resolve, WEB_LATE_POLL_MS)
97
+ timer.unref?.()
98
+ })
95
99
  }
96
100
  })().catch(() => {})
97
101
  }
@@ -116,7 +120,10 @@ export function createNet(host, config = {}) {
116
120
  if (!web && shouldWaitForWeb()) {
117
121
  const deadline = Date.now() + WEB_WAIT_MS
118
122
  while (!web && Date.now() < deadline && !closed) {
119
- await new Promise((resolve) => setTimeout(resolve, WEB_POLL_MS))
123
+ await new Promise((resolve) => {
124
+ const timer = setTimeout(resolve, WEB_POLL_MS)
125
+ timer.unref?.()
126
+ })
120
127
  web = webServer()
121
128
  }
122
129
  }
@@ -140,6 +147,9 @@ export function createNet(host, config = {}) {
140
147
  disposal = (async () => {
141
148
  if (!sharedHost) return
142
149
  // listen 失败由 ready/start 报告;清理仍需执行,且 close 失败不能被吞掉。
150
+ // 注意:dispose 在 listen 失败时仍 RESOLVE(错误经 ready/start 上报)——这是
151
+ // 被 network-lifecycle 测试固化的契约,close 不再二次上抛 listen 错,避免
152
+ // 破坏「清理成功即 dispose 成功」的语义。
143
153
  await listening.catch(() => {})
144
154
  // 迟到补挂的路由要一起撤掉,否则共享宿主关了、宿主网页端口上还留着分发器。
145
155
  try {
@@ -6,8 +6,9 @@
6
6
  */
7
7
  import { tuning } from '../tuning.mjs'
8
8
 
9
- const DEFAULT_TTL = 15 // 秒
10
- const DEFAULT_HEARTBEAT = 3 // 秒(心跳间隔应小于 TTL)
9
+ /* 与文档 owner 租约(document-workbench OWNER_TTL)对齐为 10s:
10
+ * 两条租约线共用「心跳 3s、TTL 10s」的并发协议,避免编辑器判活比文档慢半拍。 */
11
+ const DEFAULT_TTL = 10 // 秒
11
12
 
12
13
  /**
13
14
  * 创建编辑器租约仲裁器。
@@ -57,83 +58,3 @@ export function createEditorLease(opts = {}) {
57
58
  },
58
59
  }
59
60
  }
60
-
61
- /**
62
- * 编辑器端自动挂接循环。
63
- * 首次 claim 强制抢占(后打开者赢),之后静默心跳。
64
- * @param {{
65
- * clientId: string,
66
- * claim: (force: boolean) => Promise<boolean>,
67
- * release?: () => void,
68
- * onActive?: () => void,
69
- * onStandby?: () => void,
70
- * retryMs?: number,
71
- * heartbeatMs?: number,
72
- * setInterval?: (cb: () => void) => any,
73
- * clearInterval?: (handle: any) => void
74
- * }} o
75
- */
76
- export function startAutoAttach(o) {
77
- if (!o || !o.clientId) throw new Error('startAutoAttach: clientId 必填')
78
- if (typeof o.claim !== 'function') throw new Error('startAutoAttach: claim 必须是函数')
79
-
80
- const retryMs = o.retryMs || 1000
81
- const heartbeatMs = o.heartbeatMs || DEFAULT_HEARTBEAT * 1000
82
- const setI = o.setInterval || ((cb) => setInterval(cb, heartbeatMs))
83
- const clearI = o.clearInterval || ((handle) => clearInterval(handle))
84
-
85
- let active = false
86
- let heartbeat = null
87
- let disposed = false
88
-
89
- async function tryClaim(force) {
90
- try {
91
- return await o.claim(force)
92
- } catch {
93
- return false
94
- }
95
- }
96
-
97
- function goActive() {
98
- if (active) return
99
- active = true
100
- try { o.onActive && o.onActive() } catch { /* 用户回调失败不阻塞挂接 */ }
101
- heartbeat = setI(async () => {
102
- if (disposed) return
103
- const ok = await tryClaim(false)
104
- if (!ok) goStandby()
105
- })
106
- }
107
-
108
- function goStandby() {
109
- if (!active) return
110
- active = false
111
- if (heartbeat != null) {
112
- clearI(heartbeat)
113
- heartbeat = null
114
- }
115
- try { o.onStandby && o.onStandby() } catch { /* 静默 */ }
116
- }
117
-
118
- ;(async () => {
119
- let first = true
120
- while (!disposed) {
121
- const ok = await tryClaim(first)
122
- first = false
123
- if (ok) {
124
- goActive()
125
- return
126
- }
127
- await new Promise((resolve) => setTimeout(resolve, retryMs))
128
- }
129
- })()
130
-
131
- return {
132
- get active() { return active },
133
- dispose() {
134
- disposed = true
135
- goStandby()
136
- try { o.release && o.release() } catch { /* 释放失败不阻塞退出 */ }
137
- },
138
- }
139
- }
@@ -211,7 +211,15 @@ export function createServiceApp(options = {}) {
211
211
  if (req.method !== 'GET' && req.method !== 'HEAD') return false
212
212
  if (cleanPrefix && u.pathname !== cleanPrefix && !u.pathname.startsWith(cleanPrefix + '/')) return false
213
213
  const relRaw = cleanPrefix ? u.pathname.slice(cleanPrefix.length) : u.pathname
214
- const rel = relRaw === '' || relRaw === '/' ? index : decodeURIComponent(relRaw.replace(/^\/+/, ''))
214
+ let rel
215
+ try {
216
+ rel = relRaw === '' || relRaw === '/' ? index : decodeURIComponent(relRaw.replace(/^\/+/, ''))
217
+ } catch {
218
+ /* 畸形百分号编码 → URIError,不包会冒成 500;客户端错误回 400。 */
219
+ res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
220
+ res.end(req.method === 'HEAD' ? undefined : 'malformed path encoding')
221
+ return true
222
+ }
215
223
  let file = null
216
224
  let type = mimeFor(rel)
217
225
  if (files) {
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "$schema": "../capyclaw-suite-kit/suite.schema.json",
3
3
  "name": "dsh-tool-host-suite",
4
- "version": "0.2.0",
4
+ "version": "0.3.0",
5
5
  "title": "Tool Host",
6
6
  "description": "通用工具面:能力 DSL、注册表、校验、契约、MCP 壳、跨套件能力描述符注册/发现。",
7
7
  "packages": {
8
8
  "@capyclaw/tool-host": {
9
9
  "role": "provider",
10
- "version": "^0.2.0",
10
+ "version": "^0.3.0",
11
11
  "path": ".",
12
12
  "provides": {
13
13
  "services": [
@@ -1,16 +1,35 @@
1
1
  /**
2
2
  * @capyclaw/tool-host 插件:向同进程插件提供 ctx.toolHost。
3
+ *
4
+ * 同时落地“会话模式锁”这一基础设施能力:
5
+ * · 把 work-store 惰性解析器注入 toolHost(模式锁的存储真源);
6
+ * · 给 DSH tools 服务挂全局 guard(异领域调用硬拒兜底);
7
+ * · 注册框架核心工具 mode_lock / mode_status(无领域,恒可见)——显式锁定入口。
8
+ * 核心工具与 guard 的注册统一走 modeGate.install(tools)(幂等):apply 时 best-effort 挂一次,
9
+ * 若那一刻 tools 服务尚未就绪,首个套件注册(registerWithDsh / bridge host)会再调 install 补上,
10
+ * 故不依赖加载顺序。所有经 toolHost.registerWithDsh / bridge host 注册的领域能力自动受锁约束,套件零接线。
3
11
  */
4
12
  import { defineDriver } from '@capyclaw/foundation/abi'
5
13
  import { createToolHost } from '../src/index.mjs'
6
14
 
15
+ const safeGet = (ctx, name) => {
16
+ try { return ctx.reflect?.get?.(name) ?? ctx[name] } catch { return null }
17
+ }
18
+
7
19
  export const { name, inject, apply } = defineDriver({
8
20
  name: 'tool-host',
9
21
  service: 'toolHost',
10
22
  apply(ctx, config = {}) {
11
- const service = createToolHost(config)
23
+ const service = createToolHost({ ...config, getWorkStore: () => safeGet(ctx, 'workStore') })
12
24
  const dispose = ctx.provide('toolHost', service)
13
- console.log('[tool-host] ready')
14
- return () => { if (typeof dispose === 'function') dispose() }
25
+
26
+ /* 模式锁兜底闸 + 核心锁定工具(幂等)。tools 缺席则降级:稍后套件注册时经 install 补挂。 */
27
+ const tools = safeGet(ctx, 'tools')
28
+ if (tools && typeof tools.register === 'function') service.modeGate.install(tools)
29
+
30
+ console.log('[tool-host] ready (mode-gate enabled)')
31
+ return () => {
32
+ if (typeof dispose === 'function') dispose()
33
+ }
15
34
  },
16
- })
35
+ })
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/tool-host",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "DSH 公共工具面插件:能力 DSL、工具注册表、参数校验、契约报告、MCP 协议壳与 instructions 模板,向插件提供 ctx.toolHost。",
5
5
  "type": "module",
6
6
  "main": "./lib/host.mjs",
@@ -0,0 +1,80 @@
1
+ /**
2
+ * 工具结果图像准入 —— DSH 原生工具面专用。
3
+ *
4
+ * 背景(2026-11-22 会话中断根因):DSH 的 ImageBlock 契约要求
5
+ * `{ type:'image', attachment: ImageAttachmentRef }`(见 @deepseek-ai/dsh-llm
6
+ * types.ts)。但部分工作台工具(rsp_screen / browser_screenshot 等)为了「图片直接
7
+ * 回给模型」返回了 MCP wire 形态的裸 base64 块 `{ type:'image', data, mimeType }`。
8
+ * 原生面 `dsh-tools/batch.ts` 把 result.content 原样写进 session 日志、不做形状校验,
9
+ * 于是坏块永久留在历史里;下一步构建请求时序列化器读 `block.attachment.attachmentId`
10
+ * 抛 TypeError(deepseek 侧包成 TRANSPORT,qwen4 侧冒泡成 UNKNOWN),该会话此后每一轮
11
+ * 都在发出前崩掉。
12
+ *
13
+ * 官方工具(read_image / mcp-client / office)都是自己先 `attachments.saveImage`
14
+ * 再回 attachment ref。这里在注册层补上同一道准入:把裸 base64 图像块持久化成
15
+ * attachment ref 再交给 DSH,一处修复覆盖所有 capyclaw 原生工具。
16
+ *
17
+ * 注意:只用于原生面(registerWithDsh)。MCP 面(createMcpHandler/dispatcher)必须
18
+ * 保留 `{data,mimeType}` wire 形态——那是 MCP 协议本身,由 dsh-mcp-client 负责落盘。
19
+ */
20
+
21
+ /** 是否是一个尚未准入的裸 base64 图像块(缺 attachment、带 string data)。 */
22
+ function isRawImageBlock(block) {
23
+ return !!block && block.type === 'image' && !block.attachment && typeof block.data === 'string'
24
+ }
25
+
26
+ /**
27
+ * 从执行上下文 / 注册上下文解析 attachments 服务。
28
+ * agent 的会话级 ctx 与 read_image 用的是同一棵上下文树,attachments 必在其上;
29
+ * 注册 ctx 作为兜底。cordis 未 inject 时 get 可能抛错,逐一吞掉换下一个候选。
30
+ * @returns {object|null} 带 saveImage 的 AttachmentStore,或 null。
31
+ */
32
+ export function resolveAttachments(exec, ctx) {
33
+ for (const candidate of [exec?.agent?.ctx, ctx]) {
34
+ if (!candidate) continue
35
+ try {
36
+ const viaGet = typeof candidate.get === 'function' ? candidate.get('attachments') : undefined
37
+ const service = viaGet ?? candidate.attachments ?? candidate.reflect?.get?.('attachments')
38
+ if (service && typeof service.saveImage === 'function') return service
39
+ } catch { /* 该上下文取不到,换下一个候选 */ }
40
+ }
41
+ return null
42
+ }
43
+
44
+ /**
45
+ * 把工具结果 content 里的裸 base64 图像块准入为持久 attachment ref。
46
+ * 非图像块、已带 attachment 的图像块原样保留;无图像块时零开销直接返回原数组。
47
+ *
48
+ * 降级原则:宁可丢图也不毒化会话——attachments 缺席或 saveImage 失败时,把该图像块
49
+ * 换成一条说明性 text 块(工具通常另有一条带落盘路径的 text 块,信息不丢)。
50
+ *
51
+ * @param {Array} content 归一化后的 MCP content 块数组。
52
+ * @param {object|null} attachments AttachmentStore(resolveAttachments 的结果)。
53
+ * @param {{ name?: string }} [opts] 可选显示名(写入 ref.name,绝不解释为路径)。
54
+ * @returns {Promise<Array>} 准入后的 content 块数组。
55
+ */
56
+ export async function admitToolResultImages(content, attachments, { name } = {}) {
57
+ if (!Array.isArray(content)) return content
58
+ if (!content.some(isRawImageBlock)) return content
59
+
60
+ const out = []
61
+ for (const block of content) {
62
+ if (!isRawImageBlock(block)) { out.push(block); continue }
63
+
64
+ const mediaType = block.mediaType || block.mimeType || 'image/png'
65
+ if (!attachments) {
66
+ out.push({ type: 'text', text: `[image omitted: no attachment service mounted; ${mediaType}]` })
67
+ continue
68
+ }
69
+ try {
70
+ const data = Buffer.from(block.data, 'base64')
71
+ const ref = await attachments.saveImage({ data, mediaType, ...(name ? { name } : {}) })
72
+ out.push({ type: 'image', attachment: ref })
73
+ } catch (error) {
74
+ const code = error?.code || error?.name || 'ERROR'
75
+ const message = String(error?.message || error)
76
+ out.push({ type: 'text', text: `[image omitted: attachment save failed (${code}): ${message}]` })
77
+ }
78
+ }
79
+ return out
80
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * 调用者会话上下文(框架级 ALS)。
3
+ *
4
+ * registerWithDsh 把每个原生工具的执行包进 runWithCallerSession(sid, …),
5
+ * 于是工具 handler 执行期间(哪怕 handler 只拿到 (args, ctx)、丢了 exec),
6
+ * 框架内部任何一层都能用 currentCallerSession() 取回“是谁在调我”。
7
+ *
8
+ * 用途:会话模式锁在能力发现面(discoverCapabilities)按调用者会话过滤异领域
9
+ * 描述符——conductor_discover 这类 read 工具无需自己接线 exec 即自动受约束。
10
+ *
11
+ * 无会话(HTTP/MCP 管理面、墙聚合视图)时返回 '',调用方据此降级为不过滤。
12
+ */
13
+ import { AsyncLocalStorage } from 'node:async_hooks'
14
+
15
+ const als = new AsyncLocalStorage()
16
+
17
+ /** 在指定调用者会话上下文里执行 fn(同步/异步均可,ALS 随 await 传播)。 */
18
+ export function runWithCallerSession(sessionId, fn) {
19
+ return als.run(String(sessionId || ''), fn)
20
+ }
21
+
22
+ /** 当前调用者会话 id;不在工具调用上下文里时返回 ''。 */
23
+ export function currentCallerSession() {
24
+ return als.getStore() || ''
25
+ }
@@ -12,8 +12,14 @@ import { validateToolArguments } from '@capyclaw/plugin-kit/tools/validate'
12
12
  import { normalizeToolResult, resultText } from '@capyclaw/plugin-kit/tools/result'
13
13
  import { createServiceApi } from '@capyclaw/plugin-kit/service/api'
14
14
  import { createDescriptorRegistry } from './descriptors.mjs'
15
+ import { createModeGate } from './mode-gate.mjs'
16
+ import { runWithCallerSession, currentCallerSession } from './caller-session.mjs'
17
+ import { admitToolResultImages, resolveAttachments } from './admit-images.mjs'
15
18
 
19
+ export { admitToolResultImages, resolveAttachments } from './admit-images.mjs'
16
20
  export { createDescriptorRegistry } from './descriptors.mjs'
21
+ export { createModeGate } from './mode-gate.mjs'
22
+ export { runWithCallerSession, currentCallerSession } from './caller-session.mjs'
17
23
 
18
24
  const KINDS = new Set(['read', 'write', 'control'])
19
25
 
@@ -23,12 +29,13 @@ export function defineTool({
23
29
  inputSchema = { type: 'object', properties: {}, additionalProperties: false },
24
30
  kind = 'write',
25
31
  since = '1.0.0',
32
+ domain = '',
26
33
  handler,
27
34
  } = {}) {
28
35
  if (!name || typeof name !== 'string') throw new Error('defineTool 需要 name')
29
36
  if (typeof handler !== 'function') throw new Error(`工具 ${name} 需要 handler`)
30
37
  if (!KINDS.has(kind)) throw new Error(`工具 ${name} 的 kind 非法: ${kind}`)
31
- return Object.freeze({ name, description, inputSchema, kind, since, handler })
38
+ return Object.freeze({ name, description, inputSchema, kind, since, domain: String(domain || ''), handler })
32
39
  }
33
40
 
34
41
  export function defineCapability({
@@ -40,6 +47,7 @@ export function defineCapability({
40
47
  dependsOn = [],
41
48
  provides = {},
42
49
  features = [],
50
+ domain = '',
43
51
  tools = [],
44
52
  } = {}) {
45
53
  if (!id || typeof id !== 'string') throw new Error('defineCapability 需要 id')
@@ -53,6 +61,7 @@ export function defineCapability({
53
61
  dependsOn: Object.freeze([...dependsOn]),
54
62
  provides: Object.freeze({ ...provides }),
55
63
  features: Object.freeze([...features]),
64
+ domain: String(domain || ''),
56
65
  tools: Object.freeze([...tools]),
57
66
  })
58
67
  }
@@ -99,7 +108,7 @@ function selectCapabilities(capabilities, enabled) {
99
108
  * @param {Array} capabilities
100
109
  * @param {{ enabled?: string[], ports?: object, report?: Function, reserved?: string[] }} options
101
110
  */
102
- export function createRegistry(capabilities, { enabled = null, ports = null, report = null, reserved = [] } = {}) {
111
+ export function createRegistry(capabilities, { enabled = null, ports = null, report = null, reserved = [], domain = '' } = {}) {
103
112
  validateCapabilities(capabilities)
104
113
  const selected = selectCapabilities(capabilities, enabled)
105
114
 
@@ -145,11 +154,12 @@ export function createRegistry(capabilities, { enabled = null, ports = null, rep
145
154
  title: cap.title,
146
155
  description: cap.description,
147
156
  tags: [...cap.tags],
157
+ domain: cap.domain || domain || '',
148
158
  tools: cap.tools.map((tool) => tool.name),
149
159
  })
150
160
  for (const tool of cap.tools) {
151
161
  TOOLS.push({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema })
152
- TOOL_META[tool.name] = { kind: tool.kind, since: tool.since, capability: cap.id }
162
+ TOOL_META[tool.name] = { kind: tool.kind, since: tool.since, capability: cap.id, domain: tool.domain || cap.domain || domain || '' }
153
163
  TOOL_IMPL[tool.name] = (args) => tool.handler(args || {}, ctx)
154
164
  }
155
165
  }
@@ -174,7 +184,7 @@ export function createRegistry(capabilities, { enabled = null, ports = null, rep
174
184
  if (typeof tool.handler !== 'function') throw new Error(`工具 ${tool.name} 需要 handler`)
175
185
  if (TOOL_IMPL[tool.name]) throw new Error(`工具已存在: ${tool.name}`)
176
186
  TOOLS.push({ name: tool.name, description: tool.description || '', inputSchema: tool.inputSchema || { type: 'object', properties: {} } })
177
- TOOL_META[tool.name] = { kind: tool.kind || 'write', since: tool.since || '1.0.0', capability: capabilityId }
187
+ TOOL_META[tool.name] = { kind: tool.kind || 'write', since: tool.since || '1.0.0', capability: capabilityId, domain: tool.domain || domain || '' }
178
188
  TOOL_IMPL[tool.name] = (args) => tool.handler(args || {}, ctx)
179
189
  return true
180
190
  }
@@ -341,17 +351,27 @@ export function buildInstructions({
341
351
  *
342
352
  * @param {object} ctx DSH cordis context
343
353
  * @param {object} registry createRegistry() 的返回值
344
- * @param {{ namespace?: string }} options
354
+ * @param {{ namespace?: string, domain?: string, modeGate?: object }} options
355
+ * domain:本 registry 的兜底领域(工具/能力未各自声明时用);
356
+ * modeGate:会话模式锁闸(createToolHost 服务级自动注入;独立调用可显式传)。
345
357
  * @returns {() => void} 反注册全部工具
346
358
  */
347
- export function registerWithDsh(ctx, registry, { namespace = '' } = {}) {
359
+ export function registerWithDsh(ctx, registry, { namespace = '', domain = '', modeGate = null } = {}) {
348
360
  if (!ctx?.tools?.register) throw new Error('registerWithDsh: 当前 DSH 没有 ctx.tools.register')
361
+ /* 领域工具一旦注册即声明给模式锁,并挂全局 guard 兜底(幂等)。 */
362
+ if (modeGate) modeGate.install(ctx.tools)
349
363
  const disposers = []
350
364
  try {
351
365
  for (const tool of registry?.TOOLS || []) {
352
366
  const impl = registry.TOOL_IMPL?.[tool.name]
353
367
  if (typeof impl !== 'function') throw new Error(`registerWithDsh: 工具缺少实现 ${tool.name}`)
354
368
  const name = namespace ? `${namespace}_${tool.name}` : tool.name
369
+ const toolDomain = registry.TOOL_META?.[tool.name]?.domain || domain || ''
370
+ let when
371
+ if (modeGate && toolDomain) {
372
+ modeGate.declareTools(toolDomain, [name])
373
+ when = modeGate.whenFor(name)
374
+ }
355
375
  disposers.push(ctx.tools.register({
356
376
  name,
357
377
  description: tool.description || '',
@@ -364,16 +384,20 @@ export function registerWithDsh(ctx, registry, { namespace = '' } = {}) {
364
384
  ? value.content
365
385
  : normalizeToolResult(value).content),
366
386
  },
367
- execute: async (args, exec) => {
387
+ execute: async (args, exec) => runWithCallerSession(exec?.agent?.session?.id, async () => {
368
388
  const normalized = normalizeToolResult(await impl(args, exec))
369
389
  /* DSH 原生面成功恒 isError:false,失败必须 throw 才走错误路径(B 轴 P0-1)。
370
390
  * 把工具自报的 isError:true 转成 throw,与 MCP 面的失败语义对齐。 */
371
391
  if (normalized.isError === true) {
372
392
  throw new Error(resultText(normalized) || `工具 ${name} 执行失败`)
373
393
  }
374
- return normalized
375
- },
376
- }))
394
+ /* 图像准入:裸 base64 图像块(rsp_screen/browser_screenshot 等)必须先持久化成
395
+ * attachment ref 再入 session 日志,否则下一步序列化读 block.attachment.attachmentId
396
+ * 抛错、永久毒化该会话(2026-11-22 根因)。MCP 面不走这里,保留 wire 形态。 */
397
+ const content = await admitToolResultImages(normalized.content, resolveAttachments(exec, ctx), { name })
398
+ return { ...normalized, content }
399
+ }),
400
+ }, when ? { when } : {}))
377
401
  }
378
402
  } catch (error) {
379
403
  /* 全有或全无:任一工具注册失败,逆序释放已注册的,避免部分注册泄漏(B 轴 P0-6)。 */
@@ -392,9 +416,12 @@ export function registerWithDsh(ctx, registry, { namespace = '' } = {}) {
392
416
  export function createToolHost(config = {}) {
393
417
  // 跨套件能力发现注册表(互联标准 §A.4/§E)。深度校验器可选注入(suite-kit)。
394
418
  const descriptors = createDescriptorRegistry({ validate: config.validateDescriptor })
419
+ // 会话模式锁:全服务共享一个闸实例(所有套件的注册都经此)。getWorkStore 惰性解析
420
+ // (driver 注入 () => safeGet(ctx,'workStore'));底座缺席则降级为恒可见、不拒。
421
+ const modeGate = createModeGate({ getWorkStore: config.getWorkStore })
395
422
  return {
396
- api: createServiceApi('toolHost', '1.1.0', ['dsl', 'registry', 'validate', 'contract', 'mcp', 'instructions', 'native-tools', 'descriptors']),
397
- version: '0.2.0',
423
+ api: createServiceApi('toolHost', '1.2.0', ['dsl', 'registry', 'validate', 'contract', 'mcp', 'instructions', 'native-tools', 'descriptors', 'mode-gate']),
424
+ version: '0.3.0',
398
425
  defineTool,
399
426
  defineCapability,
400
427
  createRegistry: (capabilities, options = {}) => createRegistry(capabilities, { ...config, ...options }),
@@ -402,12 +429,16 @@ export function createToolHost(config = {}) {
402
429
  createToolDispatcher,
403
430
  createCapabilityReport,
404
431
  buildInstructions,
405
- registerWithDsh,
432
+ // 服务级注册自动带会话模式锁(when 可见性 + guard 硬拒 + 调用者会话 ALS),套件零接线。
433
+ registerWithDsh: (ctx, registry, options = {}) => registerWithDsh(ctx, registry, { modeGate, ...options }),
406
434
  validateToolArguments,
435
+ modeGate,
407
436
  // 能力描述符注册/发现(编排器按类型动态发现,套件零互依赖)。
408
437
  registerCapabilityDescriptor: (descriptor, options) => descriptors.register(descriptor, options),
409
438
  unregisterCapabilityDescriptor: (name) => descriptors.unregister(name),
410
- discoverCapabilities: (query) => descriptors.discover(query),
439
+ // 发现面按调用者会话过滤:原生工具调用里自动从 ALS 取会话(conductor_discover 无需接线);
440
+ // HTTP/墙等管理面无会话 → 不过滤(全局视图)。query.sessionId 可显式覆盖。
441
+ discoverCapabilities: (query = {}) => modeGate.filterEntries(descriptors.discover(query), query.sessionId || currentCallerSession()),
411
442
  capabilityCatalog: () => descriptors.catalog(),
412
443
  listSurfaces: () => descriptors.listSurfaces(),
413
444
  }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * 会话模式锁 —— 工具面标准框架的强制闸(基础设施能力,非各套件自接)。
3
+ *
4
+ * 设计目标(用户诉求):锁定一种工作模式(如 rsp)后,本会话只看得见、调得动
5
+ * 该领域的工具;其余已注册能力(browser_* 等)从工具声明里消失,且即便被强行
6
+ * 调用也在分发层硬拒。所有经 tool-host 注册的能力自动受此约束。
7
+ *
8
+ * 三道原生闸里的两道在此落地:
9
+ * · when(可见性):registerWithDsh / bridge host 给每个领域工具挂 whenFor(name),
10
+ * DSH 每步 resolve() 求值,false 同时从声明与分发中排除该工具。
11
+ * · guard(分发硬拒,兜底):install(tools) 挂一个全局 ToolGuard,异领域调用返回
12
+ * denial。单调不可翻回,兜住任何绕过 when 的路径。
13
+ *
14
+ * 领域来源:TOOL_META.domain(defineTool/defineCapability/createRegistry 声明)。
15
+ * 存储真源:work-store.getSessionMode(sid)(终生固化,无 unlock)。
16
+ * 降级:无 workStore / 无 sid / 未锁定 → 恒可见、不拒(与既有“底座缺席不启用”一致)。
17
+ * 无 domain 的工具(conductor/capyclaw/框架核心 mode_*)恒可见,不受锁限制。
18
+ */
19
+
20
+ /**
21
+ * @param {{ getWorkStore?: () => object|null }} deps
22
+ */
23
+ export function createModeGate({ getWorkStore } = {}) {
24
+ const domainByTool = new Map() // 原生工具名 → domain
25
+ const domainBySuite = new Map() // 套件名 → domain(描述符发现面按 suite 兜底)
26
+ const lockCache = new Map() // sid → kind(锁终生固化,一旦落定永不变更,可缓存)
27
+ let guardInstalled = false
28
+ const guardDisposers = []
29
+ let coreToolsRegistered = false
30
+ const coreDisposers = []
31
+
32
+ function store() {
33
+ try { return typeof getWorkStore === 'function' ? getWorkStore() : null } catch { return null }
34
+ }
35
+
36
+ /** 当前会话锁定的工作模式 kind;未锁定/底座缺席/无 sid → null。 */
37
+ function modeOf(sessionId) {
38
+ const sid = String(sessionId || '').trim()
39
+ if (!sid) return null
40
+ if (lockCache.has(sid)) return lockCache.get(sid)
41
+ const ws = store()
42
+ if (!ws || typeof ws.getSessionMode !== 'function') return null
43
+ let rec = null
44
+ try { rec = ws.getSessionMode(sid) } catch { return null }
45
+ const kind = rec && rec.kind ? String(rec.kind) : null
46
+ if (kind) lockCache.set(sid, kind) // 只缓存已落定的锁;null 不缓存(可能稍后被认领)
47
+ return kind
48
+ }
49
+
50
+ /** 领域工具在指定会话里是否可见。无 domain / 未锁定 / 同领域 → 可见。 */
51
+ function isVisible(domain, sessionId) {
52
+ if (!domain) return true
53
+ const lock = modeOf(sessionId)
54
+ return !lock || domain === lock
55
+ }
56
+
57
+ /** 声明一组工具属于某领域(registerWithDsh / bridge host 注册时调用)。 */
58
+ function declareTools(domain, names = [], suite = domain) {
59
+ const d = String(domain || '').trim()
60
+ if (!d) return
61
+ for (const name of names || []) {
62
+ if (name) domainByTool.set(String(name), d)
63
+ }
64
+ if (suite) domainBySuite.set(String(suite), d)
65
+ }
66
+
67
+ /** 某工具的领域;未声明 → ''(恒可见)。 */
68
+ function domainOf(name) {
69
+ return domainByTool.get(String(name)) || ''
70
+ }
71
+
72
+ /**
73
+ * DSH register 的 when 条件。未声明领域的工具返回 undefined(不挂 when,恒可见,
74
+ * 也避免给内置/核心工具增加每步求值开销)。
75
+ * @returns {((context: object) => boolean)|undefined}
76
+ */
77
+ function whenFor(name) {
78
+ const domain = domainOf(name)
79
+ if (!domain) return undefined
80
+ return (context) => isVisible(domain, context?.agent?.session?.id)
81
+ }
82
+
83
+ /**
84
+ * 全局 ToolGuard(分发硬拒兜底)。非领域工具立即放行(不读 store,内置工具零开销);
85
+ * 领域工具在异领域锁定的会话里返回 denial。
86
+ * @returns {{reason: string, info: object}|undefined}
87
+ */
88
+ function guard(execution) {
89
+ const name = execution?.name
90
+ const domain = domainByTool.get(String(name))
91
+ if (!domain) return undefined
92
+ const lock = modeOf(execution?.agent?.session?.id)
93
+ if (!lock || domain === lock) return undefined
94
+ return {
95
+ reason: `本会话已锁定为「${lock}」工作模式,「${name}」属于「${domain}」领域,已被框架屏蔽。`
96
+ + `请只用「${lock}」领域的工具完成任务;确需其他领域,请新开一个会话。`,
97
+ info: { name: 'SessionModeLocked', code: 'SESSION_MODE_LOCKED', reason: `locked to ${lock}, tool domain ${domain}` },
98
+ }
99
+ }
100
+
101
+ /** 框架核心工具 mode_lock / mode_status(无领域,恒可见)——显式锁定入口与状态查询。
102
+ * 存储经 modeGate 的 getWorkStore 解析(不依赖插件 ctx),故可在任何 tools 就绪时机注册。 */
103
+ function coreTools() {
104
+ const textRender = (_args, value) => [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }]
105
+ const OUTPUT_SCHEMA = { type: 'object', additionalProperties: true }
106
+ const modeLock = {
107
+ name: 'mode_lock',
108
+ description: '把当前会话锁定到一种工作模式(领域),如 rsp/browser/ppt/canvas。锁定后本会话只看得见、调得动该领域的工具,'
109
+ + '其余领域能力被框架从工具面屏蔽并在分发层硬拒。锁终生固化、不可解锁;确需其他领域请新开一个会话。',
110
+ parameters: {
111
+ type: 'object',
112
+ properties: { kind: { type: 'string', description: '要锁定的工作模式/领域,如 rsp、browser、ppt、canvas' } },
113
+ required: ['kind'],
114
+ additionalProperties: false,
115
+ },
116
+ output: { schema: OUTPUT_SCHEMA, render: textRender },
117
+ execute: async (args, exec) => {
118
+ const kind = String(args?.kind || '').trim()
119
+ if (!kind) return { ok: false, error: '需要 kind(要锁定的工作模式/领域)' }
120
+ const sid = exec?.agent?.session?.id
121
+ if (!sid) return { ok: false, error: '无法识别当前会话,不能锁定' }
122
+ const ws = store()
123
+ if (!ws || typeof ws.claimSessionMode !== 'function') return { ok: false, error: 'work-store 底座缺席,无法锁定' }
124
+ const res = ws.claimSessionMode(sid, kind, 'mode-lock', { explicit: true })
125
+ if (res && res.ok === false) {
126
+ return { ok: false, lockedTo: res.lockedTo, error: `本会话已固化为「${res.lockedTo}」模式,不能改为「${kind}」。确需其他领域请新开一个会话。` }
127
+ }
128
+ return {
129
+ ok: true, kind: res.kind, fresh: !!res.fresh, explicit: true,
130
+ message: res.fresh ? `已锁定为「${res.kind}」工作模式,本会话此后只用该领域工具。` : `本会话已处于「${res.kind}」工作模式。`,
131
+ }
132
+ },
133
+ }
134
+ const modeStatus = {
135
+ name: 'mode_status',
136
+ description: '查询当前会话的工作模式锁状态:是否锁定、锁定到哪个领域、由谁何时认领。未锁定时所有领域工具可见。',
137
+ parameters: { type: 'object', properties: {}, additionalProperties: false },
138
+ output: { schema: OUTPUT_SCHEMA, render: textRender },
139
+ execute: async (_args, exec) => {
140
+ const sid = exec?.agent?.session?.id
141
+ const ws = store()
142
+ if (!ws || typeof ws.getSessionMode !== 'function') return { locked: false, reason: 'work-store 底座缺席' }
143
+ if (!sid) return { locked: false, reason: '无法识别当前会话' }
144
+ const rec = ws.getSessionMode(sid)
145
+ if (!rec) return { locked: false, kind: null, message: '本会话未锁定工作模式,所有领域工具可见。' }
146
+ return {
147
+ locked: true, kind: rec.kind, claimedBy: rec.claimedBy || '', claimedAt: rec.claimedAt || '', explicit: !!rec.explicit,
148
+ message: `本会话已锁定为「${rec.kind}」工作模式,其余领域工具已被屏蔽。`,
149
+ }
150
+ },
151
+ }
152
+ return [modeLock, modeStatus]
153
+ }
154
+
155
+ /** 把 guard + 核心锁定工具挂到 DSH tools 服务(幂等)。每个套件在 tools 就绪时都会调用,
156
+ * 故核心工具注册不依赖 tool-host driver apply 那一刻 tools 是否已就绪(加载顺序鲁棒)。返回 disposer。 */
157
+ function install(tools) {
158
+ if (!tools) return () => {}
159
+ if (!guardInstalled && typeof tools.guard === 'function') {
160
+ try {
161
+ const dispose = tools.guard(guard)
162
+ if (typeof dispose === 'function') guardDisposers.push(dispose)
163
+ guardInstalled = true
164
+ } catch { /* 底座不支持 guard 时降级:仅 when 生效 */ }
165
+ }
166
+ if (!coreToolsRegistered && typeof tools.register === 'function') {
167
+ for (const tool of coreTools()) {
168
+ try {
169
+ const d = tools.register(tool)
170
+ if (typeof d === 'function') coreDisposers.push(d)
171
+ } catch (err) {
172
+ console.warn(`[tool-host] 注册核心工具 ${tool.name} 失败:`, err?.message || err)
173
+ }
174
+ }
175
+ coreToolsRegistered = true
176
+ }
177
+ return () => {
178
+ for (const dispose of guardDisposers.splice(0)) {
179
+ try { dispose() } catch { /* 忽略重复释放 */ }
180
+ }
181
+ for (const dispose of coreDisposers.splice(0)) {
182
+ try { dispose() } catch { /* 忽略重复释放 */ }
183
+ }
184
+ guardInstalled = false
185
+ coreToolsRegistered = false
186
+ }
187
+ }
188
+
189
+ /**
190
+ * 能力发现面过滤:锁定会话里剔除异领域描述符(conductor_discover 自动受约束)。
191
+ * 无 domain 的描述符(编排/核心基建)保留。未锁定 → 原样返回。
192
+ */
193
+ function filterEntries(entries, sessionId) {
194
+ const lock = modeOf(sessionId)
195
+ if (!lock) return entries
196
+ return (entries || []).filter((entry) => {
197
+ const d = entry?.descriptor || {}
198
+ const domain = domainByTool.get(String(d.tool || d.name)) || domainBySuite.get(String(entry?.suite)) || ''
199
+ return !domain || domain === lock
200
+ })
201
+ }
202
+
203
+ return { declareTools, domainOf, modeOf, isVisible, whenFor, guard, install, filterEntries }
204
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/browser-workbench",
3
- "version": "0.1.18",
3
+ "version": "0.1.20",
4
4
  "description": "浏览器操控工作台运行时:18 个 browser_* MCP 工具(导航/快照/点击/填写/按键/下拉/上传/滚动/批量连做/拖拽/标签页/截图)+ Playwright 引擎(有头可见、登录态持久化)+ 可视化工作台。",
5
5
  "type": "module",
6
6
  "main": "./plugin.mjs",
@@ -51,7 +51,7 @@
51
51
  "@capyclaw/foundation": "^0.1.9",
52
52
  "@capyclaw/plugin-kit": "^0.2.6",
53
53
  "@capyclaw/service-host": "^0.1.5",
54
- "@capyclaw/tool-host": "^0.2.0",
54
+ "@capyclaw/tool-host": "^0.3.0",
55
55
  "playwright": "^1.64.0"
56
56
  },
57
57
  "author": {
@@ -10,7 +10,7 @@ import { createCapabilityReport } from './shared/tool-host.mjs'
10
10
  export const CONTRACT_VERSION = '1.3.0'
11
11
 
12
12
  /** 工作台包版本。 */
13
- export const PACKAGE_VERSION = '0.1.18'
13
+ export const PACKAGE_VERSION = '0.1.20'
14
14
 
15
15
  /** 生成模型可读的能力报告。 */
16
16
  export function capabilityReport(args, workbenchUrl = '', runtime = {}) {
@@ -128,6 +128,14 @@ async function activate(ctx, config) {
128
128
  const registry = relay.tools
129
129
  const tools = safeGet(ctx, 'tools')
130
130
  const toolState = { registered: [], errors: [], hasTools: !!(tools && typeof tools.register === 'function') }
131
+ /* 会话模式锁(框架级强制):把本套件工具声明为 browser 领域,注册时逐个挂 when
132
+ * 可见性条件,并装全局 guard 兜底。锁定其他领域的会话里,本套件工具从工具面消失
133
+ * 且被硬拒。toolHost/modeGate 缺席(老宿主)时优雅降级为不屏蔽。 */
134
+ const modeGate = toolHost && toolHost.modeGate
135
+ if (modeGate && registry && Array.isArray(registry.TOOLS)) {
136
+ modeGate.declareTools('browser', registry.TOOLS.map((t) => t.name), 'browser')
137
+ if (toolState.hasTools) modeGate.install(tools)
138
+ }
131
139
  const OUTPUT_SCHEMA = { type: 'object', additionalProperties: true }
132
140
 
133
141
  function toolText(value) {
@@ -146,6 +154,7 @@ async function activate(ctx, config) {
146
154
  if (registry && Array.isArray(registry.TOOLS) && toolState.hasTools) {
147
155
  for (const tool of registry.TOOLS) {
148
156
  try {
157
+ const when = modeGate && modeGate.whenFor(tool.name)
149
158
  const dispose = tools.register({
150
159
  name: tool.name,
151
160
  description: tool.description,
@@ -157,7 +166,7 @@ async function activate(ctx, config) {
157
166
  /* 第二个参数是 DSH 的 exec(含 exec.agent.session.id):工具靠它知道是哪个
158
167
  * 会话在调用,多会话工作台才能把读写落到调用者自己那份文档上。 */
159
168
  execute: async (args, exec) => registry.TOOL_IMPL[tool.name](args || {}, exec),
160
- })
169
+ }, when ? { when } : {})
161
170
  if (typeof dispose === 'function') disposers.push(dispose)
162
171
  toolState.registered.push(tool.name)
163
172
  } catch (error) {
@@ -11,7 +11,7 @@
11
11
  },
12
12
  "tool-host": {
13
13
  "package": "@capyclaw/tool-host",
14
- "version": "0.2.0",
14
+ "version": "0.3.0",
15
15
  "apiVersion": "1.1.0",
16
16
  "spec": "@capyclaw/tool-host/src",
17
17
  "sha256": "23256dbcd5cbee0b96b33c97e4eb4e74d0e169cbdde52f91d4526f2fc0f60d3e"
@@ -111,7 +111,13 @@ export function createWorkbench(spec) {
111
111
  * 已创建的资源——否则引擎/仓库泄漏在仍存活的进程里(reused 分支的 stop 是
112
112
  * no-op,不会有人替它清理)。外部传入的 assetStore 不归本框架关。 */
113
113
  let app
114
+ /* 资产仓库周期 GC:默认只清孤儿临时文件(安全——内容寻址资产被稿件引用,
115
+ * 按龄/LRU 淘汰会毁掉旧稿渲染,必须经 tuning 显式 opt-in)。定时器 unref,
116
+ * 不拖住进程退出;所有关闭路径都要清掉它。 */
117
+ let assetGcTimer = null
118
+ const stopAssetGc = () => { if (assetGcTimer) { clearInterval(assetGcTimer); assetGcTimer = null } }
114
119
  const closeCreatedResources = async (why) => {
120
+ stopAssetGc()
115
121
  try { if (spec.beforeStop) await spec.beforeStop(ctx) } catch (error) { console.error(`[${spec.id}] ${why}:beforeStop 失败`, error?.message || error) }
116
122
  try { if (!givenAssetStore) await assetStore?.close?.() } catch (error) { console.error(`[${spec.id}] ${why}:assetStore 关闭失败`, error?.message || error) }
117
123
  try { await store?.close?.() } catch (error) { console.error(`[${spec.id}] ${why}:store 关闭失败`, error?.message || error) }
@@ -213,6 +219,32 @@ export function createWorkbench(spec) {
213
219
  }
214
220
  }
215
221
 
222
+ /* 只有真正提供服务的形态才起周期 GC(reused 形态已回收资源,不起定时器)。
223
+ * tuning.assetGcIntervalMs<=0 可整体关闭;maxAgeMs/maxBytes 缺省 0=不按龄/量淘汰。 */
224
+ if (assetStore && typeof assetStore.gc === 'function') {
225
+ const gcIntervalMs = Number(tuning.assetGcIntervalMs ?? 3600000)
226
+ if (gcIntervalMs > 0) {
227
+ const gcOptions = {
228
+ maxAgeMs: Number(tuning.assetGcMaxAgeMs) || 0,
229
+ maxBytes: Number(tuning.assetGcMaxBytes) || 0,
230
+ }
231
+ const runGc = async () => {
232
+ try {
233
+ const result = await assetStore.gc(gcOptions)
234
+ if (result?.removed || result?.orphanTmpRemoved) {
235
+ console.log(`[${spec.id}] 资产 GC:清理 ${result.removed || 0} 项、孤儿临时文件 ${result.orphanTmpRemoved || 0} 个,释放 ${result.freedBytes || 0} 字节`)
236
+ }
237
+ } catch (error) {
238
+ console.error(`[${spec.id}] 资产 GC 失败(下轮再试):`, error?.message || error)
239
+ }
240
+ }
241
+ assetGcTimer = setInterval(runGc, gcIntervalMs)
242
+ assetGcTimer.unref?.()
243
+ /* 启动即跑一轮:清掉上次进程崩溃留下的孤儿 tmp,不必等第一个周期。 */
244
+ runGc()
245
+ }
246
+ }
247
+
216
248
  try {
217
249
  /* 业务钩子:设置 URL 环境变量、崩溃恢复等(必须在工具装载之前)。 */
218
250
  if (spec.onListening) await spec.onListening(ctx, info, url)
@@ -255,12 +287,14 @@ export function createWorkbench(spec) {
255
287
  tools: ctx.toolsRegistry || null,
256
288
  ...(spec.resultExtras ? spec.resultExtras(ctx) : {}),
257
289
  stop: async () => {
290
+ stopAssetGc()
258
291
  if (!ctx.embedded) removeDiscovery(hostDir)
259
292
  if (spec.beforeStop) await spec.beforeStop(ctx)
260
293
  await info.stop()
261
294
  },
262
295
  }
263
296
  } catch (error) {
297
+ stopAssetGc()
264
298
  try { if (!ctx.embedded) removeDiscovery(hostDir) } catch { /* 忽略 */ }
265
299
  try { if (spec.beforeStop) await spec.beforeStop(ctx) } catch { /* 忽略 */ }
266
300
  try { await info.stop() } catch { /* 忽略 */ }