@glodon-aiot/workspace-sandbox 0.2.0-alpha.4 → 0.2.0-alpha.5

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 CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  供端侧宿主调用:在工程目录内读写文件,并在 Microsoft Execution Containers(MXC)里执行命令和脚本。
4
4
 
5
- 需要 Node.js 24。生产接入使用协议 2:页面通过 WebSocket 直连本进程,宿主只管理进程并转发状态。文件字节和命令输出不经过宿主,页面也拿不到工程绝对路径。
5
+ 需要 Node.js 24。生产接入使用协议 1:页面通过 WebSocket 直连本进程,宿主只管理进程并转发状态。文件字节和命令输出不经过宿主,页面也拿不到工程绝对路径。
6
6
 
7
7
  ## 生产接入
8
8
 
@@ -17,11 +17,11 @@ workspace-sandbox --listen --root /path/to/project --origin https://app.example
17
17
  stdout 第一行是以下两种管理事件之一:
18
18
 
19
19
  ```json
20
- { "protocol": 2, "op": "ready", "url": "ws://127.0.0.1:53124", "token": "<64 位十六进制>", "pid": 1234 }
20
+ { "protocol": 1, "op": "ready", "url": "ws://127.0.0.1:53124", "token": "<64 位十六进制>", "pid": 1234 }
21
21
  ```
22
22
 
23
23
  ```json
24
- { "protocol": 2, "op": "fatal", "reason": "invalid-config", "message": "沙箱启动参数不正确。" }
24
+ { "protocol": 1, "op": "fatal", "reason": "invalid-config", "message": "沙箱启动参数不正确。" }
25
25
  ```
26
26
 
27
27
  `fatal.message` 不包含工程路径或令牌。`ready` 之后 stdout 只写 `status` 和 `bye`;宿主必须持续读取 stdout 和 stderr,避免管道堵塞。令牌不能写入宿主日志。
@@ -29,7 +29,7 @@ stdout 第一行是以下两种管理事件之一:
29
29
  宿主把 `sandbox: { state, url, token, protocol }` 交给页面。页面建立连接后的第一帧必须是:
30
30
 
31
31
  ```json
32
- { "protocol": 2, "op": "auth", "token": "..." }
32
+ { "protocol": 1, "op": "auth", "token": "..." }
33
33
  ```
34
34
 
35
35
  认证成功后,文件和命令请求直接在页面与沙箱之间传输。WebSocket 不接受 `shutdown`、更换 `root` 或更换来源。
@@ -54,7 +54,7 @@ stdout 第一行是以下两种管理事件之一:
54
54
  - `file://` 页面的 Origin 通常是 `null`,只有调试时才使用 `--allow-null-origin`。
55
55
  - SDK 只加载在可信页面中;同一页面里的脚本能够读取内存中的令牌。
56
56
 
57
- ## 协议 2 数据面
57
+ ## 协议 1 数据面
58
58
 
59
59
  文本帧是 UTF-8 JSON,最大 256 KB;文件内容使用二进制帧,单片载荷最大 1 MB。所有业务请求带客户端生成的字符串 `id`。
60
60
 
@@ -64,7 +64,8 @@ stdout 第一行是以下两种管理事件之一:
64
64
  | `read` | 按 `offset` / `maxBytes` 读取窗口,最大 50 MB |
65
65
  | `write` | 先发大小和路径,再按偏移发送二进制片;同目录临时文件写完后原子替换 |
66
66
  | `mkdir` / `remove` / `move` | 修改工程内文件和目录 |
67
- | `exec` | 流式返回 `stdout` / `stderr`,最后发送 `exit` |
67
+ | `exec` | 流式返回 `stdout` / `stderr`,最后发送 `exit`。带 `skill` 时只为该次进程只读挂载对应技能版本目录 |
68
+ | `installSkill` / `skillStatus` / `skillRead` / `skillPrune` | 安装、查询、读取和清理工程外的技能缓存。ZIP 由页面传入,本进程不访问下载地址 |
68
69
  | `cancel` | 取消同一 `id` 的请求;命令会结束整个子进程树 |
