dsh-crowdtest 0.2.23 → 0.2.25

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
  1. 在 DeepSeek Harness「插件」页添加 npm 包 `dsh-crowdtest` 并启用。
4
4
  2. 在众测评测页点击「在本机运行」,复制完整命令(含口令和平台地址),在桌面端任意会话中发送。
5
- 3. 插件自动配置模型、下载附件并新建任务会话,在新会话中完成任务。
5
+ 3. 插件自动配置模型、下载附件并新建任务会话。项目声明了 Skills 时,插件会先安装并核验技能,再发送首轮任务。
6
6
  4. 每轮结束自动备份。结束前确认输入框上方显示「已同步」,有内容待同步时点击「立即同步」。
7
7
 
8
8
  在「插件」列表点击「刷新」,或打开插件详情页,DSH 会从 npm 检查新版。有新版时,列表显示「可更新」,按 DSH 的更新入口安装。更新检查由 DSH 管理,没有额外的后台定时检查。
@@ -12,3 +12,5 @@
12
12
  ```sh
13
13
  dsh plugin --profile desktop add dsh-crowdtest@0.2.22 --save-exact --registry https://registry.npmjs.org
14
14
  ```
15
+
16
+ 项目 Skills 需要支持原生 Skills 的 DSH 版本,以及本机可用的 Node.js、npm 和对技能来源的网络访问。遇到名称冲突或文件校验失败时,领取提示会说明原因。修复后,从平台复制新的领取命令。
package/lib/client.js CHANGED
@@ -36,7 +36,7 @@ __export(index_exports, {
36
36
  inject: () => inject
37
37
  });
38
38
  module.exports = __toCommonJS(index_exports);
39
- var import_react2 = require("react");
39
+ var import_react3 = require("react");
40
40
 
41
41
  // src/bridge.ts
42
42
  function object(value) {
@@ -190,8 +190,67 @@ function createSyncSource(deps) {
190
190
  };
191
191
  }
192
192
 
193
- // src/client/sync-dock.tsx
193
+ // src/client/command-card.tsx
194
194
  var import_react = __toESM(require("react"), 1);
195
+ var import_dsh_client_ui_primitives = require("@deepseek-ai/dsh-client-ui-primitives");
196
+ var import_jsx_runtime = require("react/jsx-runtime");
197
+ var separator = {
198
+ flex: "none",
199
+ width: 2,
200
+ height: 2,
201
+ margin: "0 8px",
202
+ borderRadius: 1,
203
+ background: "var(--dsw-alias-label-caption)"
204
+ };
205
+ var summaryStyle = {
206
+ minWidth: 0,
207
+ overflow: "hidden",
208
+ textOverflow: "ellipsis",
209
+ whiteSpace: "nowrap",
210
+ fontSize: "var(--dsh-content-font-size-secondary, 13px)"
211
+ };
212
+ var bodyStyle = {
213
+ minWidth: 0,
214
+ whiteSpace: "pre-wrap",
215
+ overflowWrap: "anywhere",
216
+ margin: "4px 0 4px 4px",
217
+ padding: "12px 16px",
218
+ border: "0.5px solid var(--dsw-alias-border-l1)",
219
+ borderRadius: "var(--dsw-radius-lg)",
220
+ background: "var(--dsw-alias-markdown-code-block)",
221
+ font: "var(--dsw-font-markdown-code-block-small)"
222
+ };
223
+ var errorColor = "var(--dsw-alias-state-error-primary)";
224
+ function CrowdtestCommandCard({ node: { name, outcome }, t }) {
225
+ const [expanded, setExpanded] = import_react.default.useState(false);
226
+ const failed = outcome?.kind === "error";
227
+ const summary = outcome === null ? t("command.running") : failed ? t("command.failed") : outcome.text ?? t("command.done");
228
+ const expandable = outcome?.kind === "success" && outcome.text?.includes("\n") === true;
229
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { minWidth: 0 }, children: [
230
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
231
+ import_dsh_client_ui_primitives.DisclosureRow,
232
+ {
233
+ icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_dsh_client_ui_primitives.IconApiOutlineRegular, { size: 14 }),
234
+ title: name ?? t("command.title"),
235
+ running: outcome === null,
236
+ open: expandable && expanded,
237
+ expandable,
238
+ expandOnRowClick: true,
239
+ keepContentWhenOpen: true,
240
+ onToggle: () => setExpanded((value) => !value),
241
+ collapsedContent: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
242
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { style: separator, "data-shimmer-decoration": true, "aria-hidden": true }),
243
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { style: { ...summaryStyle, color: failed ? errorColor : void 0 }, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_dsh_client_ui_primitives.TextShimmer, { children: summary }) })
244
+ ] }),
245
+ children: expandable && expanded && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { style: { ...bodyStyle, maxHeight: 260, overflow: "auto" }, children: outcome.text })
246
+ }
247
+ ),
248
+ failed && outcome.text && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { style: { ...bodyStyle, color: errorColor }, children: outcome.text })
249
+ ] });
250
+ }
251
+
252
+ // src/client/sync-dock.tsx
253
+ var import_react2 = __toESM(require("react"), 1);
195
254
 
196
255
  // src/client/sync-presentation.ts
197
256
  var SYNC_PRESENTATION = {
@@ -213,7 +272,7 @@ function formatLastSync(syncedAtMs, nowMs) {
213
272
  }
214
273
 
215
274
  // src/client/sync-dock.tsx
216
- var import_jsx_runtime = require("react/jsx-runtime");
275
+ var import_jsx_runtime2 = require("react/jsx-runtime");
217
276
  var styles = `
218
277
  [data-crowdtest-sync] {
219
278
  box-sizing: border-box;
@@ -297,8 +356,8 @@ var styles = `
297
356
  }
298
357
  `;
299
358
  function LastSuccessfulSync({ lastSyncedAtMs, uploadedAtMs }) {
300
- const [nowMs, setNowMs] = import_react.default.useState(Date.now);
301
- import_react.default.useEffect(() => {
359
+ const [nowMs, setNowMs] = import_react2.default.useState(Date.now);
360
+ import_react2.default.useEffect(() => {
302
361
  const timer = setInterval(() => {
303
362
  setNowMs(Date.now());
304
363
  }, 1e3);
@@ -308,20 +367,20 @@ function LastSuccessfulSync({ lastSyncedAtMs, uploadedAtMs }) {
308
367
  }, []);
309
368
  const title = `\u540C\u6B65\u786E\u8BA4\u65F6\u95F4\uFF1A${lastSyncedAtMs === null ? "\u672A\u8BB0\u5F55" : new Date(lastSyncedAtMs).toLocaleString()}