69
70
 
70
71
  路径使用 `/`,只允许工程根内的相对路径。空字符串和 `.` 表示工程根;`..`、盘符、反斜杠和绝对路径会返回 `SecurityError`。请求中不能传入或替换 `root`。
@@ -75,6 +76,8 @@ stdout 第一行是以下两种管理事件之一:
75
76
 
76
77
  文件覆盖使用临时文件和原子替换。宿主或其他程序正在修改/占用目标时,操作返回 `NoModificationAllowedError`,原文件保持不变。
77
78
 
79
+ 技能缓存与工程视图缓存分开,不因路径含盘符、空格或非 ASCII 而改到临时目录。Windows 使用 `%LOCALAPPDATA%\glodon-workspace-sandbox`(没有该变量时用 `%USERPROFILE%\AppData\Local\glodon-workspace-sandbox`),macOS 使用 `~/Library/Caches/glodon-workspace-sandbox`,Linux 在 `XDG_CACHE_HOME` 为绝对路径时使用 `$XDG_CACHE_HOME/glodon-workspace-sandbox`,否则使用 `~/.cache/glodon-workspace-sandbox`。其下为 `skills/<applicationId>/<skillId>/<version>/`。页面下载所用的资源令牌不会进入本进程。
80
+
78
81
  ## 运行环境
79
82
 
80
83
  本进程:
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { manifest, selfCheck } from '../src/check.mjs';
3
- import { fatalLine, runListen } from '../src/listen.mjs';
3
+ import { fatalLine, LISTEN_PROTOCOL, runListen } from '../src/listen.mjs';
4
4
 
5
5
  function optionValue(name) {
6
6
  const index = process.argv.indexOf(name);
@@ -18,7 +18,7 @@ function optionValues(name) {
18
18
  let response;
19
19
  if (process.argv.includes('--listen')) {
20
20
  process.on('uncaughtException', () => {
21
- process.stdout.write(`${JSON.stringify({ protocol: 2, op: 'bye', reason: 'fatal' })}\n`);
21
+ process.stdout.write(`${JSON.stringify({ protocol: LISTEN_PROTOCOL, op: 'bye', reason: 'fatal' })}\n`);
22
22
  process.exit(1);
23
23
  });
24
24
  const root = optionValue('--root');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glodon-aiot/workspace-sandbox",
3
- "version": "0.2.0-alpha.4",
3
+ "version": "0.2.0-alpha.5",
4
4
  "description": "供端侧宿主调用:在工程目录内读写文件,并在 Microsoft Execution Containers 里执行命令和脚本。",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/exec.mjs CHANGED
@@ -16,6 +16,7 @@ import {
16
16
  SYNTHETIC_DIR_MESSAGE,
17
17
  truncateOutput,
18
18
  } from './policy.mjs';
19
+ import { skillDirectory } from './skills.mjs';
19
20
  import { ensureView, outputMappings, toRealCommand, toVirtualCwd, toVirtualText } from './view.mjs';
20
21
 
21
22
  const PROGRAMS = new Set(['python3', 'node', 'sh']);
@@ -46,6 +47,11 @@ function makeBin(tmp, python) {
46
47
 
47
48
  /** 脚本路径换成视图路径,命令文本里不出现工程真实路径。 */
48
49
  function scriptPath(request, view) {
50
+ if (request.skillDir) {
51
+ const real = resolveInside(request.skillDir, request.argv[1]);
52
+ if (!statSync(real).isFile()) throw sandboxError('TypeMismatchError', '脚本不是文件。');
53
+ return real;
54
+ }
49
55
  const real = resolveInside(request.rootReal, request.argv[1]);
50
56
  if (!statSync(real).isFile()) throw sandboxError('TypeMismatchError', '脚本不是文件。');
51
57
  return join(view, request.argv[1]);
@@ -185,6 +191,11 @@ export async function runExec(request) {
185
191
  }
186
192
  const containment = await selectContainment();
187
193
  const view = ensureView(request.rootReal);
194
+ if (request.skill) {
195
+ request.skillDir = skillDirectory(request.skill.applicationId, request.skill.skillId, request.skill.version);
196
+ if (!existsSync(join(request.skillDir, 'installed.json'))) throw sandboxError('NotFoundError', '技能脚本不存在。');
197
+ request.skillLabel = `skills/${request.skill.name}`;
198
+ }
188
199
  const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'glodon-sandbox-')));
189
200
  try {
190
201
  const pythonPath = request.python ?? defaultPython();
@@ -209,7 +220,7 @@ export async function runExec(request) {
209
220
  );
210
221
  const launch = {
211
222
  filesystem: {
212
- readonlyPaths: [view, dirname(dirname(process.execPath)), ...(python?.readonlyPaths ?? [])],
223
+ readonlyPaths: [view, dirname(dirname(process.execPath)), ...(python?.readonlyPaths ?? []), ...(request.skillDir ? [request.skillDir] : [])],
213
224
  readwritePaths: [request.rootReal, tmp],
214
225
  },
215
226
  network: { egress: { default: 'deny' } },
@@ -222,6 +233,8 @@ export async function runExec(request) {
222
233
  };
223
234
  const command = [shellPath(), runner].map(quoteArg).join(' ');
224
235
  const mappings = outputMappings({ view, rootReal: request.rootReal, rootGiven: request.root });
236
+ if (request.skillDir) mappings.push([request.skillDir, request.skillLabel]);
237
+ mappings.sort((left, right) => right[0].length - left[0].length);
225
238
  if (typeof request.onOutput === 'function') {
226
239
  return await streamExec({ containment, command, launch, request, mappings, marker, note: python?.note ?? '' });
227
240
  }
package/src/listen.mjs CHANGED
@@ -17,9 +17,10 @@ import {
17
17
  } from './files.mjs';
18
18
  import { sandboxError } from './policy.mjs';
19
19
  import { runExec } from './exec.mjs';
20
+ import { installSkillZip, pruneSkills, readSkillFile, skillStatus, SKILL_ZIP_LIMIT } from './skills.mjs';
20
21
  import { cacheBase, rootHash } from './view.mjs';
21
22
 
22
- export const LISTEN_PROTOCOL = 2;
23
+ export const LISTEN_PROTOCOL = 1;
23
24
  const MAX_TEXT = 256 * 1024;
24
25
  const MAX_FRAME = 1024 * 1024;
25
26
  const HIGH_WATER = 4 * 1024 * 1024;
@@ -147,7 +148,7 @@ async function writeExecLog(rootReal, id, text) {
147
148
  }
148
149
 
149
150
  /**
150
- * 在 127.0.0.1 上提供协议 2 的 WebSocket。stdout 只写 ready、fatal、status、bye。
151
+ * 在 127.0.0.1 上提供协议 1 的 WebSocket。stdout 只写 ready、fatal、status、bye。
151
152
  * execute 可在测试里替换,默认走 MXC。
152
153
  */
153
154
  export function runListen({
@@ -338,6 +339,10 @@ export function runListen({
338
339
  await beginWrite(socket, message, pendingWrites);
339
340
  return;
340
341
  }
342
+ if (message.op === 'installSkill') {
343
+ await beginInstall(socket, message, pendingWrites);
344
+ return;
345
+ }
341
346
  if (message.op === 'exec') {
342
347
  void beginCommand(socket, message);
343
348
  return;
@@ -381,6 +386,29 @@ export function runListen({
381
386
  await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ok: true, ...result });
382
387
  return;
383
388
  }
389
+ if (message.op === 'skillStatus') {
390
+ const skills = await skillStatus(message.applicationId);
391
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ok: true, skills });
392
+ return;
393
+ }
394
+ if (message.op === 'skillRead') {
395
+ const bytes = await readSkillFile(message.applicationId, message.skillId, message.version, message.path ?? '');
396
+ let sent = 0;
397
+ while (sent < bytes.length) {
398
+ const payload = bytes.subarray(sent, sent + MAX_FRAME);
399
+ const eof = sent + payload.length >= bytes.length;
400
+ await waitForRoom(socket);
401
+ socket.send(encodeBinaryFrame({ id: message.id, offset: sent, eof, payload }));
402
+ sent += payload.length;
403
+ }
404
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ok: true, size: bytes.length, returned: bytes.length });
405
+ return;
406
+ }
407
+ if (message.op === 'skillPrune') {
408
+ const result = await pruneSkills(message.applicationId, Array.isArray(message.keep) ? message.keep : [], Array.isArray(message.busy) ? message.busy : []);
409
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ok: true, ...result });
410
+ return;
411
+ }
384
412
  if (message.op === 'read') {
385
413
  const window = await readFileWindow(rootReal, message.path ?? '', message.offset ?? 0, message.maxBytes ?? MAX_FILE_BYTES);
386
414
  let sent = 0;
@@ -514,6 +542,77 @@ export function runListen({
514
542
  if (size === 0) pending.enqueue({ id: message.id, offset: 0, eof: true, payload: Buffer.alloc(0) });
515
543
  }
516
544
 
545
+ async function beginInstall(socket, message, pendingWrites) {
546
+ if (fileOps >= FILE_OP_LIMIT) {
547
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ...failure(sandboxError('QuotaExceededError', '请求过多。')) });
548
+ return;
549
+ }
550
+ const size = message.size;
551
+ if (!Number.isInteger(size) || size < 0 || size > SKILL_ZIP_LIMIT) {
552
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ...failure(sandboxError('QuotaExceededError', '技能压缩包超过 20 MB。')) });
553
+ return;
554
+ }
555
+ fileOps += 1;
556
+ const chunks = [];
557
+ let received = 0;
558
+ let settled = false;
559
+ let timer;
560
+ const fail = async (error) => {
561
+ if (settled) return;
562
+ settled = true;
563
+ clearTimeout(timer);
564
+ pendingWrites.delete(message.id);
565
+ fileOps -= 1;
566
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ...failure(error) });
567
+ };
568
+ let chunkChain = Promise.resolve();
569
+ const pending = {
570
+ fail,
571
+ enqueue(frame) {
572
+ chunkChain = chunkChain.then(() => pending.chunk(frame)).catch((error) => fail(error));
573
+ },
574
+ chunk: async (frame) => {
575
+ if (frame.offset !== received) {
576
+ await fail(sandboxError('QuotaExceededError', '分片偏移不连续。'));
577
+ return;
578
+ }
579
+ chunks.push(frame.payload);
580
+ received += frame.payload.length;
581
+ clearTimeout(timer);
582
+ timer = setTimeout(() => fail(sandboxError('AbortError', '写入超时。')), WRITE_IDLE_MS);
583
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, op: 'ack', offset: received });
584
+ if (!frame.eof) return;
585
+ if (received !== size) {
586
+ await fail(sandboxError('QuotaExceededError', '写入长度与 size 不一致。'));
587
+ return;
588
+ }
589
+ try {
590
+ const result = await installSkillZip({
591
+ applicationId: message.applicationId,
592
+ skillId: message.skillId,
593
+ version: message.version,
594
+ name: message.name,
595
+ zip: Buffer.concat(chunks),
596
+ });
597
+ if (settled) return;
598
+ settled = true;
599
+ clearTimeout(timer);
600
+ pendingWrites.delete(message.id);
601
+ fileOps -= 1;
602
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ok: true, ...result });
603
+ } catch (error) {
604
+ await fail(error);
605
+ }
606
+ },
607
+ };
608
+ pendingWrites.set(message.id, pending);
609
+ timer = setTimeout(() => fail(sandboxError('AbortError', '写入超时。')), WRITE_IDLE_MS);
610
+ const queued = earlyFrames.get(message.id) ?? [];
611
+ earlyFrames.delete(message.id);
612
+ for (const frame of queued) pending.enqueue(frame);
613
+ if (size === 0) pending.enqueue({ id: message.id, offset: 0, eof: true, payload: Buffer.alloc(0) });
614
+ }
615
+
517
616
  async function beginCommand(socket, message) {
518
617
  if (command) {
519
618
  await sendJson(socket, {
package/src/skills.mjs ADDED
@@ -0,0 +1,319 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { execFile } from 'node:child_process';
3
+ import { chmod, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
4
+ import { homedir, userInfo } from 'node:os';
5
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
6
+ import { inflateRawSync } from 'node:zlib';
7
+ import { isSafeRelative, sandboxError } from './policy.mjs';
8
+
9
+ export const SKILL_ZIP_LIMIT = 20 * 1024 * 1024;
10
+ export const SKILL_ENTRY_LIMIT = 300;
11
+ export const SKILL_UNCOMPRESSED_LIMIT = 64 * 1024 * 1024;
12
+ const ID_PATTERN = /^[A-Za-z0-9._-]+$/;
13
+
14
+ /** 技能缓存根。与工程视图缓存分开,不因盘符或空格改到临时目录。 */
15
+ export function skillCacheRoot() {
16
+ if (process.platform === 'win32') {
17
+ const base = process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local');
18
+ return join(base, 'glodon-workspace-sandbox');
19
+ }
20
+ if (process.platform === 'darwin') return join(homedir(), 'Library', 'Caches', 'glodon-workspace-sandbox');
21
+ const xdg = process.env.XDG_CACHE_HOME;
22
+ if (typeof xdg === 'string' && isAbsolute(xdg)) return join(xdg, 'glodon-workspace-sandbox');
23
+ return join(homedir(), '.cache', 'glodon-workspace-sandbox');
24
+ }
25
+
26
+ export function assertSkillId(value, label) {
27
+ if (typeof value !== 'string' || !ID_PATTERN.test(value)) {
28
+ throw sandboxError('NotAllowedError', `${label} 只能包含字母、数字、点、下划线和连字符。`);
29
+ }
30
+ }
31
+
32
+ function assertVersion(version) {
33
+ if (!Number.isInteger(version) || version < 1) throw sandboxError('TypeError', '技能版本必须是已发布版本。');
34
+ }
35
+
36
+ function assertName(name) {
37
+ if (typeof name !== 'string' || !name || /[\\/\0]/.test(name) || name === '.' || name === '..') {
38
+ throw sandboxError('NotAllowedError', '技能名称必须是单个目录名。');
39
+ }
40
+ }
41
+
42
+ function appDir(applicationId) {
43
+ assertSkillId(applicationId, 'applicationId');
44
+ return join(skillCacheRoot(), 'skills', applicationId);
45
+ }
46
+
47
+ function versionDir(applicationId, skillId, version) {
48
+ assertSkillId(applicationId, 'applicationId');
49
+ assertSkillId(skillId, 'skillId');
50
+ assertVersion(version);
51
+ return join(appDir(applicationId), skillId, String(version));
52
+ }
53
+
54
+ async function restrict(dir) {
55
+ if (process.platform === 'win32') {
56
+ const user = userInfo().username;
57
+ await new Promise((resolvePromise, reject) => {
58
+ execFile('icacls', [dir, '/inheritance:r', '/grant:r', `${user}:(OI)(CI)F`], (error) => (error ? reject(error) : resolvePromise()));
59
+ });
60
+ return;
61
+ }
62
+ await chmod(dir, 0o700);
63
+ }
64
+
65
+ async function ensureRoot() {
66
+ const root = skillCacheRoot();
67
+ await mkdir(root, { recursive: true, mode: 0o700 });
68
+ await restrict(root);
69
+ return root;
70
+ }
71
+
72
+ function manifestPath(applicationId) {
73
+ return join(appDir(applicationId), 'manifest.json');
74
+ }
75
+
76
+ export async function readManifest(applicationId) {
77
+ try {
78
+ const parsed = JSON.parse(await readFile(manifestPath(applicationId), 'utf8'));
79
+ return Array.isArray(parsed.skills) ? parsed.skills : [];
80
+ } catch (error) {
81
+ if (error?.code === 'ENOENT') return [];
82
+ throw error;
83
+ }
84
+ }
85
+
86
+ async function writeManifest(applicationId, skills) {
87
+ const dir = appDir(applicationId);
88
+ await mkdir(dir, { recursive: true, mode: 0o700 });
89
+ await restrict(dir);
90
+ const file = manifestPath(applicationId);
91
+ const temporary = `${file}.${randomBytes(4).toString('hex')}.partial`;
92
+ await writeFile(temporary, JSON.stringify({ skills }));
93
+ await rename(temporary, file);
94
+ }
95
+
96
+ async function readInstalled(dir) {
97
+ try {
98
+ return JSON.parse(await readFile(join(dir, 'installed.json'), 'utf8'));
99
+ } catch (error) {
100
+ if (error?.code === 'ENOENT') return null;
101
+ throw error;
102
+ }
103
+ }
104
+
105
+ function isComplete(marker, skillId, version) {
106
+ return marker && marker.skillId === skillId && marker.version === version && Number.isInteger(marker.files);
107
+ }
108
+
109
+ export async function skillStatus(applicationId) {
110
+ const entries = await readManifest(applicationId);
111
+ const ready = [];
112
+ for (const entry of entries) {
113
+ if (!entry || typeof entry.skillId !== 'string' || !Number.isInteger(entry.version)) continue;
114
+ const marker = await readInstalled(versionDir(applicationId, entry.skillId, entry.version)).catch(() => null);
115
+ if (isComplete(marker, entry.skillId, entry.version)) ready.push(entry);
116
+ }
117
+ return ready;
118
+ }
119
+
120
+ function findEocd(buffer) {
121
+ const min = Math.max(0, buffer.length - 22 - 65535);
122
+ for (let index = buffer.length - 22; index >= min; index -= 1) {
123
+ if (buffer.readUInt32LE(index) === 0x06054b50) return index;
124
+ }
125
+ throw sandboxError('TypeError', '技能压缩包无效。');
126
+ }
127
+
128
+ function safeEntryName(name) {
129
+ const unified = String(name).replaceAll('\\', '/');
130
+ if (!unified || unified.startsWith('/') || /^[A-Za-z]:/.test(unified)) {
131
+ throw sandboxError('SecurityError', '技能压缩包路径越界。');
132
+ }
133
+ const directory = unified.endsWith('/');
134
+ const parts = unified.split('/').filter((part) => part.length > 0);
135
+ if (parts.some((part) => part === '.' || part === '..')) throw sandboxError('SecurityError', '技能压缩包路径越界。');
136
+ return { relative: parts.join('/'), directory };
137
+ }
138
+
139
+ function extractZip(buffer) {
140
+ if (buffer.length > SKILL_ZIP_LIMIT) throw sandboxError('QuotaExceededError', '技能压缩包超过 20 MB。');
141
+ const eocd = findEocd(buffer);
142
+ const count = buffer.readUInt16LE(eocd + 10);
143
+ if (count > SKILL_ENTRY_LIMIT) throw sandboxError('QuotaExceededError', '技能压缩包文件过多。');
144
+ if (buffer.readUInt32LE(eocd + 16) === 0xffffffff) throw sandboxError('QuotaExceededError', '不支持 Zip64。');
145
+ let cursor = buffer.readUInt32LE(eocd + 16);
146
+ const files = [];
147
+ let total = 0;
148
+ let fileCount = 0;
149
+ for (let index = 0; index < count; index += 1) {
150
+ if (cursor + 46 > buffer.length || buffer.readUInt32LE(cursor) !== 0x02014b50) {
151
+ throw sandboxError('TypeError', '技能压缩包无效。');
152
+ }
153
+ const flags = buffer.readUInt16LE(cursor + 8);
154
+ const method = buffer.readUInt16LE(cursor + 10);
155
+ const compressed = buffer.readUInt32LE(cursor + 20);
156
+ const uncompressed = buffer.readUInt32LE(cursor + 24);
157
+ const nameLength = buffer.readUInt16LE(cursor + 28);
158
+ const extraLength = buffer.readUInt16LE(cursor + 30);
159
+ const commentLength = buffer.readUInt16LE(cursor + 32);
160
+ const external = buffer.readUInt32LE(cursor + 38);
161
+ const localOffset = buffer.readUInt32LE(cursor + 42);
162
+ const name = buffer.toString('utf8', cursor + 46, cursor + 46 + nameLength);
163
+ cursor += 46 + nameLength + extraLength + commentLength;
164
+ if (flags & 1) throw sandboxError('NotAllowedError', '技能压缩包不能加密。');
165
+ if ((external >>> 16 & 0o170000) === 0o120000) throw sandboxError('NotAllowedError', '技能压缩包不能包含符号链接。');
166
+ if (method !== 0 && method !== 8) throw sandboxError('NotAllowedError', '技能压缩包使用了不支持的压缩方法。');
167
+ const entry = safeEntryName(name);
168
+ if (!entry.relative) continue;
169
+ if (entry.directory) {
170
+ files.push({ relative: entry.relative, directory: true, bytes: Buffer.alloc(0) });
171
+ continue;
172
+ }
173
+ fileCount += 1;
174
+ total += uncompressed;
175
+ if (fileCount > SKILL_ENTRY_LIMIT || total > SKILL_UNCOMPRESSED_LIMIT) {
176
+ throw sandboxError('QuotaExceededError', '技能压缩包超过大小或文件数限制。');
177
+ }
178
+ if (localOffset + 30 > buffer.length || buffer.readUInt32LE(localOffset) !== 0x04034b50) {
179
+ throw sandboxError('TypeError', '技能压缩包无效。');
180
+ }
181
+ const localName = buffer.readUInt16LE(localOffset + 26);
182
+ const localExtra = buffer.readUInt16LE(localOffset + 28);
183
+ const dataStart = localOffset + 30 + localName + localExtra;
184
+ const data = buffer.subarray(dataStart, dataStart + compressed);
185
+ if (data.length !== compressed) throw sandboxError('TypeError', '技能压缩包无效。');
186
+ const bytes = method === 0 ? data : inflateRawSync(data);
187
+ if (bytes.length !== uncompressed) throw sandboxError('TypeError', '技能压缩包无效。');
188
+ files.push({ relative: entry.relative, directory: false, bytes });
189
+ }
190
+ if (!files.some((file) => file.relative === 'SKILL.md' && !file.directory)) {
191
+ throw sandboxError('NotAllowedError', '技能压缩包根上必须有 SKILL.md。');
192
+ }
193
+ return files;
194
+ }
195
+
196
+ /**
197
+ * 把 ZIP 装进版本目录。正式目录已完整时丢弃本次内容并更新 manifest。
198
+ * 返回 `{ skipped: true }` 表示沿用已有目录。
199
+ */
200
+ export async function installSkillZip({ applicationId, skillId, version, name, zip }) {
201
+ assertName(name);
202
+ await ensureRoot();
203
+ const dest = versionDir(applicationId, skillId, version);
204
+ const marker = await readInstalled(dest);
205
+ if (isComplete(marker, skillId, version)) {
206
+ await upsertManifest(applicationId, { skillId, name, version });
207
+ return { skipped: true, files: marker.files };
208
+ }
209
+ const files = extractZip(Buffer.isBuffer(zip) ? zip : Buffer.from(zip));
210
+ const partial = `${dest}.partial-${randomBytes(4).toString('hex')}`;
211
+ try {
212
+ await mkdir(partial, { recursive: true, mode: 0o700 });
213
+ let count = 0;
214
+ for (const file of files) {
215
+ const target = join(partial, ...file.relative.split('/'));
216
+ if (file.directory) {
217
+ await mkdir(target, { recursive: true, mode: 0o700 });
218
+ continue;
219
+ }
220
+ await mkdir(join(target, '..'), { recursive: true, mode: 0o700 });
221
+ await writeFile(target, file.bytes);
222
+ count += 1;
223
+ }
224
+ await writeFile(join(partial, 'installed.json'), JSON.stringify({ skillId, version, files: count }));
225
+ await restrict(partial);
226
+ try {
227
+ await rename(partial, dest);
228
+ } catch (error) {
229
+ await rm(partial, { recursive: true, force: true });
230
+ const existing = await readInstalled(dest);
231
+ if ((error?.code === 'EEXIST' || error?.code === 'ENOTEMPTY') && isComplete(existing, skillId, version)) {
232
+ await upsertManifest(applicationId, { skillId, name, version });
233
+ return { skipped: true, files: existing.files };
234
+ }
235
+ throw error;
236
+ }
237
+ await upsertManifest(applicationId, { skillId, name, version });
238
+ return { skipped: false, files: count };
239
+ } catch (error) {
240
+ await rm(partial, { recursive: true, force: true });
241
+ throw error;
242
+ }
243
+ }
244
+
245
+ async function upsertManifest(applicationId, entry) {
246
+ const current = await readManifest(applicationId);
247
+ const next = current.filter((item) => item?.skillId !== entry.skillId);
248
+ next.push(entry);
249
+ await writeManifest(applicationId, next);
250
+ }
251
+
252
+ export async function readSkillFile(applicationId, skillId, version, relativePath) {
253
+ if (!isSafeRelative(relativePath)) throw sandboxError('SecurityError', '技能路径越界。');
254
+ const root = versionDir(applicationId, skillId, version);
255
+ const real = resolve(root, ...relativePath.split('/'));
256
+ const fromRoot = relative(root, real);
257
+ if (fromRoot.startsWith('..') || fromRoot === '' || fromRoot.split(sep).includes('..')) {
258
+ throw sandboxError('SecurityError', '技能路径越界。');
259
+ }
260
+ try {
261
+ return await readFile(real);
262
+ } catch (error) {
263
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') throw sandboxError('NotFoundError', '技能或资源不存在。');
264
+ throw error;
265
+ }
266
+ }
267
+
268
+ /** 删除该应用下不在 keep 中、且不在 busy 中的版本目录,并重写 manifest。 */
269
+ export async function pruneSkills(applicationId, keep, busy = []) {
270
+ assertSkillId(applicationId, 'applicationId');
271
+ const known = await readManifest(applicationId);
272
+ const nameOf = new Map(known.map((item) => [item.skillId, item.name]));
273
+ const kept = new Set(keep.map((item) => `${item.skillId}/${item.version}`));
274
+ const deferredKeys = new Set(busy.map((item) => `${item.skillId}/${item.version}`));
275
+ let names = [];
276
+ try {
277
+ names = await readdir(appDir(applicationId));
278
+ } catch (error) {
279
+ if (error?.code === 'ENOENT') return { removed: [], deferred: [] };
280
+ throw error;
281
+ }
282
+ const removed = [];
283
+ const next = [];
284
+ const deferred = [];
285
+ for (const skillId of names) {
286
+ if (skillId === 'manifest.json' || !ID_PATTERN.test(skillId)) continue;
287
+ let versions = [];
288
+ try {
289
+ versions = await readdir(join(appDir(applicationId), skillId));
290
+ } catch {
291
+ continue;
292
+ }
293
+ for (const versionName of versions) {
294
+ if (!/^[1-9][0-9]*$/.test(versionName)) continue;
295
+ const version = Number(versionName);
296
+ const key = `${skillId}/${versionName}`;
297
+ const dir = join(appDir(applicationId), skillId, versionName);
298
+ const entry = { skillId, name: nameOf.get(skillId) || skillId, version };
299
+ if (kept.has(key)) {
300
+ const marker = await readInstalled(dir);
301
+ if (isComplete(marker, skillId, version)) next.push(entry);
302
+ continue;
303
+ }
304
+ if (deferredKeys.has(key)) {
305
+ next.push(entry);
306
+ deferred.push({ skillId, version });
307
+ continue;
308
+ }
309
+ await rm(dir, { recursive: true, force: true });
310
+ removed.push({ skillId, version });
311
+ }
312
+ }
313
+ await writeManifest(applicationId, next);
314
+ return { removed, deferred };
315
+ }
316
+
317
+ export function skillDirectory(applicationId, skillId, version) {
318
+ return versionDir(applicationId, skillId, version);
319
+ }