310
369
  \u5907\u4EFD\u4E0A\u4F20\u65F6\u95F4\uFF1A${uploadedAtMs === null ? "\u672A\u77E5" : new Date(uploadedAtMs).toLocaleString()}`;
311
- if (lastSyncedAtMs === null) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "crowdtest-sync-age", title, children: uploadedAtMs === null ? formatLastSync(null, 0) : "\u5C1A\u65E0\u540C\u6B65\u786E\u8BA4\u8BB0\u5F55" });
312
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("time", { className: "crowdtest-sync-age", dateTime: new Date(lastSyncedAtMs).toISOString(), title, children: formatLastSync(lastSyncedAtMs, nowMs) });
370
+ if (lastSyncedAtMs === null) return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "crowdtest-sync-age", title, children: uploadedAtMs === null ? formatLastSync(null, 0) : "\u5C1A\u65E0\u540C\u6B65\u786E\u8BA4\u8BB0\u5F55" });
371
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("time", { className: "crowdtest-sync-age", dateTime: new Date(lastSyncedAtMs).toISOString(), title, children: formatLastSync(lastSyncedAtMs, nowMs) });
313
372
  }
314
373
  function CrowdtestDock({ useCrowdtestSync, onSync }) {
315
374
  const view = useCrowdtestSync((value) => value);
316
- return view === null ? null : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BoundCrowdtestDock, { view, onSync }, `${view.sessionId}:${view.taskId}:${view.runId}:${view.bindingEpoch}`);
375
+ return view === null ? null : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(BoundCrowdtestDock, { view, onSync }, `${view.sessionId}:${view.taskId}:${view.runId}:${view.bindingEpoch}`);
317
376
  }
318
377
  function BoundCrowdtestDock({ view, onSync }) {
319
- const [action, setAction] = import_react.default.useState(null);
320
- const request = import_react.default.useRef(0);
321
- import_react.default.useLayoutEffect(() => () => {
378
+ const [action, setAction] = import_react2.default.useState(null);
379
+ const request = import_react2.default.useRef(0);
380
+ import_react2.default.useLayoutEffect(() => () => {
322
381
  request.current++;
323
382
  }, []);
324
- import_react.default.useLayoutEffect(() => {
383
+ import_react2.default.useLayoutEffect(() => {
325
384
  if (view.phase !== "synced" && view.phase !== "uploading") {
326
385
  request.current++;
327
386
  setAction(null);
@@ -329,7 +388,7 @@ function BoundCrowdtestDock({ view, onSync }) {
329
388
  setAction((current) => current?.kind === "completed" ? null : current);
330
389
  }
331
390
  }, [view.phase, view.revision]);
332
- import_react.default.useLayoutEffect(() => {
391
+ import_react2.default.useLayoutEffect(() => {
333
392
  if (action?.kind === "settled" && view.phase === "synced") {
334
393
  setAction({ kind: "completed", message: view.uploadedAtMs === action.uploadedAtMs ? "\u5DF2\u662F\u6700\u65B0" : "\u540C\u6B65\u5B8C\u6210" });
335
394
  }
@@ -349,21 +408,21 @@ function BoundCrowdtestDock({ view, onSync }) {
349
408
  if (request.current === started) setAction(null);
350
409
  }
351
410
  };
352
- return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("section", { "aria-label": "CrowdTest \u4F1A\u8BDD\u540C\u6B65", "data-crowdtest-sync": "", "data-session-id": view.sessionId, children: [
353
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("style", { children: styles }),
354
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "crowdtest-sync-identity", children: [
355
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: "CrowdTest" }),
356
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "crowdtest-sync-meta", children: [
411
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("section", { "aria-label": "CrowdTest \u4F1A\u8BDD\u540C\u6B65", "data-crowdtest-sync": "", "data-session-id": view.sessionId, children: [
412
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("style", { children: styles }),
413
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "crowdtest-sync-identity", children: [
414
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("strong", { children: "CrowdTest" }),
415
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "crowdtest-sync-meta", children: [
357
416
  "\u4EFB\u52A1 ",
358
417
  view.taskId,
359
418
  " \xB7 \u8FD0\u884C\u65F6 ",
360
419
  view.runId
361
420
  ] })
362
421
  ] }),
363
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "crowdtest-sync-actions", children: [
364
- (view.phase !== "dirty" || hasSyncHistory) && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LastSuccessfulSync, { lastSyncedAtMs: view.lastSyncedAtMs, uploadedAtMs: view.uploadedAtMs }, view.sessionId),
365
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "crowdtest-sync-status", "data-tone": presentation.tone, role: "status", "aria-live": "polite", children: action?.kind === "completed" && view.phase === "synced" ? action.message : label }),
366
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", disabled: busy, "aria-busy": busy, onClick: () => {
422
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "crowdtest-sync-actions", children: [
423
+ (view.phase !== "dirty" || hasSyncHistory) && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(LastSuccessfulSync, { lastSyncedAtMs: view.lastSyncedAtMs, uploadedAtMs: view.uploadedAtMs }, view.sessionId),
424
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "crowdtest-sync-status", "data-tone": presentation.tone, role: "status", "aria-live": "polite", children: action?.kind === "completed" && view.phase === "synced" ? action.message : label }),
425
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { type: "button", disabled: busy, "aria-busy": busy, onClick: () => {
367
426
  void sync();
368
427
  }, children: busy ? "\u540C\u6B65\u4E2D" : presentation.action })
369
428
  ] })
@@ -373,6 +432,13 @@ function BoundCrowdtestDock({ view, onSync }) {
373
432
  // src/client/index.tsx
374
433
  var inject = ["slots", "remote", "uiConversation"];
375
434
  async function apply(ctx) {
435
+ for (const key of ["crowdtest", "crowdtest-upload"]) {
436
+ ctx.slots.inject("conversation.chat.commandview", () => ctx.slots.register({
437
+ name: "conversation.chat.commandview",
438
+ key,
439
+ locale: "chat"
440
+ }, CrowdtestCommandCard));
441
+ }
376
442
  await ctx.remote.$mount(contribution);
377
443
  await ctx.inject(["remote.crowdtestSync"], (scope) => {
378
444
  const sources = /* @__PURE__ */ new Set();
package/lib/index.js CHANGED
@@ -6,7 +6,7 @@ var __knownSymbol = (name2, symbol) => (symbol = Symbol[name2]) ? symbol : /* @_
6
6
  var __typeError = (msg) => {
7
7
  throw TypeError(msg);
8
8
  };
9
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __defNormalProp = (obj, key2, value) => key2 in obj ? __defProp(obj, key2, { enumerable: true, configurable: true, writable: true, value }) : obj[key2] = value;
10
10
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
11
11
  var __esm = (fn, res, err) => function __init() {
12
12
  if (err) throw err[0];
@@ -30,8 +30,8 @@ var __runInitializers = (array, flags, self, value) => {
30
30
  return value;
31
31
  };
32
32
  var __decorateElement = (array, flags, name2, decorators, target, extra) => {
33
- var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
34
- var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
33
+ var fn, it, done, ctx, access2, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
34
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key2 = __decoratorStrings[k + 5];
35
35
  var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
36
36
  var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name2]() {
37
37
  return __privateGet(this, extra);
@@ -42,18 +42,18 @@ var __decorateElement = (array, flags, name2, decorators, target, extra) => {
42
42
  for (var i = decorators.length - 1; i >= 0; i--) {
43
43
  ctx = __decoratorContext(k, name2, done = {}, array[3], extraInitializers);
44
44
  if (k) {
45
- ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name2 in x };
46
- if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name2];
47
- if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name2] = y;
45
+ ctx.static = s, ctx.private = p, access2 = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name2 in x };
46
+ if (k ^ 3) access2.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name2];
47
+ if (k > 2) access2.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name2] = y;
48
48
  }
49
- it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
50
- if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
49
+ it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key2] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
50
+ if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key2] = it : target = it);
51
51
  else if (typeof it !== "object" || it === null) __typeError("Object expected");
52
52
  else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
53
53
  }
54
54
  return k || __decoratorMetadata(array, target), desc && __defProp(target, name2, desc), p ? k ^ 4 ? extra : desc : target;
55
55
  };
56
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
56
+ var __publicField = (obj, key2, value) => __defNormalProp(obj, typeof key2 !== "symbol" ? key2 + "" : key2, value);
57
57
  var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
58
58
  var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
59
59
  var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
@@ -74,7 +74,7 @@ function parseView(value) {
74
74
  if (value === null) return null;
75
75
  const view = object(value);
76
76
  const keys = ["sessionId", "taskId", "runId", "bindingEpoch", "revision", "phase", "uploadedAtMs", "lastSyncedAtMs"];
77
- if (Object.keys(view).length !== keys.length || keys.some((key) => !Object.hasOwn(view, key))) throw new Error("invalid sync view");
77
+ if (Object.keys(view).length !== keys.length || keys.some((key2) => !Object.hasOwn(view, key2))) throw new Error("invalid sync view");
78
78
  const { sessionId } = parseRequest({ sessionId: view.sessionId });
79
79
  const integer = (value2) => {
80
80
  if (typeof value2 !== "number" || !Number.isSafeInteger(value2) || value2 < 0) throw new Error("invalid sync identity");
@@ -148,20 +148,226 @@ var init_remote_host = __esm({
148
148
  });
149
149
 
150
150
  // src/index.ts
151
- import { createHash as createHash3, randomUUID } from "node:crypto";
152
- import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
153
- import { homedir as homedir3 } from "node:os";
151
+ import { createHash as createHash4, randomUUID as randomUUID2 } from "node:crypto";
152
+ import { mkdir as mkdir5, readFile as readFile3, writeFile as writeFile5 } from "node:fs/promises";
153
+ import { homedir as homedir4 } from "node:os";
154
+ import { join as join8 } from "node:path";
155
+
156
+ // src/skills-provider.ts
157
+ import { realpath as realpath2 } from "node:fs/promises";
158
+ import { dirname, join as join2 } from "node:path";
159
+
160
+ // src/skill-tree.ts
161
+ import { createHash } from "node:crypto";
162
+ import { constants } from "node:fs";
163
+ import { chmod, lstat, mkdir, open, opendir, realpath, writeFile } from "node:fs/promises";
164
+ import { join } from "node:path";
165
+ var digest = (data) => createHash("sha256").update(data).digest("hex");
166
+ var SkillTree = class {
167
+ entries = /* @__PURE__ */ new Map();
168
+ folders = [];
169
+ bytes = 0;
170
+ fingerprint() {
171
+ return digest(JSON.stringify([...this.entries.values()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
172
+ }
173
+ async walk(source2, path, to, signal) {
174
+ signal.throwIfAborted();
175
+ const key2 = path.normalize("NFC").toLowerCase();
176
+ if (this.entries.has(key2) || /[\\:\x00-\x1f\x7f]/u.test(path) || path.split("/").length > 64 || this.entries.size >= 4096) throw new Error("\u9879\u76EE Skill \u8DEF\u5F84\u51B2\u7A81\u6216\u6761\u76EE\u8D85\u8FC7\u9650\u5236");
177
+ const info = await lstat(source2);
178
+ if (await realpath(source2) !== source2) throw new Error("\u9879\u76EE Skill \u8DEF\u5F84\u5305\u542B\u94FE\u63A5");
179
+ if (info.isDirectory()) {
180
+ this.entries.set(key2, [path, 0, ""]);
181
+ if (to) await mkdir(to, { mode: 448 });
182
+ for await (const entry of await opendir(source2)) {
183
+ await this.walk(join(source2, entry.name), path + "/" + entry.name, to && join(to, entry.name), signal);
184
+ }
185
+ return;
186
+ }
187
+ if (!info.isFile() || info.nlink !== 1) throw new Error("\u9879\u76EE Skill \u542B\u94FE\u63A5\u6216\u975E\u666E\u901A\u6587\u4EF6");
188
+ if (info.size > 8 * 1024 * 1024 || this.bytes + info.size > 64 * 1024 * 1024) throw new Error("\u9879\u76EE Skill \u6587\u4EF6\u8D85\u8FC7\u5927\u5C0F\u9650\u5236");
189
+ const handle = await open(source2, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
190
+ try {
191
+ const stat2 = await handle.stat();
192
+ if (!stat2.isFile() || stat2.nlink !== 1 || stat2.dev !== info.dev || stat2.ino !== info.ino || stat2.size !== info.size) throw new Error("\u9879\u76EE Skill \u6587\u4EF6\u5DF2\u66F4\u6539");
193
+ const bytes = Buffer.alloc(stat2.size);
194
+ let offset = 0;
195
+ while (offset < bytes.length) {
196
+ const { bytesRead } = await handle.read(bytes, offset, bytes.length - offset, offset);
197
+ if (!bytesRead) throw new Error("\u9879\u76EE Skill \u6587\u4EF6\u8BFB\u53D6\u4E0D\u5B8C\u6574");
198
+ offset += bytesRead;
199
+ }
200
+ const after = await handle.stat();
201
+ if (after.size !== stat2.size || after.ctimeMs !== stat2.ctimeMs || await realpath(source2) !== source2) throw new Error("\u9879\u76EE Skill \u6587\u4EF6\u5DF2\u66F4\u6539");
202
+ this.bytes += bytes.length;
203
+ const mode = to ? 384 | stat2.mode & 73 : stat2.mode & 4095;
204
+ if (to) {
205
+ await writeFile(to, bytes, { flag: "wx", mode });
206
+ await chmod(to, mode);
207
+ }
208
+ this.entries.set(key2, [path, mode, digest(bytes)]);
209
+ } finally {
210
+ await handle.close();
211
+ }
212
+ }
213
+ async read(root, signal, staging) {
214
+ if (await realpath(root) !== root) throw new Error("\u9879\u76EE Skill \u76EE\u5F55\u5305\u542B\u94FE\u63A5");
215
+ let count = 0;
216
+ for await (const entry of await opendir(root)) {
217
+ signal.throwIfAborted();
218
+ if (this.folders.length >= 100) throw new Error("\u9879\u76EE Skills \u8D85\u8FC7 100 \u4E2A");
219
+ const path = join(root, entry.name);
220
+ let source2 = path;
221
+ if (entry.isSymbolicLink() && staging) {
222
+ source2 = await realpath(path);
223
+ if (source2 !== join(staging.home, ".agents/skills", entry.name)) throw new Error("\u9879\u76EE Skill \u5B89\u88C5\u94FE\u63A5\u6307\u5411\u975E\u53D7\u7BA1\u76EE\u5F55");
224
+ }
225
+ if (!(await lstat(source2)).isDirectory() || !(await lstat(join(source2, "SKILL.md"))).isFile()) throw new Error("\u9879\u76EE Skill \u76EE\u5F55\u7F3A\u5C11\u6709\u6548 SKILL.md");
226
+ await this.walk(source2, entry.name, staging && join(staging.to, entry.name), signal);
227
+ this.folders.push(entry.name);
228
+ count++;
229
+ }
230
+ if (!count && staging) throw new Error("\u9879\u76EE Skill \u5B89\u88C5\u672A\u4EA7\u751F\u6280\u80FD");
231
+ return [...this.folders].sort();
232
+ }
233
+ };
234
+
235
+ // src/skills-provider.ts
236
+ var providerName = "crowdtest-project-skills";
237
+ var NativeSkills = class _NativeSkills {
238
+ constructor(ctx, native, registry) {
239
+ this.ctx = ctx;
240
+ this.native = native;
241
+ this.registry = registry;
242
+ }
243
+ ctx;
244
+ native;
245
+ registry;
246
+ static async load(ctx) {
247
+ const registry = ctx.get("skills");
248
+ if (!registry || !ctx.get("tools") || !ctx.get("workingDirectory") || process.platform === "win32") return;
249
+ const scope = "@deepseek-ai/dsh-scope", filesystem = "@deepseek-ai/dsh-skill-filesystem";
250
+ try {
251
+ const [{ createScope, scopeParentOf }, { FileSystemSkillProvider }] = await Promise.all([import(scope), import(filesystem)]);
252
+ if (typeof createScope === "function" && typeof FileSystemSkillProvider === "function") {
253
+ return new _NativeSkills(ctx, { createScope, scopeParentOf, FileSystemSkillProvider }, registry);
254
+ }
255
+ } catch {
256
+ return void 0;
257
+ }
258
+ }
259
+ provider(ctx, control, root) {
260
+ return new this.native.FileSystemSkillProvider(ctx, control, {
261
+ providerName,
262
+ includeDefaultRoots: false,
263
+ customSkillDirs: [root],
264
+ watch: false
265
+ });
266
+ }
267
+ async inspect(root, folders, signal) {
268
+ const provider = this.provider(this.ctx, { signal, invalidate() {
269
+ } }, root);
270
+ try {
271
+ const options = { cwd: root, signal };
272
+ const listing = await provider.list(options);
273
+ if (!Array.isArray(listing) && !listing.complete) throw new Error("\u9879\u76EE Skill \u76EE\u5F55\u626B\u63CF\u4E0D\u5B8C\u6574");
274
+ const expected = new Map(folders.map((folder) => [join2(root, folder, "SKILL.md"), folder]));
275
+ const seen = /* @__PURE__ */ new Set();
276
+ const bundles = [];
277
+ for (const item of Array.isArray(listing) ? listing : listing.candidates) {
278
+ const path = item.path, folder = path && expected.get(path);
279
+ if (!path || !folder || seen.has(item.name)) throw new Error("\u9879\u76EE Skill \u540D\u79F0\u6216\u8DEF\u5F84\u51B2\u7A81");
280
+ expected.delete(path);
281
+ seen.add(item.name);
282
+ const loaded = await provider.get(item, options);
283
+ if (!loaded?.invocation.modelInvocable || loaded.name !== item.name || loaded.path !== path || loaded.resourceBase?.kind !== "directory" || loaded.resourceBase.path !== dirname(path)) throw new Error("\u9879\u76EE Skill \u65E0\u6CD5\u4F9B\u6A21\u578B\u8C03\u7528");
284
+ bundles.push({ name: item.name, folder, body: digest(loaded.content) });
285
+ }
286
+ if (expected.size || !bundles.length) throw new Error("\u9879\u76EE\u5305\u542B\u65E0\u6CD5\u89E3\u6790\u7684 SKILL.md");
287
+ return bundles;
288
+ } finally {
289
+ await provider.dispose();
290
+ }
291
+ }
292
+ async lookup(agent, workspace, signal) {
293
+ const cwd = await this.ctx.get("workingDirectory")?.ensure(agent, signal);
294
+ const tool = this.ctx.get("tools")?.get("skill", agent);
295
+ if (!cwd || await realpath2(cwd) !== workspace || !tool || typeof tool !== "object" || !("name" in tool) || tool.name !== "skill" || !("execute" in tool) || typeof tool.execute !== "function") {
296
+ throw new Error("\u4EFB\u52A1 Agent \u7684\u5DE5\u4F5C\u533A\u6216 skill \u5DE5\u5177\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5\u9884\u8BBE\u540E\u91CD\u65B0\u9886\u53D6");
297
+ }
298
+ return { cwd, scope: agent, signal };
299
+ }
300
+ async mount(root, bundles, agent, options) {
301
+ const snapshot = await this.registry.snapshot(options);
302
+ if (!snapshot.complete || bundles.some((b) => snapshot.skills.some((skill) => skill.name === b.name))) {
303
+ throw new Error("\u9879\u76EE Skill \u4E0E\u73B0\u6709\u540D\u79F0\u51B2\u7A81\u6216\u76EE\u5F55\u626B\u63CF\u4E0D\u5B8C\u6574");
304
+ }
305
+ options.signal.throwIfAborted();
306
+ const scope = this.native.createScope(this.ctx, agent);
307
+ try {
308
+ const scoped = scope.ctx.get("skills");
309
+ if (!scoped) throw new Error("\u4EFB\u52A1 Agent \u65E0\u6CD5\u8BBF\u95EE Skills \u670D\u52A1");
310
+ let delegate;
311
+ const undo = scoped.registerProvider((control) => {
312
+ const provider = delegate = this.provider(scope.ctx, control, root);
313
+ return {
314
+ name: providerName,
315
+ async list(lookup) {
316
+ const output = await provider.list(lookup);
317
+ const candidates = (Array.isArray(output) ? output : output.candidates).filter((c) => bundles.some((b) => b.name === c.name && c.path === join2(root, b.folder, "SKILL.md"))).map((c) => ({ ...c, rank: Number.MAX_SAFE_INTEGER }));
318
+ return { complete: candidates.length === bundles.length && (Array.isArray(output) || output.complete), candidates };
319
+ },
320
+ async get(candidate, lookup) {
321
+ const b = bundles.find((b2) => b2.name === candidate.name && candidate.path === join2(root, b2.folder, "SKILL.md"));
322
+ if (!b || !candidate.path || await realpath2(candidate.path) !== candidate.path) return;
323
+ const found = await provider.get(candidate, lookup);
324
+ if (found && digest(found.content) === b.body) return found;
325
+ }
326
+ };
327
+ });
328
+ return async () => {
329
+ undo();
330
+ await Promise.all([delegate?.dispose(), scope.dispose()]);
331
+ };
332
+ } catch (error) {
333
+ await scope.dispose();
334
+ throw error;
335
+ }
336
+ }
337
+ async verify(root, bundles, options) {
338
+ const parent = options.scope && this.native.scopeParentOf?.(options.scope);
339
+ const inherited = await this.registry.snapshot({ ...options, scope: parent });
340
+ if (!inherited.complete || inherited.skills.some((s) => bundles.some((b) => b.name === s.name))) throw new Error("\u9879\u76EE Skill \u4E0E\u5DF2\u6709\u540D\u79F0\u51B2\u7A81\u6216\u76EE\u5F55\u4E0D\u53EF\u7528");
341
+ const snapshot = await this.registry.snapshot(options);
342
+ if (!snapshot.complete) throw new Error("\u5F53\u524D Agent \u7684 Skill \u76EE\u5F55\u626B\u63CF\u4E0D\u5B8C\u6574");
343
+ for (const b of bundles) {
344
+ const path = join2(root, b.folder, "SKILL.md");
345
+ const winner = snapshot.skills.find((s) => s.name === b.name);
346
+ const loaded = await this.registry.get(b.name, options);
347
+ if (winner?.provider !== providerName || winner.path !== path || !winner.invocation.modelInvocable || loaded?.provider !== providerName || !loaded.invocation.modelInvocable || loaded.name !== b.name || loaded.path !== path || loaded.resourceBase?.kind !== "directory" || loaded.resourceBase.path !== dirname(path) || digest(loaded.content) !== b.body) throw new Error("\u9879\u76EE Skill \u4E0E\u73B0\u6709\u540D\u79F0\u51B2\u7A81\u6216\u5F53\u524D Agent \u65E0\u6CD5\u8BFB\u53D6\uFF0C\u8BF7\u91CD\u65B0\u9886\u53D6");
348
+ }
349
+ }
350
+ };
351
+
352
+ // src/task-skills.ts
353
+ import { randomUUID } from "node:crypto";
354
+ import { constants as constants4 } from "node:fs";
355
+ import { lstat as lstat3, mkdir as mkdir3, mkdtemp as mkdtemp2, open as open3, readdir, realpath as realpath4, rename, rm as rm2, unlink, writeFile as writeFile3 } from "node:fs/promises";
356
+ import { dirname as dirname3, join as join6, resolve as resolve2 } from "node:path";
357
+
358
+ // src/run.ts
359
+ import { createHash as createHash3 } from "node:crypto";
154
360
  import { join as join4 } from "node:path";
155
361
 
156
362
  // src/archive.ts
157
- import { createHash } from "node:crypto";
363
+ import { createHash as createHash2 } from "node:crypto";
158
364
  import { gzipSync } from "node:zlib";
159
365
 
160
366
  // src/native-session.ts
161
- import { constants } from "node:fs";
162
- import { lstat, open } from "node:fs/promises";
367
+ import { constants as constants2 } from "node:fs";
368
+ import { lstat as lstat2, open as open2 } from "node:fs/promises";
163
369
  import { homedir } from "node:os";
164
- import { isAbsolute, join, resolve } from "node:path";
370
+ import { isAbsolute, join as join3, resolve } from "node:path";
165
371
  import { zstdDecompressSync } from "node:zlib";
166
372
  var NATIVE_SESSION_NAME = "session.v4.jsonl.zstd";
167
373
  var MAX_DECODED_BYTES = 128 * 1024 * 1024;
@@ -207,17 +413,17 @@ function fileRevision(identity) {
207
413
  return [identity.dev, identity.ino, identity.size, identity.mtimeNs, identity.ctimeNs].join(":");
208
414
  }
209
415
  async function fileStat(path) {
210
- return lstat(path, { bigint: true });
416
+ return lstat2(path, { bigint: true });
211
417
  }
212
418
  function resolveNativeSessionRoot(root) {
213
- return resolve(root ?? join(process.env.DSH_HOME || join(homedir(), ".dsh"), "sessions"));
419
+ return resolve(root ?? join3(process.env.DSH_HOME || join3(homedir(), ".dsh"), "sessions"));
214
420
  }
215
421
  async function source(options) {
216
422
  const snapshot = await options.persistence.stat(options.sessionId);
217
423
  if (!snapshot) throw new Error("\u672A\u627E\u5230\u5F53\u524D\u539F\u751F\u4F1A\u8BDD");
218
424
  const header = sessionIdentity(snapshot.header, options.sessionId);
219
425
  const root = resolveNativeSessionRoot(options.nativeSessionRoot);
220
- const path = join(root, header.cwd === void 0 ? "_no-cwd" : projectKey(header.cwd), encodeSegment(header.id), NATIVE_SESSION_NAME);
426
+ const path = join3(root, header.cwd === void 0 ? "_no-cwd" : projectKey(header.cwd), encodeSegment(header.id), NATIVE_SESSION_NAME);
221
427
  return { path, header, revision: String(snapshot.revision) };
222
428
  }
223
429
  async function nativeSessionRevision(options) {
@@ -276,8 +482,8 @@ function containsSecret(value, secret) {
276
482
  const next = pending.pop();
277
483
  if (typeof next === "string" && next.includes(secret)) return true;
278
484
  if (next !== null && typeof next === "object") {
279
- for (const [key, child] of Object.entries(next)) {
280
- if (key.includes(secret)) return true;
485
+ for (const [key2, child] of Object.entries(next)) {
486
+ if (key2.includes(secret)) return true;
281
487
  pending.push(child);
282
488
  }
283
489
  }
@@ -315,7 +521,7 @@ function validateNativeSession(bytes, header, secret) {
315
521
  }
316
522
  async function captureNativeSession(options) {
317
523
  const current = await source(options);
318
- const handle = await open(current.path, constants.O_RDONLY | constants.O_NOFOLLOW);
524
+ const handle = await open2(current.path, constants2.O_RDONLY | constants2.O_NOFOLLOW);
319
525
  let bytes;
320
526
  let revision;
321
527
  try {
@@ -385,11 +591,46 @@ function validArchiveSessionId(id) {
385
591
  function buildSessionArchive(sessionId, file) {
386
592
  if (!validArchiveSessionId(sessionId)) throw new Error("\u4F1A\u8BDD\u6807\u8BC6\u65E0\u6548");
387
593
  const bytes = new Uint8Array(gzipSync(buildTar([{ path: `${sessionId}/${file.name}`, content: file.bytes }]), { level: 9 }));
388
- return { bytes, sha256: createHash("sha256").update(bytes).digest("hex"), size: bytes.length };
594
+ return { bytes, sha256: createHash2("sha256").update(bytes).digest("hex"), size: bytes.length };
595
+ }
596
+
597
+ // src/skill-plan.ts
598
+ var repository = /^(?:(?:https:\/\/github\.com\/)?[\w][\w.-]*\/[\w][\w.-]*|https:\/\/skills\.volces\.com\/skills\/[\w][\w.-]*\/[\w][\w.-]*)$/u;
599
+ var selection = /^(?:[a-z0-9]+(?:-[a-z0-9]+)*|\*)$/u;
600
+ var SKILLS_PACKAGE = "skills@1.5.15";
601
+ function parseDeclaration(row) {
602
+ const invalid = () => new Error("\u9879\u76EE Skill \u7684\u6765\u6E90\u3001\u5B89\u88C5\u7248\u672C\u6216\u53C2\u6570\u4E0D\u53D7\u652F\u6301\uFF0C\u8BF7\u8054\u7CFB\u9879\u76EE\u7BA1\u7406\u5458");
603
+ if (!row || typeof row !== "object" || !("id" in row) || typeof row.id !== "number" || !Number.isSafeInteger(row.id) || row.id < 1 || !("name" in row) || typeof row.name !== "string" || !row.name.trim() || !("argv" in row) || !Array.isArray(row.argv) || !row.argv.every((arg) => typeof arg === "string" && !/\s/u.test(arg))) throw invalid();
604
+ const args = row.argv;
605
+ const add = args.indexOf("add");
606
+ const source2 = args[add + 1];
607
+ if (args[0] !== "npx" || add < 3 || args[add - 1] !== SKILLS_PACKAGE || !args.slice(1, add - 1).every((arg) => arg === "-y" || arg === "--yes") || !source2 || !repository.test(source2)) throw invalid();
608
+ let agent = false, global = false, yes = false;
609
+ const selected = [];
610
+ for (let i = add + 2; i < args.length; ) {
611
+ const flag = args[i++];
612
+ if (flag === "-g" || flag === "--global") global = true;
613
+ else if (flag === "-y" || flag === "--yes") yes = true;
614
+ else if ((flag === "-a" || flag === "--agent") && args[i++] === "claude-code") agent = true;
615
+ else if (flag === "-s" || flag === "--skill") {
616
+ const start = i;
617
+ while (i < args.length && selection.test(args[i])) selected.push(args[i++]);
618
+ if (i === start) throw invalid();
619
+ } else throw invalid();
620
+ }
621
+ if (!agent || !global || !yes) throw invalid();
622
+ return { id: row.id, name: row.name, source: source2, selection: selected };
623
+ }
624
+ function parseSkillInstallPlan(plan) {
625
+ if (!plan || typeof plan !== "object" || !("version" in plan) || plan.version !== 1 || !("skills" in plan) || !Array.isArray(plan.skills)) throw new Error("\u9879\u76EE Skill \u5B89\u88C5\u8BA1\u5212\u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u9886\u53D6");
626
+ if (plan.skills.length > 100 || Buffer.byteLength(JSON.stringify(plan)) > 1024 * 1024) throw new Error("\u9879\u76EE Skill \u5B89\u88C5\u8BA1\u5212\u8D85\u8FC7\u9650\u5236");
627
+ const skills = plan.skills.map(parseDeclaration);
628
+ if (new Set(skills.map((skill) => skill.id)).size !== skills.length) throw new Error("\u9879\u76EE Skill \u5B89\u88C5\u8BA1\u5212\u5305\u542B\u91CD\u590D\u8D44\u6E90");
629
+ return skills;
389
630
  }
390
631
 
391
632
  // src/version.ts
392
- var PLUGIN_VERSION = "0.2.23";
633
+ var PLUGIN_VERSION = "0.2.25";
393
634
 
394
635
  // src/bff.ts
395
636
  var PROTOCOL_VERSION = "crowdtest-dsh/v1";
@@ -414,7 +655,7 @@ function validModel(model) {
414
655
  if (model.maxTokens !== void 0 && !positive(model.maxTokens)) return false;
415
656
  if (model.reasoningEffort !== void 0 && !text(model.reasoningEffort)) return false;
416
657
  const efforts = model.reasoningEfforts;
417
- if (efforts !== void 0 && efforts !== false && !(record(efforts) && Object.entries(efforts).every(([key, value]) => text(key) && text(value)))) return false;
658
+ if (efforts !== void 0 && efforts !== false && !(record(efforts) && Object.entries(efforts).every(([key2, value]) => text(key2) && text(value)))) return false;
418
659
  normalizeServerBaseUrl(model.baseUrl);
419
660
  return true;
420
661
  }
@@ -454,6 +695,7 @@ function parseManifest(value) {
454
695
  projectEndTime,
455
696
  model,
456
697
  attachments,
698
+ ...value.skillInstallPlan === void 0 ? {} : { projectSkills: parseSkillInstallPlan(value.skillInstallPlan) },
457
699
  sessionBackup: { format: sessionBackup.format, maxBytes: sessionBackup.maxBytes }
458
700
  };
459
701
  }
@@ -528,11 +770,21 @@ var CrowdtestBffClient = class {
528
770
  if (!record(value) || !text(value.token) || !positive(value.tokenExpiresAt) || value.tokenExpiresAt <= Date.now()) {
529
771
  throw new Error("\u5E73\u53F0\u8FD4\u56DE\u7684\u8FD0\u884C\u51ED\u8BC1\u65E0\u6548\u6216\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u9886\u53D6");
530
772
  }
531
- return { token: value.token, tokenExpiresAt: value.tokenExpiresAt };
773
+ const token = { token: value.token, tokenExpiresAt: value.tokenExpiresAt };
774
+ if (value.run === void 0) return token;
775
+ const run = value.run;
776
+ if (!record(run) || !positive(run.projectId) || !positive(run.taskId) || !positive(run.taskModelRunId) || !validArchiveSessionId(run.sessionId)) {
777
+ throw new Error("\u5E73\u53F0\u8FD4\u56DE\u7684\u9886\u53D6\u53E3\u4EE4\u8FD0\u884C\u6807\u8BC6\u65E0\u6548");
778
+ }
779
+ return { ...token, run: { projectId: run.projectId, taskId: run.taskId, taskModelRunId: run.taskModelRunId, sessionId: run.sessionId } };
532
780
  }
533
- async manifest(token, signal) {
781
+ async manifest(token, signal, supportsProjectSkills = false) {
534
782
  const response = await this.fetchImpl(this.url("/dsh/manifest"), {
535
- headers: { authorization: `Bearer ${token}`, "x-autocase-client-version": CLIENT_VERSION },
783
+ headers: {
784
+ authorization: `Bearer ${token}`,
785
+ "x-autocase-client-version": CLIENT_VERSION,
786
+ ...supportsProjectSkills ? { "x-crowdtest-capabilities": "project-skills-v1" } : {}
787
+ },
536
788
  signal
537
789
  });
538
790
  if (!response.ok) throw await failure(response, "\u62C9\u53D6\u4EFB\u52A1\u6E05\u5355");
@@ -556,7 +808,7 @@ var CrowdtestBffClient = class {
556
808
  if (!signed.ok) throw await failure(signed, "\u7533\u8BF7\u4F1A\u8BDD\u4E0A\u4F20\u5730\u5740");
557
809
  const post = await signed.json();
558
810
  const form = new FormData();
559
- for (const [key, value] of Object.entries(post.formFields)) form.append(key, value);
811
+ for (const [key2, value] of Object.entries(post.formFields)) form.append(key2, value);
560
812
  form.append(post.fileField, new Blob([archive], { type: "application/gzip" }), "session.tar.gz");
561
813
  const uploaded = await this.fetchImpl(post.signedPostUrl, { method: "POST", body: form, signal });
562
814
  if (!uploaded.ok) throw await failure(uploaded, "\u4E0A\u4F20\u4F1A\u8BDD\u5F52\u6863");
@@ -570,23 +822,16 @@ var CrowdtestBffClient = class {
570
822
  }
571
823
  };
572
824
 
573
- // src/state.ts
574
- import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
575
- import { homedir as homedir2 } from "node:os";
576
- import { dirname, join as join3, relative, resolve as resolve2 } from "node:path";
577
-
578
825
  // src/run.ts
579
- import { createHash as createHash2 } from "node:crypto";
580
- import { join as join2 } from "node:path";
581
826
  function identityKey(run) {
582
827
  return JSON.stringify([run.serverBaseUrl, run.projectId, run.taskId, run.taskModelRunId, run.sessionId]);
583
828
  }
584
829
  function scopedResources(identity, workspaceRoot) {
585
- const key = createHash2("sha256").update(identityKey(identity)).digest("hex");
830
+ const key2 = createHash3("sha256").update(identityKey(identity)).digest("hex");
586
831
  return {
587
- credentialRef: `CROWDTEST_RUN_${key.toUpperCase()}_TOKEN`,
588
- provider: `crowdtest-run-${key}`,
589
- workspace: join2(workspaceRoot, `${identity.projectId}-${identity.taskId}-${identity.taskModelRunId}-${key}`)
832
+ credentialRef: `CROWDTEST_RUN_${key2.toUpperCase()}_TOKEN`,
833
+ provider: `crowdtest-run-${key2}`,
834
+ workspace: join4(workspaceRoot, `${identity.projectId}-${identity.taskId}-${identity.taskModelRunId}-${key2}`)
590
835
  };
591
836
  }
592
837
  function parseJoinArguments(rawInput, configuredBaseUrl) {
@@ -613,9 +858,9 @@ function piAiProviderProfile(manifest, resources) {
613
858
  };
614
859
  }
615
860
  function runModelSelection(manifest, resources) {
616
- const selection = { provider: resources.provider, model: manifest.model.alias };
617
- if (manifest.model.reasoningEffort !== void 0) selection.reasoningEffort = manifest.model.reasoningEffort;
618
- return selection;
861
+ const selection2 = { provider: resources.provider, model: manifest.model.alias };
862
+ if (manifest.model.reasoningEffort !== void 0) selection2.reasoningEffort = manifest.model.reasoningEffort;
863
+ return selection2;
619
864
  }
620
865
  function isRunRoute(model, provider, config) {
621
866
  return config.provider === provider && config.model === model.alias;
@@ -645,20 +890,345 @@ function firstTaskMessage(prompt, attachmentPaths) {
645
890
  return sections.join("\n");
646
891
  }
647
892
 
893
+ // src/skill-installer.ts
894
+ import { spawn } from "node:child_process";
895
+ import { constants as constants3 } from "node:fs";
896
+ import { access, mkdir as mkdir2, mkdtemp, readFile, realpath as realpath3, rm, writeFile as writeFile2 } from "node:fs/promises";
897
+ import { homedir as homedir2, tmpdir } from "node:os";
898
+ import { basename, delimiter, dirname as dirname2, isAbsolute as isAbsolute2, join as join5, sep } from "node:path";
899
+ async function findNpx() {
900
+ const paths = (process.env.PATH ?? "").split(delimiter).filter(isAbsolute2).map((dir) => join5(dir, "node"));
901
+ for (const candidate of /* @__PURE__ */ new Set([process.execPath, ...paths, "/opt/homebrew/bin/node", "/usr/local/bin/node"])) {
902
+ if (basename(candidate) !== "node") continue;
903
+ try {
904
+ const node = await realpath3(candidate), bin = dirname2(node);
905
+ const npx = await realpath3(join5(bin, "npx"));
906
+ if (basename(node) !== "node" || basename(bin) !== "bin" || !npx.startsWith(dirname2(bin) + sep) || !npx.endsWith("/npm/bin/npx-cli.js")) continue;
907
+ await Promise.all([access(node, constants3.X_OK), access(npx, constants3.R_OK)]);
908
+ return { node, npx };
909
+ } catch {
910
+ continue;
911
+ }
912
+ }
913
+ throw new Error("\u9879\u76EE Skill \u9700\u8981\u53EF\u7528\u7684 Node.js \u548C npm\uFF0C\u8BF7\u5B89\u88C5\u540E\u91CD\u65B0\u9886\u53D6");
914
+ }
915
+ function networkUrl(value, registry = false) {
916
+ let url;
917
+ try {
918
+ url = new URL(value);
919
+ } catch {
920
+ throw new Error("Skill \u5B89\u88C5\u7F51\u7EDC\u914D\u7F6E\u65E0\u6548");
921
+ }
922
+ if (!(url.protocol === "https:" || !registry && url.protocol === "http:") || url.username || url.password || url.search || url.hash) throw new Error("Skill \u5B89\u88C5\u53EA\u652F\u6301\u65E0\u51ED\u636E\u7684\u7F51\u7EDC\u914D\u7F6E");
923
+ return url.href;
924
+ }
925
+ async function installerEnvironment(home, node) {
926
+ const env = {
927
+ HOME: home,
928
+ PATH: [dirname2(node), "/usr/bin", "/bin"].join(delimiter),
929
+ TMPDIR: join5(home, "tmp"),
930
+ CLAUDE_CONFIG_DIR: join5(home, ".claude"),
931
+ XDG_CONFIG_HOME: join5(home, ".config"),
932
+ XDG_DATA_HOME: join5(home, ".local/share"),
933
+ XDG_CACHE_HOME: join5(home, ".cache"),
934
+ XDG_STATE_HOME: join5(home, ".local/state"),
935
+ npm_config_cache: join5(home, ".npm"),
936
+ npm_config_userconfig: join5(home, "user.npmrc"),
937
+ npm_config_globalconfig: join5(home, "global.npmrc"),
938
+ npm_config_ignore_scripts: "true",
939
+ GIT_CONFIG_NOSYSTEM: "1",
940
+ GIT_CONFIG_GLOBAL: "/dev/null",
941
+ GIT_ALLOW_PROTOCOL: "https",
942
+ GIT_TERMINAL_PROMPT: "0",
943
+ GIT_CEILING_DIRECTORIES: home,
944
+ DISABLE_TELEMETRY: "1",
945
+ CI: "1"
946
+ };
947
+ const npmrc = await readFile(join5(homedir2(), ".npmrc"), "utf8").catch((error) => {
948
+ if (error.code !== "ENOENT") throw new Error("\u65E0\u6CD5\u8BFB\u53D6 npm registry \u914D\u7F6E");
949
+ return "";
950
+ });
951
+ const registry = process.env.npm_config_registry ?? process.env.NPM_CONFIG_REGISTRY ?? /^\s*registry\s*=\s*(\S+)\s*$/m.exec(npmrc)?.[1];
952
+ if (registry) env.npm_config_registry = networkUrl(registry, true);
953
+ for (const key2 of ["HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "https_proxy", "http_proxy", "all_proxy"]) {
954
+ const value = process.env[key2];
955
+ if (value) env[key2] = networkUrl(value);
956
+ }
957
+ for (const key2 of ["NO_PROXY", "no_proxy", "NODE_EXTRA_CA_CERTS", "SSL_CERT_FILE", "GIT_SSL_CAINFO"]) {
958
+ if (process.env[key2]) env[key2] = process.env[key2];
959
+ }
960
+ return env;
961
+ }
962
+ async function install(skill, home, signal) {
963
+ if (process.platform === "win32") throw new Error("\u5F53\u524D\u7CFB\u7EDF\u5C1A\u4E0D\u652F\u6301 DSH \u9879\u76EE Skill \u5B89\u88C5");
964
+ const { node, npx } = await findNpx();
965
+ const env = await installerEnvironment(home, node);
966
+ const cwd = join5(home, "work");
967
+ await Promise.all([mkdir2(cwd), mkdir2(join5(home, "tmp")), writeFile2(join5(home, "user.npmrc"), ""), writeFile2(join5(home, "global.npmrc"), "")]);
968
+ const args = [npx, "-y", SKILLS_PACKAGE, "add", skill.source, "-g", "-y", "--agent", "claude-code"];
969
+ if (skill.selection.length) args.push("--skill", ...skill.selection);
970
+ const deadline = AbortSignal.any([signal, AbortSignal.timeout(12e4)]);
971
+ deadline.throwIfAborted();
972
+ await new Promise((resolve4, reject) => {
973
+ const child = spawn(node, args, { cwd, env, shell: false, detached: true, stdio: ["ignore", "pipe", "pipe"] });
974
+ let outputBytes = 0;
975
+ let stopped = false;
976
+ const killGroup = () => {
977
+ if (child.pid) {
978
+ try {
979
+ process.kill(-child.pid, "SIGKILL");
980
+ } catch {
981
+ child.kill("SIGKILL");
982
+ }
983
+ }
984
+ };
985
+ const stop = () => {
986
+ stopped = true;
987
+ killGroup();
988
+ };
989
+ const count = (chunk) => {
990
+ outputBytes += chunk.length;
991
+ if (!stopped && outputBytes > 1024 * 1024) stop();
992
+ };
993
+ child.stdout.on("data", count);
994
+ child.stderr.on("data", count);
995
+ deadline.addEventListener("abort", stop, { once: true });
996
+ child.once("error", () => reject(new Error("\u65E0\u6CD5\u542F\u52A8\u9879\u76EE Skill \u5B89\u88C5\u5668")));
997
+ child.once("close", (code) => {
998
+ deadline.removeEventListener("abort", stop);
999
+ killGroup();
1000
+ if (code === 0 && !stopped) resolve4();
1001
+ else reject(new Error("\u9879\u76EE Skill \u5B89\u88C5\u5931\u8D25\u6216\u8D85\u51FA\u65F6\u9650\uFF0C\u8BF7\u68C0\u67E5\u6765\u6E90\u548C\u7F51\u7EDC\u540E\u91CD\u65B0\u9886\u53D6"));
1002
+ });
1003
+ });
1004
+ }
1005
+ async function stageSkill(skill, signal, consume) {
1006
+ signal.throwIfAborted();
1007
+ const home = await mkdtemp(join5(tmpdir(), "crowdtest-project-skill-"));
1008
+ try {
1009
+ await install(skill, home, signal);
1010
+ await consume(await realpath3(home));
1011
+ } finally {
1012
+ await rm(home, { recursive: true, force: true });
1013
+ }
1014
+ }
1015
+
1016
+ // src/task-skills.ts
1017
+ var reclaim = () => new Error("\u9879\u76EE Skills \u672A\u5C31\u7EEA\u6216\u5DF2\u66F4\u6539\uFF0C\u8BF7\u4ECE\u5E73\u53F0\u91CD\u65B0\u9886\u53D6\u4EFB\u52A1");
1018
+ var hex = /^[a-f0-9]{64}$/u;
1019
+ var generationName = /^generation-[A-Za-z0-9]{6}$/u;
1020
+ var missing = (e) => e instanceof Error && "code" in e && e.code === "ENOENT";
1021
+ var key = (run) => digest(identityKey(run));
1022
+ function receiptValid(v) {
1023
+ return !!v && typeof v === "object" && "version" in v && v.version === 1 && "run" in v && typeof v.run === "string" && hex.test(v.run) && "workspace" in v && typeof v.workspace === "string" && "generation" in v && typeof v.generation === "string" && generationName.test(v.generation) && "tree" in v && typeof v.tree === "string" && hex.test(v.tree) && "bundles" in v && Array.isArray(v.bundles) && v.bundles.length > 0 && v.bundles.length <= 100 && v.bundles.every((b) => !!b && typeof b === "object" && "name" in b && typeof b.name === "string" && "folder" in b && typeof b.folder === "string" && b.folder !== "." && b.folder !== ".." && !/[/\\]/u.test(b.folder) && !!b.folder && "body" in b && typeof b.body === "string" && hex.test(b.body));
1024
+ }
1025
+ var TaskSkills = class {
1026
+ constructor(ctx, stateFile) {
1027
+ this.ctx = ctx;
1028
+ this.stateFile = stateFile;
1029
+ }
1030
+ ctx;
1031
+ stateFile;
1032
+ mounts = /* @__PURE__ */ new Map();
1033
+ epochs = /* @__PURE__ */ new Map();
1034
+ activating = /* @__PURE__ */ new Map();
1035
+ closed = false;
1036
+ async directory(run, create = false) {
1037
+ const parent = dirname3(resolve2(this.stateFile));
1038
+ if (create) await mkdir3(parent, { recursive: true, mode: 448 });
1039
+ const root = join6(await realpath4(parent), "task-skills");
1040
+ const path = join6(root, key(run));
1041
+ for (const dir of [root, path]) {
1042
+ if (create) await mkdir3(dir, { mode: 448 }).catch((e) => {
1043
+ if (e.code !== "EEXIST") throw e;
1044
+ });
1045
+ if (!(await lstat3(dir)).isDirectory() || await realpath4(dir) !== dir) throw reclaim();
1046
+ }
1047
+ return path;
1048
+ }
1049
+ async begin(run) {
1050
+ const dir = await this.directory(run, true);
1051
+ const own = "claim-" + process.pid + "-" + randomUUID();
1052
+ await writeFile3(join6(dir, own), "", { flag: "wx", mode: 384 });
1053
+ const release = () => rm2(join6(dir, own), { force: true });
1054
+ try {
1055
+ for (const name2 of await readdir(dir)) {
1056
+ const match = /^claim-(\d+)-[a-f0-9-]+$/u.exec(name2);
1057
+ if (!match || name2 === own) continue;
1058
+ try {
1059
+ process.kill(Number(match[1]), 0);
1060
+ } catch (e) {
1061
+ if (e instanceof Error && "code" in e && e.code === "ESRCH") {
1062
+ await rm2(join6(dir, name2), { force: true });
1063
+ continue;
1064
+ }
1065
+ }
1066
+ throw new Error("\u8BE5\u4EFB\u52A1\u6B63\u5728\u53E6\u4E00\u4E2A\u8FDB\u7A0B\u4E2D\u9886\u53D6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
1067
+ }
1068
+ await this.invalidate(run.sessionId);
1069
+ await unlink(join6(dir, "receipt.json")).catch((e) => {
1070
+ if (!missing(e)) throw e;
1071
+ });
1072
+ return release;
1073
+ } catch (error) {
1074
+ await release();
1075
+ throw error;
1076
+ }
1077
+ }
1078
+ async prepare(run, skills, signal) {
1079
+ signal = AbortSignal.any([signal, AbortSignal.timeout(10 * 6e4)]);
1080
+ const native = await NativeSkills.load(this.ctx);
1081
+ if (!native) throw new Error("\u5F53\u524D DeepSeek Harness \u7F3A\u5C11\u9879\u76EE Skills \u670D\u52A1\uFF0C\u8BF7\u66F4\u65B0\u540E\u91CD\u65B0\u9886\u53D6");
1082
+ const dir = await this.directory(run);
1083
+ const root = await mkdtemp2(join6(dir, "generation-"));
1084
+ const temp = join6(dir, "receipt-" + randomUUID());
1085
+ let published = false;
1086
+ try {
1087
+ const collector = new SkillTree();
1088
+ let folders = [];
1089
+ const selections = /* @__PURE__ */ new Map();
1090
+ for (const skill of skills) {
1091
+ await stageSkill(skill, signal, async (home) => {
1092
+ const previous = new Set(folders);
1093
+ folders = await collector.read(join6(home, ".claude", "skills"), signal, { home, to: root });
1094
+ if (skill.selection.length && !skill.selection.includes("*")) {
1095
+ for (const folder of folders) if (!previous.has(folder)) selections.set(folder, skill.selection);
1096
+ }
1097
+ });
1098
+ }
1099
+ const bundles = await native.inspect(root, folders, signal);
1100
+ for (const selected of new Set(selections.values())) {
1101
+ const names = bundles.filter((b) => selections.get(b.folder) === selected).map((b) => b.name);
1102
+ if (names.some((name2) => !selected.includes(name2)) || selected.some((name2) => !names.includes(name2))) {
1103
+ throw new Error("\u5B9E\u9645\u5B89\u88C5\u7684\u9879\u76EE Skills \u4E0E\u6E05\u5355\u9009\u62E9\u4E0D\u4E00\u81F4");
1104
+ }
1105
+ }
1106
+ const receipt = {
1107
+ version: 1,
1108
+ run: key(run),
1109
+ workspace: await realpath4(run.workspace),
1110
+ generation: root.slice(dir.length + 1),
1111
+ tree: collector.fingerprint(),
1112
+ bundles
1113
+ };
1114
+ const bytes = JSON.stringify(receipt);
1115
+ signal.throwIfAborted();
1116
+ await writeFile3(temp, bytes, { mode: 384, flag: "wx" });
1117
+ await rename(temp, join6(dir, "receipt.json"));
1118
+ published = true;
1119
+ return digest(bytes);
1120
+ } finally {
1121
+ await rm2(temp, { force: true });
1122
+ if (!published) await rm2(root, { recursive: true, force: true });
1123
+ }
1124
+ }
1125
+ async read(run) {
1126
+ if (!run.skillReceipt || !hex.test(run.skillReceipt)) throw reclaim();
1127
+ const dir = await this.directory(run);
1128
+ const handle = await open3(join6(dir, "receipt.json"), constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
1129
+ try {
1130
+ const stat2 = await handle.stat();
1131
+ if (!stat2.isFile() || stat2.nlink !== 1 || stat2.size > 1024 * 1024) throw reclaim();
1132
+ const bytes = Buffer.alloc(stat2.size);
1133
+ const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
1134
+ if (bytesRead !== bytes.length || digest(bytes) !== run.skillReceipt) throw reclaim();
1135
+ const data = JSON.parse(bytes.toString("utf8"));
1136
+ if (!receiptValid(data) || data.run !== key(run) || data.workspace !== await realpath4(run.workspace)) throw reclaim();
1137
+ return { receipt: data, root: join6(dir, data.generation) };
1138
+ } finally {
1139
+ await handle.close();
1140
+ }
1141
+ }
1142
+ async confirmActive(run, agent) {
1143
+ const mounted = this.mounts.get(run.sessionId);
1144
+ if (!mounted || mounted.agent !== agent || mounted.pin !== run.skillReceipt) throw reclaim();
1145
+ await this.read(run).catch(() => {
1146
+ throw reclaim();
1147
+ });
1148
+ if (this.mounts.get(run.sessionId) !== mounted) throw reclaim();
1149
+ }
1150
+ async invalidate(id, agent) {
1151
+ const previous = this.mounts.get(id);
1152
+ if (agent && !previous && !this.activating.has(id)) return;
1153
+ if (agent && previous && previous.agent !== agent) return;
1154
+ this.epochs.set(id, (this.epochs.get(id) ?? 0) + 1);
1155
+ this.mounts.delete(id);
1156
+ await previous?.dispose();
1157
+ }
1158
+ async ensure(run, agent, signal) {
1159
+ if (run.skillReceipt === "pending") throw reclaim();
1160
+ const id = run.sessionId, epoch = this.epochs.get(id);
1161
+ const guard = () => {
1162
+ signal.throwIfAborted();
1163
+ if (this.closed || agent.id !== id || this.epochs.get(id) !== epoch || this.ctx.agents.get(id) !== agent) throw reclaim();
1164
+ };
1165
+ const check = async () => {
1166
+ guard();
1167
+ const native = await NativeSkills.load(this.ctx);
1168
+ if (!native || !run.skillReceipt) throw reclaim();
1169
+ const { receipt, root } = await this.read(run).catch(() => {
1170
+ throw reclaim();
1171
+ });
1172
+ const tree = new SkillTree();
1173
+ await tree.read(root, signal);
1174
+ if (tree.fingerprint() !== receipt.tree) throw reclaim();
1175
+ const lookup = await native.lookup(agent, receipt.workspace, signal);
1176
+ guard();
1177
+ const previous = this.mounts.get(id);
1178
+ if (!previous || previous.pin !== run.skillReceipt || previous.agent !== agent) {
1179
+ if (previous) {
1180
+ this.mounts.delete(id);
1181
+ await previous.dispose();
1182
+ }
1183
+ const dispose = await native.mount(root, receipt.bundles, agent, lookup);
1184
+ try {
1185
+ guard();
1186
+ } catch (error) {
1187
+ await dispose();
1188
+ throw error;
1189
+ }
1190
+ this.mounts.set(id, { agent, pin: run.skillReceipt, dispose });
1191
+ }
1192
+ await native.verify(root, receipt.bundles, lookup);
1193
+ await this.read(run);
1194
+ guard();
1195
+ };
1196
+ const operation = (this.activating.get(id) ?? Promise.resolve()).catch(() => {
1197
+ }).then(check).catch(async (error) => {
1198
+ if (this.epochs.get(id) === epoch) await this.invalidate(id, agent);
1199
+ throw error;
1200
+ });
1201
+ this.activating.set(id, operation);
1202
+ try {
1203
+ await operation;
1204
+ } finally {
1205
+ if (this.activating.get(id) === operation) this.activating.delete(id);
1206
+ }
1207
+ }
1208
+ async dispose() {
1209
+ this.closed = true;
1210
+ await Promise.allSettled([...this.mounts.keys()].map((id) => this.invalidate(id)));
1211
+ await Promise.allSettled(this.activating.values());
1212
+ }
1213
+ };
1214
+
648
1215
  // src/state.ts
1216
+ import { mkdir as mkdir4, readFile as readFile2, rename as rename2, stat, writeFile as writeFile4 } from "node:fs/promises";
1217
+ import { homedir as homedir3 } from "node:os";
1218
+ import { dirname as dirname4, join as join7, relative, resolve as resolve3 } from "node:path";
649
1219
  var RECLAIM_MESSAGE = "\u6B64\u4F1A\u8BDD\u7684\u8FD0\u884C\u8D44\u6E90\u5F52\u5C5E\u4E0D\u660E\u786E\uFF0C\u8BF7\u4ECE\u5E73\u53F0\u91CD\u65B0\u9886\u53D6\u4EFB\u52A1";
650
1220
  function defaultStateFile() {
651
- return join3(process.env.DSH_HOME || join3(homedir2(), ".dsh"), "crowdtest", "runs.json");
1221
+ return join7(process.env.DSH_HOME || join7(homedir3(), ".dsh"), "crowdtest", "runs.json");
652
1222
  }
653
1223
  async function workspaceKey(workspace) {
654
- const path = resolve2(workspace);
1224
+ const path = resolve3(workspace);
655
1225
  let ancestor = path;
656
1226
  for (; ; ) {
657
1227
  try {
658
1228
  const directory = await stat(ancestor, { bigint: true });
659
1229
  return `${directory.dev}:${directory.ino}/${relative(ancestor, path)}`;
660
1230
  } catch (error) {
661
- const parent = dirname(ancestor);
1231
+ const parent = dirname4(ancestor);
662
1232
  if (error.code !== "ENOENT" || parent === ancestor) return void 0;
663
1233
  ancestor = parent;
664
1234
  }
@@ -675,7 +1245,7 @@ var RunBindings = class {
675
1245
  async load() {
676
1246
  let text2;
677
1247
  try {
678
- text2 = await readFile(this.file, "utf8");
1248
+ text2 = await readFile2(this.file, "utf8");
679
1249
  } catch (error) {
680
1250
  if (error.code === "ENOENT") return;
681
1251
  throw error;
@@ -704,10 +1274,10 @@ var RunBindings = class {
704
1274
  sharedWorkspaces.add(previous.sessionId);
705
1275
  }
706
1276
  }
707
- for (const [index, key] of [[bySession, binding.sessionId], [byCredential, binding.credentialRef], [byProvider, binding.provider]]) {
708
- const previous = index.get(key);
1277
+ for (const [index, key2] of [[bySession, binding.sessionId], [byCredential, binding.credentialRef], [byProvider, binding.provider]]) {
1278
+ const previous = index.get(key2);
709
1279
  if (!previous) {
710
- index.set(key, binding);
1280
+ index.set(key2, binding);
711
1281
  } else if (identityKey(previous) !== identityKey(binding)) {
712
1282
  blocked.add(previous.sessionId);
713
1283
  blocked.add(binding.sessionId);
@@ -722,6 +1292,9 @@ var RunBindings = class {
722
1292
  else if (identityKey(owner) !== identityKey(binding)) this.duplicateOwners.push(binding);
723
1293
  }
724
1294
  }
1295
+ all() {
1296
+ return this.bindings.values();
1297
+ }
725
1298
  get(sessionId) {
726
1299
  return this.bindings.get(sessionId);
727
1300
  }
@@ -771,10 +1344,10 @@ var RunBindings = class {
771
1344
  }
772
1345
  async write(runs) {
773
1346
  const snapshot = JSON.stringify({ version: 1, runs: [...runs, ...this.duplicateOwners] }, null, 2);
774
- await mkdir(dirname(this.file), { recursive: true, mode: 448 });
1347
+ await mkdir4(dirname4(this.file), { recursive: true, mode: 448 });
775
1348
  const temporary = `${this.file}.${process.pid}.tmp`;
776
- await writeFile(temporary, snapshot, { mode: 384 });
777
- await rename(temporary, this.file);
1349
+ await writeFile4(temporary, snapshot, { mode: 384 });
1350
+ await rename2(temporary, this.file);
778
1351
  }
779
1352
  };
780
1353
 
@@ -992,7 +1565,7 @@ function errorText(error) {
992
1565
  }
993
1566
  async function sha256File(path) {
994
1567
  try {
995
- return createHash3("sha256").update(await readFile2(path)).digest("hex");
1568
+ return createHash4("sha256").update(await readFile3(path)).digest("hex");
996
1569
  } catch (error) {
997
1570
  if (error.code === "ENOENT") return void 0;
998
1571
  throw error;
@@ -1000,16 +1573,16 @@ async function sha256File(path) {
1000
1573
  }
1001
1574
  async function downloadAttachment(directory, attachment, signal) {
1002
1575
  const fileName = attachment.name;
1003
- const target = join4(directory, fileName);
1576
+ const target = join8(directory, fileName);
1004
1577
  const existing = await sha256File(target);
1005
1578
  if (existing !== void 0 && attachment.sha256 !== null && existing === attachment.sha256) return fileName;
1006
1579
  const response = await fetch(attachment.url, { signal });
1007
1580
  if (!response.ok) throw new Error(`\u4E0B\u8F7D\u9644\u4EF6 ${fileName} \u5931\u8D25\uFF08HTTP ${response.status}\uFF09`);
1008
1581
  const bytes = new Uint8Array(await response.arrayBuffer());
1009
1582
  if (bytes.length !== attachment.size) throw new Error(`\u9644\u4EF6 ${fileName} \u5927\u5C0F\u6821\u9A8C\u5931\u8D25`);
1010
- const digest = createHash3("sha256").update(bytes).digest("hex");
1011
- if (attachment.sha256 !== null && digest !== attachment.sha256) throw new Error(`\u9644\u4EF6 ${fileName} SHA-256 \u6821\u9A8C\u5931\u8D25`);
1012
- await writeFile2(target, bytes, { mode: 256 });
1583
+ const digest2 = createHash4("sha256").update(bytes).digest("hex");
1584
+ if (attachment.sha256 !== null && digest2 !== attachment.sha256) throw new Error(`\u9644\u4EF6 ${fileName} SHA-256 \u6821\u9A8C\u5931\u8D25`);
1585
+ await writeFile5(target, bytes, { mode: 256 });
1013
1586
  return fileName;
1014
1587
  }
1015
1588
  async function sessionExists(ctx, sessionId) {
@@ -1048,49 +1621,106 @@ async function matchesCreationRecord(ctx, saved) {
1048
1621
  await handle.close();
1049
1622
  }
1050
1623
  }
1051
- async function pinRunModel(ctx, sessionId, selection) {
1624
+ async function pinRunModel(ctx, sessionId, selection2) {
1052
1625
  const previous = ctx.agentDefaultModel.currentSelection();
1053
- await ctx.sessionController.selectModel({ sessionId, ...selection });
1626
+ await ctx.sessionController.selectModel({ sessionId, ...selection2 });
1054
1627
  const deadline = Date.now() + 5e3;
1055
1628
  while (Date.now() < deadline) {
1056
1629
  const current = ctx.agentDefaultModel.currentSelection();
1057
- if (current.provider === selection.provider && current.model === selection.model && current.reasoningEffort === selection.reasoningEffort) break;
1058
- await new Promise((resolve3) => setTimeout(resolve3, 100));
1630
+ if (current.provider === selection2.provider && current.model === selection2.model && current.reasoningEffort === selection2.reasoningEffort) break;
1631
+ await new Promise((resolve4) => setTimeout(resolve4, 100));
1059
1632
  }
1060
- if (previous.provider !== selection.provider || previous.model !== selection.model || previous.reasoningEffort !== selection.reasoningEffort) {
1633
+ if (previous.provider !== selection2.provider || previous.model !== selection2.model || previous.reasoningEffort !== selection2.reasoningEffort) {
1061
1634
  await ctx.agentDefaultModel.saveSelection(previous);
1062
1635
  }
1063
1636
  }
1064
1637
  async function apply(ctx, config = {}) {
1065
- const bindings = new RunBindings(config.stateFile ?? defaultStateFile());
1066
- await bindings.load();
1067
- const llmEntryId = config.llmEntryId ?? "llm-pi-ai";
1068
- const workspaceRoot = config.workspaceRoot ?? join4(homedir3(), "CrowdTest");
1069
- const backups = new SessionBackups(ctx, bindings, config);
1070
- ctx.effect(() => () => backups.dispose());
1071
- if (ctx.typert) {
1072
- const { installRemote: installRemote2 } = await Promise.resolve().then(() => (init_remote_host(), remote_host_exports));
1073
- await installRemote2(ctx, backups);
1074
- }
1075
- ctx.effect(() => ctx.on("session/event", (session, event) => {
1076
- backups.changed(session.id, event.type === "turn/end");
1077
- }));
1638
+ const stateFile = config.stateFile ?? defaultStateFile();
1639
+ const bindings = new RunBindings(stateFile);
1640
+ const skills = new TaskSkills(ctx, stateFile);
1641
+ const lifetime = new AbortController();
1642
+ ctx.effect(() => () => {
1643
+ lifetime.abort();
1644
+ return skills.dispose();
1645
+ });
1646
+ const bindingsReady = bindings.load();
1078
1647
  ctx.effect(() => ctx.on("agent/request", async (payload, next) => {
1648
+ await bindingsReady;
1649
+ lifetime.signal.throwIfAborted();
1650
+ if (ctx.fiber?.uid === null) throw new DOMException("Plugin disposed", "AbortError");
1651
+ payload.signal.throwIfAborted();
1079
1652
  const saved = bindings.get(payload.agent.id);
1080
1653
  if (saved && saved.resourceStatus !== "ready") throw new Error(RECLAIM_MESSAGE);
1654
+ if (saved?.skillReceipt !== void 0) await skills.ensure(saved, payload.agent, payload.signal);
1081
1655
  const resolved = await next();
1082
1656
  const binding = bindings.get(payload.agent.id);
1657
+ if ((saved?.skillReceipt !== void 0 || binding?.skillReceipt !== void 0) && binding !== saved) throw new Error(RECLAIM_MESSAGE);
1658
+ if (binding?.skillReceipt !== void 0) await skills.confirmActive(binding, payload.agent);
1083
1659
  if (binding !== void 0 && !isRunRoute(binding.model, binding.provider, resolved)) {
1084
1660
  throw new Error(`CrowdTest \u4EFB\u52A1\u4F1A\u8BDD\u53EA\u80FD\u4F7F\u7528\u5E73\u53F0\u4E0B\u53D1\u7684\u6A21\u578B ${binding.model.alias}\uFF0C\u8BF7\u5207\u6362\u56DE\u8BE5\u6A21\u578B\u540E\u91CD\u8BD5`);
1085
1661
  }
1086
1662
  return resolved;
1087
1663
  }));
1664
+ await bindingsReady;
1665
+ if (lifetime.signal.aborted || ctx.fiber?.uid === null) return;
1666
+ ctx.effect(() => ctx.on("agent/created", async ({ agent, signal }) => {
1667
+ const binding = bindings.get(agent.id);
1668
+ if (binding?.resourceStatus === "ready" && binding.skillReceipt !== void 0) {
1669
+ try {
1670
+ await skills.ensure(binding, agent, signal ?? new AbortController().signal);
1671
+ } catch {
1672
+ ctx.logger.warn("CrowdTest \u9879\u76EE Skills \u9700\u8981\u91CD\u65B0\u9886\u53D6", agent.id);
1673
+ }
1674
+ }
1675
+ }));
1676
+ ctx.effect(() => ctx.on("agent/disposed", ({ agent }) => {
1677
+ void skills.invalidate(agent.id, agent).catch(() => ctx.logger.warn("CrowdTest \u9879\u76EE Skills \u6E05\u7406\u5931\u8D25", agent.id));
1678
+ }));
1679
+ for (const binding of bindings.all()) {
1680
+ if (binding.resourceStatus !== "ready" || binding.skillReceipt === void 0) continue;
1681
+ const agent = ctx.agents.get(binding.sessionId);
1682
+ if (agent) await skills.ensure(binding, agent, lifetime.signal).catch(() => ctx.logger.warn("CrowdTest \u9879\u76EE Skills \u9700\u8981\u91CD\u65B0\u9886\u53D6", agent.id));
1683
+ }
1684
+ const llmEntryId = config.llmEntryId ?? "llm-pi-ai";
1685
+ const workspaceRoot = config.workspaceRoot ?? join8(homedir4(), "CrowdTest");
1686
+ const backups = new SessionBackups(ctx, bindings, config);
1687
+ ctx.effect(() => () => backups.dispose());
1688
+ if (ctx.typert) {
1689
+ const { installRemote: installRemote2 } = await Promise.resolve().then(() => (init_remote_host(), remote_host_exports));
1690
+ await installRemote2(ctx, backups);
1691
+ }
1692
+ ctx.effect(() => ctx.on("session/event", (session, event) => {
1693
+ backups.changed(session.id, event.type === "turn/end");
1694
+ }));
1088
1695
  async function claim(rawInput, signal) {
1089
1696
  const { ticket, serverBaseUrl } = parseJoinArguments(rawInput, config.serverBaseUrl);
1090
1697
  signal.throwIfAborted();
1091
1698
  const client = new CrowdtestBffClient(serverBaseUrl);
1092
- const { token } = await client.exchangeTicket(ticket, signal);
1093
- const manifest = await client.manifest(token, signal);
1699
+ const { token, run } = await client.exchangeTicket(ticket, signal);
1700
+ const exchanged = run && { serverBaseUrl, ...run };
1701
+ const known = exchanged && bindings.ownerForClaim(exchanged);
1702
+ let release;
1703
+ try {
1704
+ if (known?.skillReceipt !== void 0) release = await skills.begin(known);
1705
+ const native = await NativeSkills.load(ctx);
1706
+ const manifest = await client.manifest(token, signal, native !== void 0);
1707
+ if (exchanged && identityKey(exchanged) !== identityKey({ serverBaseUrl, ...manifest })) {
1708
+ throw new Error("\u9886\u53D6\u53E3\u4EE4\u5BF9\u5E94\u7684\u8FD0\u884C\u4E0E\u4EFB\u52A1\u6E05\u5355\u4E0D\u4E00\u81F4");
1709
+ }
1710
+ const previous = bindings.ownerForClaim({ serverBaseUrl, ...manifest });
1711
+ if (previous?.skillReceipt !== void 0 && (!exchanged || manifest.projectSkills === void 0)) {
1712
+ release ??= await skills.begin(previous);
1713
+ throw new Error("\u5E73\u53F0\u672A\u63D0\u4F9B\u9879\u76EE Skills \u7EED\u9886\u6240\u9700\u7684\u8FD0\u884C\u6807\u8BC6\u6216\u5B89\u88C5\u8BA1\u5212\uFF0C\u8BF7\u66F4\u65B0\u540E\u91CD\u65B0\u9886\u53D6");
1714
+ }
1715
+ if (manifest.projectSkills?.length && (!exchanged || !native)) throw new Error("\u5E73\u53F0\u6216\u63D2\u4EF6\u7F3A\u5C11\u9879\u76EE Skills \u652F\u6301\uFF0C\u8BF7\u66F4\u65B0\u540E\u91CD\u65B0\u9886\u53D6");
1716
+ return await claimManifest(manifest, token, serverBaseUrl, signal, async (binding) => {
1717
+ release ??= await skills.begin(binding);
1718
+ });
1719
+ } finally {
1720
+ await release?.();
1721
+ }
1722
+ }
1723
+ async function claimManifest(manifest, token, serverBaseUrl, signal, beginSkills) {
1094
1724
  const { projectId, taskId, taskModelRunId, sessionId } = manifest;
1095
1725
  const identity = { serverBaseUrl, projectId, taskId, taskModelRunId, sessionId };
1096
1726
  const saved = bindings.ownerForClaim(identity);
@@ -1114,29 +1744,45 @@ async function apply(ctx, config = {}) {
1114
1744
  backupFormat: manifest.sessionBackup.format,
1115
1745
  backupMaxBytes: manifest.sessionBackup.maxBytes
1116
1746
  };
1117
- const claimNonce = existing ? void 0 : saved?.claimNonce ?? randomUUID();
1118
- if (claimNonce) await bindings.put({ ...binding, resourceStatus: "creating", claimNonce });
1747
+ const declarations = manifest.projectSkills ?? [];
1748
+ if (declarations.length || saved?.skillReceipt !== void 0) await beginSkills(binding);
1749
+ const claimNonce = saved?.claimNonce ?? (existing ? void 0 : randomUUID2());
1750
+ const skillsPending = declarations.length || saved?.skillReceipt !== void 0;
1751
+ const pending = skillsPending ? { ...binding, skillReceipt: "pending" } : binding;
1752
+ if (claimNonce) await bindings.put({ ...pending, resourceStatus: "creating", claimNonce });
1753
+ else if (skillsPending) await bindings.put(pending);
1119
1754
  await ctx.credentials.set(credentialRef, token);
1120
1755
  await ctx.settings.mutate(llmEntryId, [
1121
1756
  { op: "set", path: ["providers", provider], value: piAiProviderProfile(manifest, resources) }
1122
1757
  ]);
1123
- const attachmentDirectory = join4(workspace, "attachments");
1124
- await mkdir2(workspace, { recursive: true });
1758
+ const attachmentDirectory = join8(workspace, "attachments");
1759
+ await mkdir5(workspace, { recursive: true });
1125
1760
  const attachmentPaths = [];
1126
1761
  if (manifest.attachments.length > 0) {
1127
- await mkdir2(attachmentDirectory, { recursive: true });
1762
+ await mkdir5(attachmentDirectory, { recursive: true });
1128
1763
  for (const attachment of manifest.attachments) {
1129
1764
  attachmentPaths.push(`attachments/${await downloadAttachment(attachmentDirectory, attachment, signal)}`);
1130
1765
  }
1131
1766
  }
1132
- if (claimNonce) {
1767
+ const ready = declarations.length ? { ...binding, skillReceipt: await skills.prepare(binding, declarations, signal) } : binding;
1768
+ if (!existing && claimNonce) {
1133
1769
  const { workspace: registered } = await ctx.workspaceController.create({ path: workspace });
1134
1770
  const created = await ctx.sessionController.create({ workspaceId: registered.workspaceId, sessionId });
1135
1771
  if (created.sessionId !== sessionId) throw new Error("\u521B\u5EFA\u7684\u4F1A\u8BDD\u6807\u8BC6\u4E0E\u5E73\u53F0\u5206\u914D\u7684\u4E0D\u4E00\u81F4\uFF0C\u65E0\u6CD5\u7ED1\u5B9A\u4F17\u6D4B\u8FD0\u884C");
1136
1772
  await recordCreation(ctx, manifest, provider, claimNonce);
1137
1773
  }
1138
1774
  await pinRunModel(ctx, sessionId, runModelSelection(manifest, resources));
1139
- await bindings.put(binding);
1775
+ if (ready.skillReceipt) {
1776
+ const agent = ctx.agents.get(sessionId);
1777
+ if (!agent) throw new Error("\u8BF7\u5148\u6253\u5F00\u4EFB\u52A1\u4F1A\u8BDD\uFF0C\u518D\u91CD\u65B0\u9886\u53D6\u4EE5\u6838\u9A8C\u9879\u76EE Skills");
1778
+ try {
1779
+ await skills.ensure(ready, agent, signal);
1780
+ await bindings.put(ready);
1781
+ } catch (error) {
1782
+ await skills.invalidate(sessionId);
1783
+ throw error;
1784
+ }
1785
+ } else await bindings.put(ready);
1140
1786
  if (existing && !recovering) return `\u5DF2\u66F4\u65B0\u4EFB\u52A1\u300C${manifest.title}\u300D\u7684\u8FD0\u884C\u51ED\u8BC1\u4E0E\u6A21\u578B\u8DEF\u7531\u3002\u8BF7\u5728\u4FA7\u680F\u6253\u5F00\u5DE5\u4F5C\u533A ${workspace} \u4E2D\u7684\u4F1A\u8BDD\u7EE7\u7EED\u3002`;
1141
1787
  const message = firstTaskMessage(manifest.prompt, attachmentPaths);
1142
1788
  if (config.autoSendPrompt === false) {
@@ -1145,7 +1791,7 @@ async function apply(ctx, config = {}) {
1145
1791
  ${message}`;
1146
1792
  }
1147
1793
  await ctx.sessionController.prompt({
1148
- requestId: randomUUID(),
1794
+ requestId: randomUUID2(),
1149
1795
  sessionId: manifest.sessionId,
1150
1796
  mode: "queue",
1151
1797
  content: [{ type: "text", text: message }]
@@ -1161,7 +1807,7 @@ ${message}`;
1161
1807
  recordInput: false,
1162
1808
  handler: async ({ rawInput, signal }) => {
1163
1809
  try {
1164
- const result = claimQueue.then(() => claim(rawInput, signal));
1810
+ const result = claimQueue.then(() => claim(rawInput, AbortSignal.any([signal, lifetime.signal])));
1165
1811
  claimQueue = result.then(() => void 0, () => void 0);
1166
1812
  return { kind: "success", text: await result };
1167
1813
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-crowdtest",
3
- "version": "0.2.23",
3
+ "version": "0.2.25",
4
4
  "description": "CrowdTest 众测:在 DeepSeek Harness 桌面端领取众测任务、配置测试模型并自动上传会话",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -26,7 +26,9 @@
26
26
  "peerDependencies": {
27
27
  "@deepseek-ai/cordis": "*",
28
28
  "@deepseek-ai/dsh-session": "*",
29
- "@deepseek-ai/dsh-typert-protocol": "*"
29
+ "@deepseek-ai/dsh-typert-protocol": "*",
30
+ "@deepseek-ai/dsh-scope": "*",
31
+ "@deepseek-ai/dsh-skill-filesystem": "*"
30
32
  },
31
33
  "peerDependenciesMeta": {
32
34
  "@deepseek-ai/dsh-session": {
@@ -37,6 +39,12 @@
37
39
  },
38
40
  "@deepseek-ai/dsh-typert-protocol": {
39
41
  "optional": true
42
+ },
43
+ "@deepseek-ai/dsh-scope": {
44
+ "optional": true
45
+ },
46
+ "@deepseek-ai/dsh-skill-filesystem": {
47
+ "optional": true
40
48
  }
41
49
  },
42
50
  "dsh": {