dsh-multigameassistant 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/cordis.patch.yml +16 -1
  2. package/lib/analyzer.js +38 -82
  3. package/lib/browser.js +1 -1
  4. package/lib/{chunk-77ZYHRN7.js → chunk-26JIEF6M.js} +153 -5
  5. package/lib/{chunk-SHTX4AGU.js → chunk-6DSSLS7I.js} +26 -0
  6. package/lib/{chunk-YG4B5G7F.js → chunk-B4UT4NYH.js} +1 -0
  7. package/lib/{chunk-EOWM56PA.js → chunk-EKTA4OYC.js} +3 -3
  8. package/lib/{chunk-TWUATN5X.js → chunk-I4NHWXKH.js} +3 -3
  9. package/lib/{chunk-FH64SAZU.js → chunk-ICJLH3DP.js} +1 -1
  10. package/lib/chunk-J4QJC6UZ.js +22944 -0
  11. package/lib/chunk-J4QJC6UZ.js.LEGAL.txt +8 -0
  12. package/lib/{chunk-MEKSHT6V.js → chunk-KTOQFJ7R.js} +387 -38
  13. package/lib/{chunk-V2X4PLF5.js → chunk-NEUZQ7TI.js} +264 -20
  14. package/lib/emulator.js +3 -3
  15. package/lib/feishu.js +5 -5
  16. package/lib/game-intel.js +454 -57
  17. package/lib/gateway.js +16 -6
  18. package/lib/guard.js +2 -2
  19. package/lib/intervene.js +8 -6
  20. package/lib/low-context.js +3 -3
  21. package/lib/monitor.js +4 -4
  22. package/lib/notify.js +5 -5
  23. package/lib/orchestrator.js +8 -8
  24. package/lib/qqbot.js +5 -5
  25. package/lib/runner.js +4 -4
  26. package/lib/scheduler.js +2 -2
  27. package/lib/script-registry.js +33 -3558
  28. package/lib/webapi-GDSF5EWP.js +2481 -0
  29. package/package.json +1 -1
  30. package/skills/game-intel.md +9 -1
  31. package/skills/script-analysis.md +30 -3
  32. package/skills/web-reading.md +7 -2
  33. package/web/assets/index-C5cMI4PK.css +1 -0
  34. package/web/assets/index-ClYIoZUR.js +244 -0
  35. package/web/assets/index-ClYIoZUR.js.map +1 -0
  36. package/web/index.html +2 -2
  37. package/lib/chunk-RFCFA5P5.js +0 -11
  38. package/lib/games/arknights/game.yaml +0 -36
  39. package/lib/games/endfield/game.yaml +0 -25
  40. package/lib/games/starrail/game.yaml +0 -33
  41. package/lib/packs/maa/adg.script.yaml +0 -220
  42. package/lib/packs/maaend/adg.script.yaml +0 -160
  43. package/lib/packs/march7th/adg.script.yaml +0 -216
  44. package/web/assets/index-C-csjWiw.js +0 -244
  45. package/web/assets/index-C-csjWiw.js.map +0 -1
  46. package/web/assets/index-CjtVfcDS.css +0 -1
@@ -1,3573 +1,48 @@
1
1
  import { createRequire as __adgCreateRequire } from 'node:module'; import { dirname as __adgDirname } from 'node:path'; import { fileURLToPath as __adgFileURLToPath } from 'node:url'; const require = __adgCreateRequire(import.meta.url); const __filename = __adgFileURLToPath(import.meta.url); const __dirname = __adgDirname(__filename);
2
2
  import {
3
- PACKS_DIR
4
- } from "./chunk-RFCFA5P5.js";
5
- import {
6
- GitHubClient,
7
- GitHubError,
8
- MirrorChyanError,
9
- SETUP_NAMES,
10
- applyFix,
11
- archiveKind,
12
- checkEnvironment,
13
- compareVersions,
14
- contentKind,
15
- detectVersion,
16
- download,
17
- extract,
18
- matchesDetect,
19
- mirrorCatalogue,
20
- mirrorLatest,
21
- probeProject,
22
- readMirrorChanges,
23
- runSetup,
24
- setupExitText,
25
- setupKind,
26
- systemHost
27
- } from "./chunk-YG4B5G7F.js";
28
- import {
29
- MANIFEST_FILE,
30
- SKILL_FILE,
31
- chooseAsset,
32
- globToRegExp,
33
- guideView,
34
- parseManifest,
35
- versionOfTag
36
- } from "./chunk-77ZYHRN7.js";
37
- import {
38
- sessionConversations
39
- } from "./chunk-TWUATN5X.js";
40
- import "./chunk-MEKSHT6V.js";
41
- import "./chunk-FH64SAZU.js";
42
- import {
43
- ExeIcons,
44
- writeFileAtomic
45
- } from "./chunk-RESS7WVY.js";
46
- import {
47
- EnvReport,
48
- GitHubRepo,
49
- InstallSettings,
50
- LocalVersion,
51
- MirrorRid,
52
- ProjectProbe,
53
- SCRIPTS_CAPABILITY,
54
- SKILLHUB_CAPABILITY,
55
- ScriptFamily,
56
- ScriptId,
57
- ScriptSource,
58
- ScriptSummary,
59
- SetupAgent,
60
- UPDATE_RULE,
61
- optimizeScriptPrompt,
62
- parseGitHubLink,
63
- taskMessage
64
- } from "./chunk-V2X4PLF5.js";
65
- import {
66
- external_exports
67
- } from "./chunk-SHTX4AGU.js";
3
+ AdgScripts,
4
+ MCP_TOOL_NAMES,
5
+ OPTIMIZE_AFTER_RUNS,
6
+ ScriptIntegrations,
7
+ ScriptLibrary,
8
+ ScriptMcp,
9
+ SkillHub,
10
+ TOOL_NAMES,
11
+ discoverMcp,
12
+ discoverSkills,
13
+ frontmatter,
14
+ lib_default,
15
+ loadPacks,
16
+ mcpEndpoints,
17
+ packForRepo,
18
+ parseMcpConfig,
19
+ readSkills
20
+ } from "./chunk-J4QJC6UZ.js";
21
+ import "./chunk-B4UT4NYH.js";
22
+ import "./chunk-26JIEF6M.js";
23
+ import "./chunk-I4NHWXKH.js";
24
+ import "./chunk-KTOQFJ7R.js";
25
+ import "./chunk-ICJLH3DP.js";
26
+ import "./chunk-RESS7WVY.js";
27
+ import "./chunk-NEUZQ7TI.js";
28
+ import "./chunk-6DSSLS7I.js";
68
29
  import "./chunk-2UFLGPDY.js";
69
-
70
- // packages/script-registry/lib/index.js
71
- import { join as join6 } from "node:path";
72
- import { Service } from "@deepseek-ai/cordis";
73
-
74
- // packages/script-registry/lib/role.js
75
- var SCRIPT_ROLE = {
76
- id: "scripts",
77
- name: "\u811A\u672C",
78
- description: "\u5B89\u88C5\u548C\u4ECB\u7ECD\u811A\u672C\u3001\u68C0\u67E5\u811A\u672C\u5305\u3001\u5408\u5E76\u6280\u80FD",
79
- order: 30,
80
- titles: ["\u5B89\u88C5\u811A\u672C", "\u811A\u672C\u4ECB\u7ECD", "\u68C0\u67E5\u811A\u672C\u5305", "\u5408\u5E76\u6280\u80FD"],
81
- // Scripts, their packs and environment, skills; the screen for setup programs. No game reading or pipelines.
82
- tools: [
83
- "script_*",
84
- "pack_*",
85
- "skill_hub_*",
86
- "emulator_*",
87
- "game_list",
88
- "game_locate",
89
- "game_path_set",
90
- "screen_*",
91
- "window_*",
92
- "monitor_incidents",
93
- "monitor_stall_*",
94
- "system_info",
95
- "skill_focus",
96
- "skill_save",
97
- // Project sites and wikis that need clicking through (the built-in browser).
98
- "browser_*"
99
- ],
100
- duty: [
101
- "# \u4F60\u7684\u89D2\u8272\uFF1A\u811A\u672C",
102
- "\u4F60\u662F MultiGameAssistant \u7684\u300C\u811A\u672C\u300Dagent\uFF1A\u5B89\u88C5\u3001\u66F4\u65B0\u548C\u4ECB\u7ECD\u811A\u672C\uFF0C\u68C0\u67E5\u548C\u4FEE\u597D\u8FD0\u884C\u73AF\u5883\uFF0C\u68C0\u67E5\u811A\u672C\u5305\uFF0C\u5B89\u88C5\u548C\u5408\u5E76\u6280\u80FD\u3002\u7528\u6237\u6216\u540C\u4E8B\u8981\u5728\u6E38\u620F\u91CC\u505A\u4E00\u4EF6\u4E8B\u3001\u800C\u67D0\u4E2A\u811A\u672C\u6709\u8FD9\u4E2A\u4EFB\u52A1\u65F6\uFF0C\u4E5F\u7531\u4F60\u7528 script_run \u8FD0\u884C\u90A3\u4E2A\u4EFB\u52A1\u53BB\u505A\u3002",
103
- UPDATE_RULE,
104
- "script_update \u4ECE Mirror\u9171\uFF08\u8F6F\u4EF6\u91CC\u7684 CDK\uFF0C\u6216\u811A\u672C\u81EA\u5DF1\u8BBE\u7F6E\u91CC\u586B\u7684 CDK\uFF09\u6216 GitHub \u7684\u53D1\u5E03\u5305\u4E0B\u8F7D\uFF0C\u5E76\u63A5\u4E0A\u539F\u6765\u7684\u914D\u7F6E\u3002\u8FD0\u884C\u4EFB\u52A1\u524D\u8F6F\u4EF6\u4E5F\u4F1A\u5148\u8FD9\u6837\u66F4\u65B0\u4E00\u6B21\uFF08\u8DDF\u7740\u5206\u652F\u6E90\u7801\u7684\u811A\u672C\u4E0D\u4F1A\u81EA\u52A8\u66F4\u65B0\uFF09\uFF0C\u66F4\u65B0\u5931\u8D25\u5C31\u7167\u65E7\u7528\u73B0\u6709\u7248\u672C\u8FD0\u884C\u3002",
105
- "\u4E0D\u8BFB\u6E38\u620F\u6D3B\u52A8\u3001\u4E0D\u5199\u65E5\u62A5\u3001\u4E0D\u6539\u6D41\u6C34\u7EBF\u548C\u5B9A\u65F6\uFF1B\u9700\u8981\u8FD9\u4E9B\u65F6\u4EA4\u7ED9\u5BF9\u5E94\u7684\u540C\u4E8B\uFF08agent_delegate\uFF09\uFF0C\u6216\u8005\u5728\u56DE\u590D\u91CC\u8BF4\u6E05\u695A\u3002"
106
- ].join("\n")
107
- };
108
-
109
- // packages/script-registry/lib/capability.js
110
- import { existsSync, readdirSync } from "node:fs";
111
- import { basename, join } from "node:path";
112
- function scriptsCapability(library, summaries, setupAgent, review, optimizer2, icons) {
113
- return {
114
- id: SCRIPTS_CAPABILITY,
115
- version: 1,
116
- methods: {
117
- "scripts/list": () => library.list(),
118
- "scripts/get": (params) => library.get(params.id),
119
- "scripts/guide": (params) => {
120
- const pack = library.packOf(params.id);
121
- return { guide: pack === void 0 ? null : guideView(pack.manifest, { builtin: pack.builtin }) };
122
- },
123
- "scripts/icon": async (params, call) => {
124
- const id = params.id;
125
- const program = scriptProgram(library, id);
126
- if (program === void 0 || icons === void 0 || process.platform !== "win32")
127
- return {};
128
- try {
129
- return { icon: { mediaType: "image/png", data: (await icons.png(program, call.signal)).toString("base64") } };
130
- } catch {
131
- return {};
132
- }
133
- },
134
- "scripts/search": (params, call) => library.search(params.query, call.signal),
135
- "scripts/releases": (params, call) => {
136
- const p = params;
137
- return library.releases(p.repo, p.limit ?? 10, call.signal);
138
- },
139
- "scripts/install": async (params, call) => {
140
- const p = params;
141
- const mirror = p.mirrorchyan === void 0 ? void 0 : await library.lookupMirror(p.mirrorchyan, call.signal);
142
- const { job } = library.install(mirror === void 0 ? { repo: p.repo, tag: p.tag, asset: p.asset, branch: p.branch, id: p.id } : { mirrorchyan: mirror, id: p.id });
143
- return { jobId: job.id, scriptId: job.scriptId };
144
- },
145
- "scripts/checkUpdate": (params, call) => library.checkUpdate(params.id, call.signal),
146
- "scripts/update": async (params, call) => {
147
- const result = await library.update(params.id, call.signal);
148
- return result.upToDate ? { upToDate: true } : { upToDate: false, jobId: result.job.id };
149
- },
150
- "scripts/rollback": (params) => {
151
- const p = params;
152
- return library.rollback(p.id, p.version);
153
- },
154
- "scripts/source/set": async (params, call) => {
155
- const p = params;
156
- const mirrorchyan = typeof p.mirrorchyan === "string" ? await library.lookupMirror(p.mirrorchyan, call.signal) : p.mirrorchyan;
157
- return library.setUpdateSource(p.id, { repo: p.repo, mirrorchyan, reset: p.reset });
158
- },
159
- "scripts/mirrorchyan/search": (params, call) => library.searchMirror(params.query, call.signal),
160
- "scripts/mirrorchyan/match": (params, call) => library.matchMirror(params.id, call.signal),
161
- "scripts/mirrorchyan/lookup": (params, call) => library.lookupMirror(params.rid, call.signal),
162
- "scripts/restore": (params) => library.restore(params.id),
163
- "scripts/packReview": (params) => {
164
- const p = params;
165
- return review.decide(p.id, p.decision);
166
- },
167
- "scripts/setup/open": async (params) => {
168
- const { dir } = await library.runSetup(params.id, { quiet: false });
169
- return { dir };
170
- },
171
- "scripts/setup/agent": async (params) => ({ sessionId: await setupAgent(params.id) }),
172
- "scripts/setup/discard": async (params) => {
173
- await library.discardSetup(params.id);
174
- return {};
175
- },
176
- "scripts/import": (params) => {
177
- const p = params;
178
- return library.import({ path: p.path, id: p.id, name: p.name, packId: p.packId });
179
- },
180
- "scripts/remove": async (params) => {
181
- const p = params;
182
- await library.remove(p.id, p.deleteFiles === true);
183
- return {};
184
- },
185
- "scripts/envCheck": (params) => library.envCheck(params.id),
186
- "scripts/envFix": async (params) => {
187
- const p = params;
188
- const plan = await library.envFixPlan(p.id, p.kind);
189
- if (plan === void 0)
190
- throw new Error("\u8FD9\u4E00\u9879\u5DF2\u7ECF\u6EE1\u8DB3\uFF0C\u65E0\u9700\u5904\u7406");
191
- if (plan.kind === "manual")
192
- throw new Error(plan.description);
193
- return { jobId: library.envFix(p.id, p.kind, plan).job.id };
194
- },
195
- "scripts/jobs": () => ({ items: library.jobs() }),
196
- "scripts/jobs/cancel": (params) => {
197
- library.cancelJob(params.jobId);
198
- return {};
199
- },
200
- "scripts/settings": () => library.settings(),
201
- "scripts/settings/set": (params) => library.setSettings(params),
202
- "scripts/mirrorchyan/check": (_params, call) => library.checkMirrorCdk(call.signal),
203
- "scripts/optimize": async (params) => {
204
- const p = params;
205
- return optimizer2.decide(p.id, p.decision, "\u4F60");
206
- },
207
- "scripts/summarize": async (params) => ({ sessionId: await summaries.summarize(params.id) })
208
- }
209
- };
210
- }
211
- function scriptProgram(library, id) {
212
- let info, pack;
213
- try {
214
- info = library.get(id);
215
- pack = library.packOf(id);
216
- } catch {
217
- return void 0;
218
- }
219
- const launch = pack?.manifest.launch;
220
- if (info.dir === void 0)
221
- return void 0;
222
- if (launch === void 0)
223
- return mainProgram(info.dir);
224
- for (const exe of [launch.settings?.exe, launch.exe]) {
225
- if (exe === void 0)
226
- continue;
227
- const path = join(info.dir, launch.cwd ?? "", exe);
228
- if (existsSync(path))
229
- return path;
230
- if (existsSync(join(info.dir, exe)))
231
- return join(info.dir, exe);
232
- }
233
- return mainProgram(info.dir);
234
- }
235
- var HELPER = /unins|updat|setup|install|crash|report|helper|python|pythonw|pip|node|git|adb|7z|vc_?redist/i;
236
- function mainProgram(dir) {
237
- let exes;
238
- try {
239
- exes = readdirSync(dir).filter((name) => name.toLowerCase().endsWith(".exe") && !HELPER.test(name));
240
- } catch {
241
- return void 0;
242
- }
243
- const folder = basename(dir).toLowerCase();
244
- const named = exes.find((name) => {
245
- const stem = name.slice(0, -4).toLowerCase();
246
- return folder.includes(stem) || stem.includes(folder);
247
- });
248
- const exe = named ?? (exes.length === 1 ? exes[0] : void 0);
249
- return exe === void 0 ? void 0 : join(dir, exe);
250
- }
251
-
252
- // packages/script-registry/lib/library.js
253
- import { existsSync as existsSync2 } from "node:fs";
254
- import { copyFile, cp, mkdir as mkdir2, readdir as readdir2, readFile as readFile3, rename as rename2, rm, stat, writeFile as writeFile2 } from "node:fs/promises";
255
- import { basename as basename2, dirname as dirname2, isAbsolute, join as join3, relative, resolve } from "node:path";
256
-
257
- // packages/script-registry/lib/jobs.js
258
- var KEEP_FINISHED = 20;
259
- var JobBoard = class {
260
- #jobs = /* @__PURE__ */ new Map();
261
- #publish;
262
- #now;
263
- constructor(publish, now = Date.now) {
264
- this.#publish = publish;
265
- this.#now = now;
266
- }
267
- /** The unfinished job on a script, if any. */
268
- active(scriptId) {
269
- for (const { job } of this.#jobs.values())
270
- if (job.scriptId === scriptId && job.endedAt === void 0)
271
- return job;
272
- return void 0;
273
- }
274
- list() {
275
- return [...this.#jobs.values()].map((e) => e.job).sort((a, b) => b.startedAt - a.startedAt);
276
- }
277
- get(id) {
278
- return this.#jobs.get(id)?.job;
279
- }
280
- /**
281
- * Start `work` as a job; it reports through `update` and resolves with the version it produced.
282
- * @throws Error when the script already has an unfinished job.
283
- */
284
- start(kind, scriptId, work) {
285
- const busy = this.active(scriptId);
286
- if (busy !== void 0)
287
- throw new Error(`${scriptId} \u6B63\u5728\u8FDB\u884C\u53E6\u4E00\u4E2A\u4EFB\u52A1\uFF08${busy.kind}\uFF09\uFF0C\u8BF7\u7B49\u5B83\u7ED3\u675F`);
288
- const controller = new AbortController();
289
- const job = { id: `job-${crypto.randomUUID()}`, kind, scriptId, phase: "queued", startedAt: this.#now() };
290
- this.#jobs.set(job.id, { job, controller });
291
- this.#publish(job);
292
- const update = (patch) => {
293
- const entry = this.#jobs.get(job.id);
294
- if (entry === void 0 || entry.job.endedAt !== void 0)
295
- return;
296
- entry.job = { ...entry.job, ...patch };
297
- this.#publish(entry.job);
298
- };
299
- const done = (async () => {
300
- try {
301
- const version = await work({ signal: controller.signal, phase: (phase, extra = {}) => update({ phase, ...extra }) });
302
- update({ phase: "done", endedAt: this.#now(), ...version === void 0 ? {} : { version } });
303
- } catch (error) {
304
- const cancelled = controller.signal.aborted;
305
- update({
306
- phase: cancelled ? "cancelled" : "failed",
307
- endedAt: this.#now(),
308
- error: cancelled ? "\u5DF2\u53D6\u6D88" : error instanceof Error ? error.message : String(error)
309
- });
310
- }
311
- this.#prune();
312
- return this.#jobs.get(job.id).job;
313
- })();
314
- return { job, done };
315
- }
316
- cancel(id) {
317
- const entry = this.#jobs.get(id);
318
- if (entry === void 0 || entry.job.endedAt !== void 0)
319
- return false;
320
- entry.controller.abort(new Error("cancelled by user"));
321
- return true;
322
- }
323
- /** Abort everything (plugin unload). */
324
- dispose() {
325
- for (const { controller } of this.#jobs.values())
326
- controller.abort(new Error("script registry stopped"));
327
- }
328
- #prune() {
329
- const finished = [...this.#jobs.values()].filter((e) => e.job.endedAt !== void 0).sort((a, b) => b.job.startedAt - a.job.startedAt);
330
- for (const entry of finished.slice(KEEP_FINISHED))
331
- this.#jobs.delete(entry.job.id);
332
- }
333
- };
334
-
335
- // packages/script-registry/lib/known-projects.js
336
- var KNOWN_PROJECTS = [
337
- { id: "maa", name: "MAA\uFF08\u660E\u65E5\u65B9\u821F\uFF09", repo: "MaaAssistantArknights/MaaAssistantArknights", mirrorchyan: { rid: "MAA", platform: true } },
338
- { id: "maaend", name: "MaaEnd\uFF08\u7EC8\u672B\u5730\uFF09", repo: "MaaEnd/MaaEnd", mirrorchyan: { rid: "MaaEnd", platform: true } },
339
- { id: "march7th", name: "\u4E09\u6708\u4E03\u5C0F\u52A9\u624B\uFF08\u661F\u7A79\u94C1\u9053\uFF09", repo: "moesnow/March7thAssistant", mirrorchyan: { rid: "March7thAssistant", platform: false } },
340
- { id: "m9a", name: "M9A\uFF08\u91CD\u8FD4\u672A\u6765\uFF1A1999\uFF09", repo: "MAA1999/M9A", mirrorchyan: { rid: "M9A", platform: true } },
341
- { id: "ok-ww", name: "\u9E23\u6F6E ok-ww", repo: "ok-oldking/ok-wuthering-waves", mirrorchyan: { rid: "okww", platform: false } },
342
- // Uploaded for any system but x64 only: asked with arch and without os (without arch Mirror酱 answers an old build).
343
- { id: "zzz-od", name: "\u7EDD\u533A\u96F6 \u4E00\u6761\u9F99", repo: "OneDragon-Anything/ZenlessZoneZero-OneDragon", mirrorchyan: { rid: "ZZZ-OneDragon", platform: false, arch: true } },
344
- {
345
- id: "bettergi",
346
- name: "BetterGI\uFF08\u539F\u795E\uFF09",
347
- repo: "babalae/better-genshin-impact",
348
- mirrorchyan: { rid: "BGI", platform: false },
349
- detect: ["BetterGI.exe"],
350
- version: { exe: "BetterGI.exe" },
351
- family: "gui-config"
352
- }
353
- ];
354
- function knownById(id) {
355
- return id === void 0 ? void 0 : KNOWN_PROJECTS.find((p) => p.id === id);
356
- }
357
- function knownByRepo(repo) {
358
- const lower = repo?.toLowerCase();
359
- return lower === void 0 ? void 0 : KNOWN_PROJECTS.find((p) => p.repo?.toLowerCase() === lower);
360
- }
361
- function knownByMirror(rid) {
362
- const lower = rid.toLowerCase();
363
- return KNOWN_PROJECTS.find((p) => p.mirrorchyan?.rid.toLowerCase() === lower);
364
- }
365
- async function knownByDir(dir) {
366
- for (const project of KNOWN_PROJECTS) {
367
- if (project.detect !== void 0 && await matchesDetect(dir, project.detect))
368
- return project;
369
- }
370
- return void 0;
371
- }
372
- function mirrorResourceFor(pack, repo) {
373
- return pack?.manifest.source.mirrorchyan ?? knownByRepo(repo)?.mirrorchyan;
374
- }
375
-
376
- // packages/script-registry/lib/packs.js
377
- import { readdir, readFile } from "node:fs/promises";
378
- import { join as join2 } from "node:path";
379
- async function loadPacks(dirs) {
380
- const packs = /* @__PURE__ */ new Map();
381
- const errors = [];
382
- for (const { dir, builtin } of dirs) {
383
- const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
384
- for (const entry of entries) {
385
- if (!entry.isDirectory() || entry.name.startsWith("."))
386
- continue;
387
- const packDir = join2(dir, entry.name);
388
- const file = join2(packDir, MANIFEST_FILE);
389
- let text;
390
- try {
391
- text = await readFile(file, "utf8");
392
- } catch {
393
- continue;
394
- }
395
- try {
396
- const manifest = parseManifest(text, file);
397
- if (manifest.id !== entry.name)
398
- throw new Error(`${file}: id "${manifest.id}" must match its directory name "${entry.name}"`);
399
- const skill = await readFile(join2(packDir, SKILL_FILE), "utf8").catch(() => void 0);
400
- const under = packs.get(manifest.id);
401
- packs.set(manifest.id, { manifest, dir: packDir, builtin, ...skill === void 0 ? {} : { skill }, ...!builtin && under?.builtin === true ? { over: under } : {} });
402
- } catch (error) {
403
- errors.push({ id: entry.name, dir: packDir, builtin, error: error instanceof Error ? error.message : String(error) });
404
- }
405
- }
406
- }
407
- return { packs, errors };
408
- }
409
- function packForRepo(packs, repo) {
410
- const wanted = repo.toLowerCase();
411
- for (const pack of packs.values())
412
- if (pack.manifest.source.github?.toLowerCase() === wanted)
413
- return pack;
414
- return void 0;
415
- }
416
-
417
- // packages/script-registry/lib/state.js
418
- import { mkdir, readFile as readFile2, rename, writeFile } from "node:fs/promises";
419
- import { dirname } from "node:path";
420
- var StoredVersion = external_exports.object({
421
- version: external_exports.string(),
422
- dir: external_exports.string(),
423
- installedAt: external_exports.number(),
424
- asset: external_exports.object({ name: external_exports.string(), size: external_exports.number() }).optional()
425
- });
426
- var LocalBackup = external_exports.object({
427
- dir: external_exports.string(),
428
- /** Version before the update, when it was known. */
429
- from: external_exports.string().optional(),
430
- to: external_exports.string(),
431
- at: external_exports.number(),
432
- /** Relative paths (`/`) the update created: undoing deletes them. */
433
- added: external_exports.array(external_exports.string()),
434
- /** Relative paths it overwrote or deleted: their old copies are in `files/`. */
435
- saved: external_exports.array(external_exports.string())
436
- });
437
- var StoredScript = external_exports.object({
438
- id: external_exports.string(),
439
- name: external_exports.string(),
440
- source: ScriptSource,
441
- packId: external_exports.string().optional(),
442
- family: ScriptFamily.optional(),
443
- current: external_exports.string().optional(),
444
- versions: external_exports.array(StoredVersion),
445
- env: EnvReport.optional(),
446
- probe: ProjectProbe.optional(),
447
- update: external_exports.object({ latest: external_exports.string(), available: external_exports.boolean(), checkedAt: external_exports.number() }).optional(),
448
- addedAt: external_exports.number(),
449
- /** GitHub update channel the user set (`owner/repo`); undefined: the automatic one. `null`: the user turned it off. */
450
- updateFrom: external_exports.string().nullable().optional(),
451
- /** Mirror酱 update channel the user set, likewise. */
452
- mirrorchyan: external_exports.object({ rid: external_exports.string(), platform: external_exports.boolean(), os: external_exports.boolean().optional(), arch: external_exports.boolean().optional() }).nullable().optional(),
453
- /** The known project (no pack describes it) an imported folder was recognized as. */
454
- known: external_exports.string().optional(),
455
- /** The version found in a local import's directory, and where it was read. */
456
- localVersion: LocalVersion.optional(),
457
- /** Files a local update replaced or removed, newest last; `dir` holds them under `files/`. */
458
- backups: external_exports.array(LocalBackup).optional(),
459
- /** The agent's summary of what the script is. */
460
- summary: ScriptSummary.optional(),
461
- /** Installed from this branch's source (the repository has no releases): updates follow the branch. */
462
- sourceBranch: external_exports.string().optional(),
463
- /** The script version its pack was written or last checked for (a newer one asks to check the pack). */
464
- packVersion: external_exports.string().optional(),
465
- /** The version the user was last asked about, so each update asks once. */
466
- packReviewAsked: external_exports.string().optional(),
467
- /**
468
- * 优化脚本: clean runs since `since` (it was last optimized, the offer turned
469
- * down, or first counted), at `version`; `at` when it was last optimized;
470
- * `asked` the offer already made for this stretch.
471
- */
472
- optimize: external_exports.object({ runs: external_exports.number(), since: external_exports.number(), version: external_exports.string().optional(), at: external_exports.number().optional(), asked: external_exports.string().optional() }).optional()
473
- });
474
- var PendingSetup = external_exports.object({
475
- scriptId: external_exports.string(),
476
- name: external_exports.string(),
477
- kind: external_exports.enum(["nsis", "inno", "kachina"]),
478
- /** The installer, kept in the script's downloads folder until it is done. */
479
- file: external_exports.string(),
480
- version: external_exports.string(),
481
- asset: external_exports.object({ name: external_exports.string(), size: external_exports.number() }),
482
- /** Where it installs: a new version folder, or a local import's own folder (updated in place). */
483
- dir: external_exports.string(),
484
- /** How a new script came (an update keeps the script's own). */
485
- source: ScriptSource,
486
- packId: external_exports.string().optional(),
487
- /** Updating an existing script. */
488
- update: external_exports.boolean(),
489
- at: external_exports.number(),
490
- agent: SetupAgent.optional()
491
- });
492
- var DEFAULT_SETTINGS = {
493
- apiBase: "https://api.github.com",
494
- downloadMirror: "",
495
- mirrorFallback: true,
496
- tokenRef: "GITHUB_TOKEN",
497
- keepVersions: 3,
498
- includePrereleases: false,
499
- cdkRef: "MIRRORCHYAN_CDK",
500
- autoUpdate: "ask"
501
- };
502
- var StateFile = external_exports.object({
503
- version: external_exports.literal(1),
504
- settings: InstallSettings.partial().default({}),
505
- scripts: external_exports.array(StoredScript).default([]),
506
- setups: external_exports.array(PendingSetup).default([])
507
- });
508
- var StateStore = class {
509
- file;
510
- #writing = Promise.resolve();
511
- constructor(file) {
512
- this.file = file;
513
- }
514
- /** Read the state; a missing file is an empty library, a corrupt one is kept aside and reported. */
515
- async load(defaults, log) {
516
- let text;
517
- try {
518
- text = await readFile2(this.file, "utf8");
519
- } catch {
520
- return { settings: { ...DEFAULT_SETTINGS, ...defaults }, scripts: [], setups: [] };
521
- }
522
- const parsed = StateFile.safeParse(safeJson(text));
523
- if (!parsed.success) {
524
- const aside = `${this.file}.corrupt-${Date.now()}`;
525
- await rename(this.file, aside).catch(() => {
526
- });
527
- log.warn(`script library state was unreadable and was moved to ${aside}: ${parsed.error.message}`);
528
- return { settings: { ...DEFAULT_SETTINGS, ...defaults }, scripts: [], setups: [] };
529
- }
530
- return { settings: { ...DEFAULT_SETTINGS, ...defaults, ...stripUndefined(parsed.data.settings) }, scripts: parsed.data.scripts, setups: parsed.data.setups };
531
- }
532
- /** Persist; writes are serialized so the last state always wins. */
533
- save(state) {
534
- const text = `${JSON.stringify({ version: 1, settings: state.settings, scripts: state.scripts, ...state.setups.length === 0 ? {} : { setups: state.setups } }, null, 2)}
535
- `;
536
- this.#writing = this.#writing.catch(() => {
537
- }).then(async () => {
538
- await mkdir(dirname(this.file), { recursive: true });
539
- const temp = `${this.file}.${process.pid}.tmp`;
540
- await writeFile(temp, text);
541
- await rename(temp, this.file);
542
- });
543
- return this.#writing;
544
- }
545
- };
546
- function safeJson(text) {
547
- try {
548
- return JSON.parse(text);
549
- } catch {
550
- return void 0;
551
- }
552
- }
553
- function stripUndefined(value) {
554
- return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== void 0));
555
- }
556
-
557
- // packages/script-registry/lib/library.js
558
- var CATALOGUE_TTL_MS = 24 * 60 * 6e4;
559
- var PRE_RUN_CHECK_MS = 3e4;
560
- var MAX_SETUP_ONLY_FILES = 4;
561
- var ScriptLibrary = class {
562
- toolsDir;
563
- formerToolsDirs;
564
- #options;
565
- #store;
566
- #jobs;
567
- #now;
568
- #state = { settings: DEFAULT_SETTINGS, scripts: [], setups: [] };
569
- #packs = /* @__PURE__ */ new Map();
570
- #packErrors = [];
571
- #checkers = /* @__PURE__ */ new Map();
572
- #packListeners = /* @__PURE__ */ new Set();
573
- #catalogue;
574
- constructor(options) {
575
- this.#options = options;
576
- this.toolsDir = resolve(options.toolsDir);
577
- this.formerToolsDirs = (options.formerToolsDirs ?? []).map((dir) => resolve(dir)).filter((dir) => !samePath(dir, this.toolsDir));
578
- this.#store = new StateStore(join3(options.dataDir, "scripts.json"));
579
- this.#now = options.now ?? Date.now;
580
- this.#jobs = new JobBoard(options.onJob, this.#now);
581
- }
582
- get sharedDir() {
583
- const own = join3(this.toolsDir, "_shared");
584
- if (!existsSync2(own)) {
585
- for (const former of this.formerToolsDirs)
586
- if (existsSync2(join3(former, "_shared")))
587
- return join3(former, "_shared");
588
- }
589
- return own;
590
- }
591
- async start() {
592
- this.#state = await this.#store.load(this.#options.defaults ?? {}, this.#options.log);
593
- for (const setup of this.#state.setups) {
594
- if (setup.agent?.state === "running")
595
- setup.agent = { ...setup.agent, state: "failed", reason: "\u7A0B\u5E8F\u91CD\u65B0\u542F\u52A8\u4E86\uFF0Cagent \u6CA1\u6709\u88C5\u5B8C" };
596
- }
597
- await this.reloadPacks();
598
- for (const script of this.#state.scripts)
599
- await this.#recognize(script);
600
- }
601
- dispose() {
602
- this.#jobs.dispose();
603
- }
604
- async reloadPacks() {
605
- const dirs = [
606
- ...this.#options.packDirs.map((dir) => ({ dir, builtin: true })),
607
- { dir: join3(this.#options.dataDir, "packs"), builtin: false }
608
- ];
609
- const { packs, errors } = await loadPacks(dirs);
610
- this.#packs = packs;
611
- this.#packErrors = errors;
612
- for (const error of errors)
613
- this.#options.log.warn(`script pack skipped: ${error.error}`);
614
- for (const listener of this.#packListeners)
615
- listener();
616
- }
617
- /** Let another plugin check a requirement kind (e.g. `emulator`). @returns the disposer. */
618
- registerEnvChecker(kind, checker) {
619
- this.#checkers.set(kind, checker);
620
- return () => {
621
- if (this.#checkers.get(kind) === checker)
622
- this.#checkers.delete(kind);
623
- };
624
- }
625
- /** Run `listener` after packs are (re)loaded. @returns the disposer. */
626
- onPacksChanged(listener) {
627
- this.#packListeners.add(listener);
628
- return () => {
629
- this.#packListeners.delete(listener);
630
- };
631
- }
632
- /** Every loaded pack. */
633
- packs() {
634
- return [...this.#packs.values()];
635
- }
636
- /** The pack describing a library script, if any. */
637
- packOf(id) {
638
- const packId = this.#script(id).packId;
639
- return packId === void 0 ? void 0 : this.#packs.get(packId);
640
- }
641
- /** Directories MultiGameAssistant must not let the agent rewrite: the tools directories and every imported directory. */
642
- protectedDirs() {
643
- return [this.toolsDir, ...this.formerToolsDirs, ...this.#state.scripts.filter((s) => s.source.kind === "local").map((s) => s.source.path)];
644
- }
645
- pack(id) {
646
- return this.#packs.get(id);
647
- }
648
- // ── reading ───────────────────────────────────────────────────────────
649
- list() {
650
- const used = new Set(this.#state.scripts.map((s) => s.packId).filter(Boolean));
651
- const packs = [...this.#packs.values()].map(({ manifest, builtin }) => ({
652
- id: manifest.id,
653
- name: manifest.name,
654
- builtin,
655
- installed: used.has(manifest.id),
656
- ...manifest.description === void 0 ? {} : { description: manifest.description },
657
- ...manifest.source.github === void 0 ? {} : { repo: manifest.source.github },
658
- ...manifest.source.mirrorchyan === void 0 ? {} : { mirrorchyan: manifest.source.mirrorchyan.rid },
659
- ...manifest.family === void 0 ? {} : { family: manifest.family }
660
- }));
661
- for (const error of this.#packErrors)
662
- packs.push({ id: error.id, name: error.id, builtin: error.builtin, installed: false, error: error.error });
663
- const known = KNOWN_PROJECTS.filter((p) => p.repo === void 0 || packForRepo(this.#packs, p.repo) === void 0).map((p) => ({
664
- id: p.id,
665
- name: p.name,
666
- installed: this.#state.scripts.some((s) => s.known === p.id || s.source.kind === "github" && s.source.repo.toLowerCase() === p.repo?.toLowerCase() || s.source.kind === "mirrorchyan" && s.source.rid === p.mirrorchyan?.rid),
667
- ...p.repo === void 0 ? {} : { repo: p.repo },
668
- ...p.mirrorchyan === void 0 ? {} : { mirrorchyan: p.mirrorchyan.rid }
669
- }));
670
- const setups = this.#state.setups.map(({ file: _file, asset: _asset, source: _source, packId: _packId, ...shown }) => shown);
671
- return { scripts: this.#state.scripts.map((s) => this.#info(s)), packs, known, setups, toolsDir: this.toolsDir };
672
- }
673
- get(id) {
674
- return this.#info(this.#script(id));
675
- }
676
- jobs() {
677
- return this.#jobs.list();
678
- }
679
- cancelJob(jobId) {
680
- if (!this.#jobs.cancel(jobId))
681
- throw new Error("\u4EFB\u52A1\u4E0D\u5B58\u5728\u6216\u5DF2\u7ED3\u675F");
682
- }
683
- async settings() {
684
- return {
685
- ...this.#state.settings,
686
- tokenConfigured: await this.#options.credentialConfigured(this.#state.settings.tokenRef),
687
- cdkConfigured: await this.#options.credentialConfigured(this.#state.settings.cdkRef)
688
- };
689
- }
690
- /** Ask Mirror酱 with the CDK (for a script it carries) whether the CDK works, and until when. */
691
- async checkMirrorCdk(signal) {
692
- const cdk = await this.#options.credential(this.#state.settings.cdkRef);
693
- if (cdk === void 0 || cdk === "")
694
- return { ok: false, message: "\u8FD8\u6CA1\u6709\u586B\u5199 Mirror\u9171 CDK" };
695
- const resource = [...this.#packs.values()].map((p) => p.manifest.source.mirrorchyan).find((r) => r !== void 0);
696
- if (resource === void 0)
697
- return { ok: false, message: "\u6CA1\u6709\u5728 Mirror\u9171 \u53D1\u5E03\u7684\u811A\u672C\u5305\uFF0C\u65E0\u6CD5\u68C0\u67E5" };
698
- try {
699
- const latest = await mirrorLatest(resource, this.#mirrorOptions(cdk, signal));
700
- const until = latest.cdkExpiresAt === void 0 ? "" : `\uFF0C\u5230 ${new Date(latest.cdkExpiresAt).toLocaleDateString("zh-CN")} \u5230\u671F`;
701
- return { ok: true, message: `CDK \u53EF\u7528${until}`, ...latest.cdkExpiresAt === void 0 ? {} : { expiresAt: latest.cdkExpiresAt } };
702
- } catch (error) {
703
- return { ok: false, message: errorText(error) };
704
- }
705
- }
706
- async setSettings(patch) {
707
- const defined = Object.fromEntries(Object.entries(patch).filter(([, v]) => v !== void 0));
708
- this.#state.settings = { ...this.#state.settings, ...defined };
709
- await this.#save();
710
- this.#options.onChanged();
711
- return this.#state.settings;
712
- }
713
- // ── GitHub ────────────────────────────────────────────────────────────
714
- async search(query, signal) {
715
- const items = await this.#github().search(query, 10, signal);
716
- return { items: items.map((item) => ({ ...item, ...packForRepo(this.#packs, item.repo) === void 0 ? {} : { packId: packForRepo(this.#packs, item.repo).manifest.id } })) };
717
- }
718
- async releases(repo, limit = 10, signal) {
719
- const pack = packForRepo(this.#packs, repo);
720
- const releases = await this.#github().releases(repo, limit, signal);
721
- return {
722
- repo,
723
- ...pack === void 0 ? {} : { packId: pack.manifest.id },
724
- releases: releases.map((release) => {
725
- const choice = chooseAsset(release.assets, { ...globsOf(pack), tag: release.tag });
726
- return { ...release, ...choice.asset === void 0 ? {} : { suggestedAsset: choice.asset.name } };
727
- })
728
- };
729
- }
730
- /** Download a file from GitHub through the download mirror the user set (the skills repository uses it). */
731
- async downloadFromGitHub(url, dest, signal) {
732
- const settings = this.#state.settings;
733
- await download({
734
- url,
735
- dest,
736
- mirror: settings.downloadMirror,
737
- mirrorFallback: settings.mirrorFallback,
738
- ...signal === void 0 ? {} : { signal },
739
- ...this.#options.fetch === void 0 ? {} : { fetch: this.#options.fetch }
740
- });
741
- }
742
- /** Unpack an archive safely into a new folder (a single top folder lifted). */
743
- unpack(archive, dest, signal) {
744
- return extract(archive, dest, signal === void 0 ? {} : { signal });
745
- }
746
- /** Whether `repo` is described by a pack this installation ships (curated). */
747
- isKnownRepo(repo) {
748
- return packForRepo(this.#packs, repo)?.builtin === true;
749
- }
750
- /** Id an install of `repo` would use. */
751
- scriptIdFor(repo, id) {
752
- return id ?? packForRepo(this.#packs, repo)?.manifest.id ?? knownByRepo(repo)?.id ?? slug(repo.split("/")[1] ?? repo);
753
- }
754
- /** Whether a Mirror酱 resource is one a pack or the known-project list names (curated). */
755
- isKnownMirror(rid) {
756
- return knownByMirror(rid) !== void 0 || this.#packForMirror(rid)?.builtin === true;
757
- }
758
- /**
759
- * Whether Mirror酱 has `rid`, its latest version, and how to ask for its
760
- * Windows build. No CDK is needed. Its project list says how; for a
761
- * resource not on it (or when the list cannot be read), the pack or the
762
- * known-project list, else each way of asking is tried.
763
- */
764
- async lookupMirror(rid, signal) {
765
- const { projects } = await this.mirrorProjects(signal);
766
- const listed = projects.find((p) => p.rid.toLowerCase() === rid.toLowerCase());
767
- if (listed !== void 0 && listed.windows === void 0)
768
- throw new Error(`Mirror\u9171 \u4E0A\u7684 ${listed.name}\uFF08${listed.rid}\uFF09\u6CA1\u6709 Windows \u7248`);
769
- if (listed !== void 0 && !listed.download)
770
- throw new Error(`Mirror\u9171 \u4E0D\u63D0\u4F9B ${listed.name}\uFF08${listed.rid}\uFF09\u7684\u4E0B\u8F7D`);
771
- const named = (resource, version) => {
772
- const pack = this.#packForMirror(resource.rid);
773
- const project = knownByMirror(resource.rid);
774
- const name = pack?.manifest.name ?? project?.name ?? listed?.name;
775
- const repo = pack?.manifest.source.github ?? project?.repo ?? listed?.repo;
776
- return {
777
- rid: resource.rid,
778
- version: versionOfTag(version),
779
- platform: resource.platform,
780
- ...resource.os === void 0 ? {} : { os: resource.os },
781
- ...resource.arch === void 0 ? {} : { arch: resource.arch },
782
- ...name === void 0 ? {} : { name },
783
- ...listed?.description === void 0 || listed.description === "" ? {} : { description: listed.description },
784
- ...repo === void 0 ? {} : { repo }
785
- };
786
- };
787
- const known = listed?.windows ?? this.#packForMirror(rid)?.manifest.source.mirrorchyan ?? knownByMirror(rid)?.mirrorchyan;
788
- if (known !== void 0)
789
- return named(known, (await mirrorLatest(known, this.#mirrorOptions(void 0, signal))).version);
790
- let last;
791
- for (const [os, arch] of [[true, true], [false, false], [false, true], [true, false]]) {
792
- const resource = { rid, platform: os && arch, os, arch };
793
- try {
794
- return named(resource, (await mirrorLatest(resource, this.#mirrorOptions(void 0, signal))).version);
795
- } catch (error) {
796
- if (!(error instanceof MirrorChyanError) || error.code !== 8001)
797
- throw error;
798
- last = error;
799
- }
800
- }
801
- throw last;
802
- }
803
- /**
804
- * Mirror酱's project list, read at most once a day (kept in
805
- * `<dataDir>/mirrorchyan-projects.json`, so an older copy serves when it
806
- * cannot be read); without any copy, the packs and known projects on it.
807
- * Needs no CDK.
808
- */
809
- async mirrorProjects(signal) {
810
- const file = join3(this.#options.dataDir, "mirrorchyan-projects.json");
811
- if (this.#catalogue === void 0) {
812
- try {
813
- const saved = JSON.parse(await readFile3(file, "utf8"));
814
- if (typeof saved.at === "number" && Array.isArray(saved.projects))
815
- this.#catalogue = { at: saved.at, projects: saved.projects };
816
- } catch {
817
- }
818
- }
819
- const cached = this.#catalogue;
820
- if (cached !== void 0 && this.#now() - cached.at < CATALOGUE_TTL_MS)
821
- return { projects: cached.projects, from: "mirrorchyan", fetchedAt: cached.at };
822
- try {
823
- const projects = await mirrorCatalogue({
824
- ...this.#options.mirrorchyanBase === void 0 ? {} : { base: this.#options.mirrorchyanBase },
825
- ...this.#options.fetch === void 0 ? {} : { fetch: this.#options.fetch },
826
- ...signal === void 0 ? {} : { signal }
827
- });
828
- this.#catalogue = { at: this.#now(), projects };
829
- await mkdir2(dirname2(file), { recursive: true });
830
- await writeFile2(file, `${JSON.stringify(this.#catalogue)}
831
- `).catch(() => {
832
- });
833
- return { projects, from: "mirrorchyan", fetchedAt: this.#catalogue.at };
834
- } catch (error) {
835
- if (signal?.aborted === true)
836
- throw error;
837
- this.#options.log.warn(`Mirror\u9171 project list: ${errorText(error)}`);
838
- if (cached !== void 0)
839
- return { projects: cached.projects, from: "mirrorchyan", fetchedAt: cached.at };
840
- return { projects: this.#builtinMirrorProjects(), from: "builtin" };
841
- }
842
- }
843
- /**
844
- * Search Mirror酱's tools (with a Windows build it hands out) by name,
845
- * game, id or repository; every word of `query` must match. An empty query
846
- * lists them all, the known ones first. Needs no CDK.
847
- */
848
- async searchMirror(query, signal) {
849
- const list = await this.mirrorProjects(signal);
850
- const words = query.split(/\s+/).map(squash).filter((w) => w !== "");
851
- const scored = [];
852
- for (const p of list.projects) {
853
- if (p.windows === void 0 || !p.download || p.type !== "" && p.type !== "GameTools")
854
- continue;
855
- const fields = { rid: squash(p.rid), name: squash(p.name), repo: squash(p.repo ?? ""), description: squash(p.description) };
856
- let score = 0;
857
- let all = true;
858
- for (const word of words) {
859
- const s = fields.rid === word ? 100 : fields.name === word ? 90 : fields.rid.includes(word) || fields.name.includes(word) ? 60 : fields.repo.includes(word) ? 40 : fields.description.includes(word) ? 30 : 0;
860
- if (s === 0) {
861
- all = false;
862
- break;
863
- }
864
- score += s;
865
- }
866
- if (!all)
867
- continue;
868
- const known = this.isKnownMirror(p.rid);
869
- scored.push({
870
- // The ones MultiGameAssistant recognizes and updates first, unless another is named exactly.
871
- score: score + (known ? 40 : 0),
872
- item: {
873
- rid: p.rid,
874
- name: p.name,
875
- description: p.description,
876
- installed: this.#state.scripts.some((s) => this.#channels(s).mirror?.resource.rid.toLowerCase() === p.rid.toLowerCase()),
877
- known,
878
- ...p.repo === void 0 ? {} : { repo: p.repo },
879
- ...p.url === void 0 ? {} : { url: p.url }
880
- }
881
- });
882
- }
883
- scored.sort((a, b) => b.score - a.score || a.item.name.localeCompare(b.item.name, "zh-CN"));
884
- return { items: scored.map((s) => s.item), from: list.from, ...list.fetchedAt === void 0 ? {} : { fetchedAt: list.fetchedAt } };
885
- }
886
- /**
887
- * Whether a script is on Mirror酱, for one that has no Mirror酱 channel
888
- * yet: the projects whose GitHub repository is its repository, else whose
889
- * name or id is in its name (or the reverse). Needs no CDK.
890
- */
891
- async matchMirror(id, signal) {
892
- const script = this.#script(id);
893
- const { items, from } = await this.searchMirror("", signal);
894
- const repo = this.#channels(script).github?.repo.toLowerCase();
895
- const byRepo = repo === void 0 ? [] : items.filter((i) => i.repo?.toLowerCase() === repo);
896
- if (byRepo.length > 0)
897
- return { items: byRepo.map((i) => ({ ...i, by: "repo" })), from };
898
- const names = [script.name, script.id, script.source.kind === "local" ? basename2(script.source.path) : void 0].filter((n) => n !== void 0).map(squash).filter((n) => n.length >= 2);
899
- const byName = items.filter((i) => {
900
- const keys = [squash(i.name), squash(i.rid)].filter((k) => k.length >= 3);
901
- return keys.some((k) => names.some((n) => n.includes(k) || k.includes(n)));
902
- });
903
- return { items: byName.map((i) => ({ ...i, by: "name" })), from };
904
- }
905
- /** The packs and known projects on Mirror酱, for when its list cannot be read. */
906
- #builtinMirrorProjects() {
907
- const out = /* @__PURE__ */ new Map();
908
- const add = (resource, name, repo, description = "") => {
909
- if (out.has(resource.rid.toLowerCase()))
910
- return;
911
- out.set(resource.rid.toLowerCase(), { rid: resource.rid, name, description, type: "GameTools", download: true, windows: resource, ...repo === void 0 ? {} : { repo } });
912
- };
913
- for (const pack of this.#packs.values()) {
914
- const resource = pack.manifest.source.mirrorchyan;
915
- if (resource !== void 0)
916
- add(resource, pack.manifest.name, pack.manifest.source.github, pack.manifest.description ?? "");
917
- }
918
- for (const project of KNOWN_PROJECTS)
919
- if (project.mirrorchyan !== void 0)
920
- add(project.mirrorchyan, project.name, project.repo);
921
- return [...out.values()];
922
- }
923
- // ── installing ────────────────────────────────────────────────────────
924
- /** Start an install from GitHub (`repo`) or Mirror酱 (`mirrorchyan`); the returned promise settles when the job ends. */
925
- install(request) {
926
- const mirror = request.mirrorchyan;
927
- if (request.repo === void 0 === (mirror === void 0))
928
- throw new Error("\u8BF7\u7ED9\u51FA GitHub \u4ED3\u5E93\u6216 Mirror\u9171 \u8D44\u6E90 id \u4E4B\u4E00");
929
- const pack = request.repo !== void 0 ? packForRepo(this.#packs, request.repo) : this.#packForMirror(mirror.rid);
930
- const scriptId = request.repo !== void 0 ? this.scriptIdFor(request.repo, request.id) : request.id ?? pack?.manifest.id ?? knownByMirror(mirror.rid)?.id ?? slug(mirror.rid);
931
- const existing = this.#state.scripts.find((s) => s.id === scriptId);
932
- if (existing !== void 0 && existing.source.kind === "local") {
933
- throw new Error(`id ${scriptId} \u5DF2\u88AB\u672C\u5730\u5BFC\u5165\u7684\u811A\u672C\u4F7F\u7528\uFF0C\u8BF7\u6362\u4E00\u4E2A id`);
934
- }
935
- const source = request.repo !== void 0 ? { kind: "github", repo: request.repo } : { kind: "mirrorchyan", ...resourceOf(mirror) };
936
- if (existing !== void 0 && !sameSource(existing.source, source)) {
937
- throw new Error(`id ${scriptId} \u5DF2\u5C5E\u4E8E ${describeSource(existing.source)}\uFF0C\u8BF7\u6362\u4E00\u4E2A id`);
938
- }
939
- const channels = existing !== void 0 ? this.#channels(existing) : this.#newChannels(source, pack);
940
- const use = request.tag !== void 0 || request.asset !== void 0 || request.branch !== void 0 ? channels.github === void 0 ? {} : { github: channels.github } : channels;
941
- return this.#jobs.start(existing === void 0 ? "install" : "update", scriptId, (ctl) => this.#installJob(scriptId, source, request, use, pack, ctl));
942
- }
943
- /**
944
- * Compare the current version with the latest release, from Mirror酱 with
945
- * a CDK else GitHub (Mirror酱 without a CDK when it is the only channel).
946
- * A local import is compared by the version found in its directory (read
947
- * again each time: the script may have updated itself).
948
- */
949
- async checkUpdate(id, signal) {
950
- const script = this.#script(id);
951
- await this.#recognize(script);
952
- const pack = this.#packOf(script);
953
- const channels = this.#channels(script);
954
- if (channels.github === void 0 && channels.mirror === void 0) {
955
- throw new Error("\u8FD9\u4E2A\u811A\u672C\u8FD8\u6CA1\u6709\u66F4\u65B0\u6E20\u9053\uFF1A\u5728\u811A\u672C\u9875\u586B\u5199\u5B83\u7684 GitHub \u4ED3\u5E93\uFF08owner/repo\uFF09\u6216 Mirror\u9171 \u8D44\u6E90 id \u540E\u518D\u68C0\u67E5");
956
- }
957
- let current = script.current;
958
- if (script.source.kind === "local") {
959
- const found = await this.#detectVersion(script);
960
- if (found !== void 0)
961
- script.localVersion = found;
962
- current = script.localVersion?.version;
963
- }
964
- const version = await this.#latestVersion(id, channels, pack, signal, script.sourceBranch);
965
- const managed = script.source.kind !== "local";
966
- const available = current === void 0 || (script.sourceBranch !== void 0 ? version !== current : compareVersions(version, current) > 0 || managed && compareVersions(version, current) === 0 && version !== current);
967
- script.update = { latest: version, available, checkedAt: this.#now() };
968
- await this.#save();
969
- this.#options.onChanged(id);
970
- return { ...current === void 0 ? {} : { current }, latest: version, available };
971
- }
972
- /**
973
- * Update to the latest release over its channels. An installed script gets
974
- * it beside the current version; a local import is updated in its own
975
- * directory, with what it replaces backed up first (see {@link restore}).
976
- */
977
- async update(id, signal, options = {}) {
978
- const script = this.#script(id);
979
- const check = await this.checkUpdate(id, signal);
980
- if (!check.available)
981
- return { upToDate: true };
982
- const channels = this.#channels(script);
983
- if (script.source.kind === "local") {
984
- return { upToDate: false, ...this.#jobs.start("update", id, (ctl) => this.#localUpdateJob(script, channels, ctl, options.byAgent === true)) };
985
- }
986
- const source = script.source;
987
- return { upToDate: false, ...this.#jobs.start("update", id, (ctl) => this.#installJob(id, source, { byAgent: options.byAgent }, channels, this.#packOf(script), ctl)) };
988
- }
989
- /**
990
- * Before a task runs: update when a newer version is out and the settings
991
- * say `auto`; otherwise only check, and leave the update to the user. Never
992
- * throws — the run goes on with what it has. Left alone: a script without an update
993
- * channel, one following a branch's source (official releases only), or one another job is installing. A release that is a setup
994
- * program is left waiting for the agent and counts as not updated.
995
- */
996
- async updateBeforeRun(id, signal) {
997
- if (!this.#checkable(id))
998
- return { state: "skipped" };
999
- const policy = this.#state.settings.autoUpdate;
1000
- if (policy !== "auto") {
1001
- try {
1002
- const check = await this.checkUpdate(id, AbortSignal.any([signal, AbortSignal.timeout(PRE_RUN_CHECK_MS)]));
1003
- return check.available ? { state: "available", version: check.latest, policy } : { state: "current" };
1004
- } catch {
1005
- return { state: "skipped" };
1006
- }
1007
- }
1008
- try {
1009
- const started = await this.update(id, AbortSignal.any([signal, AbortSignal.timeout(PRE_RUN_CHECK_MS)]), { byAgent: true });
1010
- if (started.upToDate)
1011
- return { state: "current" };
1012
- const cancel = () => {
1013
- this.#jobs.cancel(started.job.id);
1014
- };
1015
- signal.addEventListener("abort", cancel, { once: true });
1016
- const job = await started.done.finally(() => signal.removeEventListener("abort", cancel));
1017
- if (job.phase !== "done")
1018
- return { state: "failed", error: job.error ?? "\u6CA1\u6709\u66F4\u65B0\u5B8C" };
1019
- if (job.setup !== void 0)
1020
- return { state: "failed", error: `\u65B0\u7248\u672C ${job.version ?? ""} \u662F\u5B89\u88C5\u7A0B\u5E8F\uFF0C\u8981 agent \u8FD0\u884C\u5B83\u88C5\u597D\uFF08\u811A\u672C\u9875\u80FD\u770B\u5230\uFF09` };
1021
- return { state: "updated", version: job.version ?? this.get(id).current ?? "" };
1022
- } catch (error) {
1023
- return { state: "failed", error: signal.aborted ? "\u5DF2\u505C\u6B62" : errorText(error) };
1024
- }
1025
- }
1026
- /**
1027
- * Check every script that can update on its own (see {@link updateBeforeRun}) for a newer version,
1028
- * one after another; what it finds is on each script (`update`). Never throws.
1029
- */
1030
- async checkUpdates(signal) {
1031
- for (const { id } of [...this.#state.scripts]) {
1032
- if (signal?.aborted === true)
1033
- return;
1034
- if (!this.#checkable(id))
1035
- continue;
1036
- try {
1037
- await this.checkUpdate(id, signal);
1038
- } catch (error) {
1039
- this.#options.log.info(`update check for ${id} failed: ${errorText(error)}`);
1040
- }
1041
- }
1042
- }
1043
- /** It has an update channel, follows releases (not a branch's source), and nothing is installing it. */
1044
- #checkable(id) {
1045
- const script = this.#script(id);
1046
- const channels = this.#channels(script);
1047
- if (channels.github === void 0 && channels.mirror === void 0)
1048
- return false;
1049
- return script.sourceBranch === void 0 && this.#jobs.active(id) === void 0;
1050
- }
1051
- /**
1052
- * Set a script's update channels: a value sets it, `null` turns it off,
1053
- * `reset` goes back to the automatic one. How it was installed stays its
1054
- * channel (an installed script's repository, a Mirror酱 install's resource).
1055
- */
1056
- async setUpdateSource(id, patch) {
1057
- const script = this.#script(id);
1058
- if (patch.repo !== void 0 || patch.reset?.includes("repo") === true) {
1059
- if (script.source.kind === "github")
1060
- throw new Error("\u4ECE GitHub \u5B89\u88C5\u7684\u811A\u672C\u8DDF\u968F\u5B83\u5B89\u88C5\u65F6\u7684\u4ED3\u5E93\u66F4\u65B0");
1061
- if (patch.reset?.includes("repo") === true)
1062
- delete script.updateFrom;
1063
- else
1064
- script.updateFrom = patch.repo;
1065
- }
1066
- if (patch.mirrorchyan !== void 0 || patch.reset?.includes("mirrorchyan") === true) {
1067
- if (script.source.kind === "mirrorchyan")
1068
- throw new Error("\u4ECE Mirror\u9171 \u5B89\u88C5\u7684\u811A\u672C\u8DDF\u968F\u5B83\u5B89\u88C5\u65F6\u7684\u8D44\u6E90\u66F4\u65B0");
1069
- if (patch.reset?.includes("mirrorchyan") === true)
1070
- delete script.mirrorchyan;
1071
- else
1072
- script.mirrorchyan = patch.mirrorchyan === null ? null : resourceOf(patch.mirrorchyan);
1073
- }
1074
- delete script.update;
1075
- await this.#save();
1076
- this.#options.onChanged(id);
1077
- return this.#info(script);
1078
- }
1079
- async #installJob(scriptId, source, request, channels, pack, ctl) {
1080
- const script = this.#state.scripts.find((s) => s.id === scriptId);
1081
- const previous = script === void 0 ? void 0 : currentVersion(script);
1082
- const have = (version2) => script?.versions.some((v) => v.version === version2 && (request.asset === void 0 || v.asset?.name === request.asset)) === true;
1083
- const branch = request.branch ?? (request.tag === void 0 && request.asset === void 0 ? script?.sourceBranch : void 0);
1084
- const previousAsset = script?.versions.find((v) => v.version === previous?.version)?.asset?.name;
1085
- const fetched = await this.#fetch(scriptId, channels, pack, previous?.version, ctl, { ...request, branch, previousAsset }, have);
1086
- const followBranch = async () => {
1087
- const added = this.#state.scripts.find((s) => s.id === scriptId);
1088
- if (added === void 0 || added.sourceBranch === fetched.branch)
1089
- return;
1090
- if (fetched.branch === void 0)
1091
- delete added.sourceBranch;
1092
- else
1093
- added.sourceBranch = fetched.branch;
1094
- await this.#save();
1095
- };
1096
- const { version, archive } = fetched;
1097
- if (archive === void 0 && script !== void 0) {
1098
- script.current = version;
1099
- delete script.update;
1100
- await this.#save();
1101
- this.#options.onChanged(scriptId);
1102
- ctl.phase("done", { message: `${version} \u5DF2\u5B89\u88C5\uFF0C\u5DF2\u5207\u6362\u4E3A\u5F53\u524D\u7248\u672C`, version });
1103
- return version;
1104
- }
1105
- const versionDir = join3(this.toolsDir, scriptId, dirName(version));
1106
- const setup = await setupKind(archive);
1107
- if (setup !== void 0) {
1108
- return this.#handOffSetup(setup, { scriptId, file: archive, version, asset: fetched.asset, dir: versionDir, source: script?.source ?? source, ...pack === void 0 ? {} : { packId: pack.manifest.id }, update: script !== void 0 }, request.byAgent === true, ctl);
1109
- }
1110
- const root = pack?.manifest.install.root;
1111
- ctl.phase("extracting", { message: fetched.incremental ? `\u5728 ${previous.version} \u7684\u57FA\u7840\u4E0A\u66F4\u65B0\u5230 ${version}` : `\u89E3\u538B\u5230 ${versionDir}` });
1112
- await rm(versionDir, { recursive: true, force: true });
1113
- if (!fetched.incremental) {
1114
- await extract(archive, versionDir, { signal: ctl.signal, ...root === void 0 ? {} : { root } });
1115
- const inner = await this.#takeSoleSetup(versionDir, archive);
1116
- if (inner !== void 0) {
1117
- return this.#handOffSetup(inner.kind, { scriptId, file: inner.file, version, asset: fetched.asset, dir: versionDir, source: script?.source ?? source, ...pack === void 0 ? {} : { packId: pack.manifest.id }, update: script !== void 0 }, request.byAgent === true, ctl);
1118
- }
1119
- } else {
1120
- const patch = `${versionDir}.patch`;
1121
- await rm(patch, { recursive: true, force: true });
1122
- await extract(archive, patch, { signal: ctl.signal });
1123
- try {
1124
- await cp(previous.dir, versionDir, { recursive: true });
1125
- const prefix = await patchPrefix(patch, previous.dir, root);
1126
- const from = prefix === void 0 ? patch : join3(patch, prefix);
1127
- await cp(from, versionDir, { recursive: true, force: true });
1128
- if (from === patch)
1129
- await rm(join3(versionDir, "changes.json"), { force: true });
1130
- const gone = await readMirrorChanges(patch, prefix) ?? [];
1131
- for (const rel of gone)
1132
- await rm(join3(versionDir, ...rel.split("/")), { recursive: true, force: true });
1133
- if (gone.length > 0)
1134
- this.#options.log.info(`${scriptId}: the incremental package removed ${gone.length} path(s)`);
1135
- } catch (error) {
1136
- await rm(versionDir, { recursive: true, force: true });
1137
- throw error;
1138
- } finally {
1139
- await rm(patch, { recursive: true, force: true });
1140
- }
1141
- }
1142
- await rm(archive, { force: true });
1143
- await this.#addVersion(scriptId, source, pack, version, versionDir, fetched.asset, ctl);
1144
- await followBranch();
1145
- return version;
1146
- }
1147
- /** A version unpacked (or installed) in `dir` becomes the current one, the script added if it is new. */
1148
- async #addVersion(scriptId, source, pack, version, dir, asset, ctl, name) {
1149
- let script = this.#state.scripts.find((s) => s.id === scriptId);
1150
- const previous = script === void 0 ? void 0 : currentVersion(script);
1151
- if (previous !== void 0 && pack !== void 0 && !samePath(previous.dir, dir)) {
1152
- const carried = await carryConfig(pack, previous.dir, dir);
1153
- if (carried.length > 0)
1154
- this.#options.log.info(`${scriptId}: carried ${carried.length} config file(s) from ${previous.version}`);
1155
- }
1156
- if (script === void 0) {
1157
- const known = source.kind === "github" ? knownByRepo(source.repo) : source.kind === "mirrorchyan" ? knownByMirror(source.rid) : void 0;
1158
- script = {
1159
- id: scriptId,
1160
- name: name ?? newName(scriptId, source, pack),
1161
- source,
1162
- versions: [],
1163
- addedAt: this.#now(),
1164
- ...pack === void 0 ? {} : { packId: pack.manifest.id },
1165
- ...pack === void 0 && known !== void 0 ? { known: known.id } : {},
1166
- ...(pack?.manifest.family ?? known?.family) === void 0 ? {} : { family: pack?.manifest.family ?? known?.family }
1167
- };
1168
- this.#state.scripts.push(script);
1169
- }
1170
- script.versions = script.versions.filter((v) => v.version !== version);
1171
- script.versions.push({ version, dir, installedAt: this.#now(), asset });
1172
- script.current = version;
1173
- delete script.update;
1174
- script.probe = await probeProject(dir);
1175
- if (script.family === void 0 && script.probe.family !== void 0)
1176
- script.family = script.probe.family;
1177
- await this.#prune(script);
1178
- await this.#save();
1179
- this.#options.onChanged(scriptId);
1180
- if (pack !== void 0 && pack.manifest.install.requires.length > 0) {
1181
- ctl?.phase("checking", { message: "\u68C0\u67E5\u8FD0\u884C\u73AF\u5883" });
1182
- await this.envCheck(scriptId);
1183
- }
1184
- }
1185
- // ── setup programs ──────────────────────────────────────────────────
1186
- /**
1187
- * The download is a setup program: keep it for the agent instead of
1188
- * unpacking it. Without `byAgent` the app starts a conversation for it.
1189
- * @returns the version it will install.
1190
- */
1191
- async #handOffSetup(kind, setup, byAgent, ctl) {
1192
- const pack = setup.packId === void 0 ? void 0 : this.#packs.get(setup.packId);
1193
- const pending = { ...setup, kind, name: this.#state.scripts.find((s) => s.id === setup.scriptId)?.name ?? newName(setup.scriptId, setup.source, pack), at: this.#now() };
1194
- for (const old of this.#state.setups.filter((s) => s.scriptId === setup.scriptId && !samePath(s.file, setup.file)))
1195
- await rm(old.file, { force: true });
1196
- this.#state.setups = [...this.#state.setups.filter((s) => s.scriptId !== setup.scriptId), pending];
1197
- await this.#save();
1198
- this.#options.onChanged(setup.scriptId);
1199
- const what = `${basename2(setup.file)} \u662F ${SETUP_NAMES[kind]} \u5B89\u88C5\u7A0B\u5E8F\uFF0C\u4E0D\u662F\u538B\u7F29\u5305`;
1200
- const handed = { kind, dir: setup.dir };
1201
- const sessionId = byAgent ? void 0 : await this.#options.onSetup?.(pending).catch((error) => {
1202
- this.#options.log.warn(`${setup.scriptId}: setup program not handed to the agent: ${errorText(error)}`);
1203
- return void 0;
1204
- });
1205
- if (sessionId === void 0) {
1206
- ctl.phase("running", { message: `${what}\uFF1A\u8BA9 agent \u7528 script_setup_run \u8FD0\u884C\u5B83\uFF0C\u88C5\u597D\u540E\u7528 script_import \u5BFC\u5165 ${setup.dir}`, setup: handed });
1207
- } else {
1208
- ctl.phase("running", { message: `${what}\uFF0C\u5DF2\u4EA4\u7ED9 agent \u5B89\u88C5\uFF08\u5BF9\u8BDD\u300C\u5B89\u88C5\u811A\u672C\uFF1A${pending.name}\u300D\uFF09`, setup: { ...handed, sessionId } });
1209
- }
1210
- return setup.version;
1211
- }
1212
- /**
1213
- * An unpacked archive that is only a setup program (one exe, a few files at
1214
- * most, and that exe an installer): the exe is moved beside the archive,
1215
- * the unpacked folder and the archive deleted. @returns where the exe is
1216
- * now and what installer it is; undefined for anything else (left as it is).
1217
- */
1218
- async #takeSoleSetup(dir, archive) {
1219
- const files = await listFiles(dir).catch(() => []);
1220
- const exes = files.filter((f) => f.toLowerCase().endsWith(".exe"));
1221
- if (exes.length !== 1 || files.length > MAX_SETUP_ONLY_FILES)
1222
- return void 0;
1223
- const inside = join3(dir, ...exes[0].split("/"));
1224
- const kind = await setupKind(inside);
1225
- if (kind === void 0)
1226
- return void 0;
1227
- const file = join3(dirname2(archive), basename2(inside));
1228
- if (!samePath(file, archive)) {
1229
- await rm(file, { force: true });
1230
- await rename2(inside, file);
1231
- await rm(archive, { force: true });
1232
- }
1233
- await rm(dir, { recursive: true, force: true });
1234
- return { file, kind };
1235
- }
1236
- /** The setup program waiting to be run for a script, if any. */
1237
- pendingSetup(id) {
1238
- return this.#state.setups.find((s) => s.scriptId === id);
1239
- }
1240
- /** Note how the agent is doing with a script's waiting setup program (undefined: no agent on it). */
1241
- async setSetupAgent(id, agent) {
1242
- const setup = this.pendingSetup(id);
1243
- if (setup === void 0)
1244
- return;
1245
- if (agent === void 0)
1246
- delete setup.agent;
1247
- else
1248
- setup.agent = agent;
1249
- await this.#save();
1250
- this.#options.onChanged(id);
1251
- }
1252
- /** Give up a script's waiting setup program: deleted, nothing installed. */
1253
- async discardSetup(id) {
1254
- const setup = this.pendingSetup(id);
1255
- if (setup === void 0)
1256
- return;
1257
- this.#state.setups = this.#state.setups.filter((s) => s !== setup);
1258
- await rm(setup.file, { force: true });
1259
- await this.#save();
1260
- this.#options.onChanged(id);
1261
- }
1262
- /**
1263
- * Run a script's waiting setup program: quietly into its folder, waiting
1264
- * until it is done; or with its own window (returning at once), for the
1265
- * agent to click through. Then `import` of that folder finishes the install.
1266
- */
1267
- async runSetup(id, options) {
1268
- const setup = this.pendingSetup(id);
1269
- if (setup === void 0)
1270
- throw new Error(`${id} \u6CA1\u6709\u7B49\u5F85\u8FD0\u884C\u7684\u5B89\u88C5\u7A0B\u5E8F`);
1271
- if (!await exists(setup.file)) {
1272
- this.#state.setups = this.#state.setups.filter((s) => s !== setup);
1273
- await this.#save();
1274
- throw new Error(`\u5B89\u88C5\u7A0B\u5E8F ${setup.file} \u5DF2\u7ECF\u4E0D\u5728\u4E86\uFF1A\u8BF7\u91CD\u65B0\u5B89\u88C5\u6216\u66F4\u65B0 ${setup.name}`);
1275
- }
1276
- const fresh = this.#ownsDir(setup.dir) && this.#state.scripts.find((s) => s.id === id)?.versions.some((v) => samePath(v.dir, setup.dir)) !== true;
1277
- if (options.quiet && fresh)
1278
- await rm(setup.dir, { recursive: true, force: true });
1279
- const exitCode = await runSetup(setup.file, { kind: setup.kind, dir: setup.dir, quiet: options.quiet, ...options.signal === void 0 ? {} : { signal: options.signal } });
1280
- if (exitCode === void 0)
1281
- return { dir: setup.dir, result: `${SETUP_NAMES[setup.kind]} \u5B89\u88C5\u7A0B\u5E8F\u7684\u7A97\u53E3\u5DF2\u7ECF\u6253\u5F00\uFF0C\u5B89\u88C5\u4F4D\u7F6E\u9884\u5148\u586B\u597D\u4E86 ${setup.dir}` };
1282
- const files = await exists(setup.dir) ? (await listFiles(setup.dir)).length : 0;
1283
- this.#options.log.info(`${id}: setup ${basename2(setup.file)} exited ${exitCode}, ${files} file(s) in ${setup.dir}`);
1284
- return { dir: setup.dir, exitCode, result: setupExitText(setup.kind, exitCode), files, executables: files === 0 ? [] : (await probeProject(setup.dir)).executables };
1285
- }
1286
- /** The agent imported the folder a setup program installed into: the install (or update) is done. */
1287
- async #finishSetup(setup, path, request) {
1288
- if (!await stat(path).then((s) => s.isDirectory(), () => false))
1289
- throw new Error(`\u4E0D\u662F\u4E00\u4E2A\u5B58\u5728\u7684\u76EE\u5F55\uFF1A${path}`);
1290
- if ((await listFiles(path)).length === 0)
1291
- throw new Error(`${path} \u662F\u7A7A\u7684\uFF1A\u5B89\u88C5\u7A0B\u5E8F\u8FD8\u6CA1\u628A\u6587\u4EF6\u88C5\u8FDB\u53BB`);
1292
- const script = this.#state.scripts.find((s) => s.id === setup.scriptId);
1293
- const pack = setup.packId === void 0 ? void 0 : this.#packs.get(setup.packId);
1294
- const inside = (dir) => {
1295
- const rel = relative(join3(this.toolsDir, setup.scriptId), dir);
1296
- return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
1297
- };
1298
- let id = setup.scriptId;
1299
- if (script?.source.kind === "local") {
1300
- if (!samePath(script.source.path, path))
1301
- throw new Error(`${script.name} \u5728 ${script.source.path}\uFF0C\u5B89\u88C5\u7A0B\u5E8F\u8981\u88C5\u56DE\u90A3\u91CC\uFF08\u73B0\u5728\u7ED9\u7684\u662F ${path}\uFF09`);
1302
- script.localVersion = { version: setup.version, from: "\u5B89\u88C5\u7A0B\u5E8F" };
1303
- delete script.update;
1304
- script.probe = await probeProject(path);
1305
- } else if (inside(path)) {
1306
- await this.#addVersion(setup.scriptId, setup.source, pack, setup.version, path, setup.asset, void 0, request.name ?? setup.name);
1307
- } else if (script !== void 0) {
1308
- throw new Error(`\u5B89\u88C5\u7A0B\u5E8F\u88C5\u5230\u4E86 ${path}\uFF1B${script.name} \u7684\u65B0\u7248\u672C\u8981\u88C5\u5728 ${setup.dir}`);
1309
- } else {
1310
- id = (await this.#importLocal(path, { id: setup.scriptId, name: request.name ?? setup.name, packId: request.packId ?? setup.packId })).id;
1311
- this.#script(id).localVersion ??= { version: setup.version, from: "\u5B89\u88C5\u7A0B\u5E8F" };
1312
- }
1313
- this.#state.setups = this.#state.setups.filter((s) => s !== setup);
1314
- await rm(setup.file, { force: true });
1315
- await this.#save();
1316
- this.#options.onChanged(id);
1317
- return this.#info(this.#script(id));
1318
- }
1319
- /**
1320
- * Update a local import where it is. The release is unpacked aside; every
1321
- * file it would overwrite or delete is first copied to
1322
- * `<toolsDir>/<id>/.local-backup/<time>/files/`; the pack's config files
1323
- * (and the usual user-data folders) that exist are left as they are. A
1324
- * failure part way (a file in use) puts the old files back.
1325
- */
1326
- async #localUpdateJob(script, channels, ctl, byAgent = false) {
1327
- const target = script.source.path;
1328
- const pack = this.#packOf(script);
1329
- const fetched = await this.#fetch(script.id, channels, pack, script.localVersion?.version, ctl);
1330
- const { version } = fetched;
1331
- const archive = fetched.archive;
1332
- const setup = await setupKind(archive);
1333
- if (setup !== void 0) {
1334
- return this.#handOffSetup(setup, { scriptId: script.id, file: archive, version, asset: fetched.asset, dir: target, source: script.source, ...pack === void 0 ? {} : { packId: pack.manifest.id }, update: true }, byAgent, ctl);
1335
- }
1336
- const root = pack?.manifest.install.root;
1337
- const staging = join3(this.toolsDir, script.id, ".staging");
1338
- try {
1339
- ctl.phase("extracting", { message: `\u89E3\u538B ${fetched.asset.name}` });
1340
- await rm(staging, { recursive: true, force: true });
1341
- await extract(archive, staging, { signal: ctl.signal, ...fetched.incremental || root === void 0 ? {} : { root } });
1342
- const inner = fetched.incremental ? void 0 : await this.#takeSoleSetup(staging, archive);
1343
- if (inner !== void 0) {
1344
- return this.#handOffSetup(inner.kind, { scriptId: script.id, file: inner.file, version, asset: fetched.asset, dir: target, source: script.source, ...pack === void 0 ? {} : { packId: pack.manifest.id }, update: true }, byAgent, ctl);
1345
- }
1346
- const prefix = fetched.incremental ? await patchPrefix(staging, target, root) : void 0;
1347
- const from = prefix === void 0 ? staging : join3(staging, prefix);
1348
- const keep = await keptFiles(pack, target);
1349
- const writes = (await listFiles(from)).filter((rel) => !keep.has(rel.toLowerCase()) && !(fetched.incremental && from === staging && rel === "changes.json"));
1350
- const removes = [];
1351
- for (const rel of fetched.incremental ? await readMirrorChanges(staging, prefix) ?? [] : []) {
1352
- if (!keep.has(rel.toLowerCase()) && await exists(join3(target, ...rel.split("/"))))
1353
- removes.push(rel);
1354
- }
1355
- const at = this.#now();
1356
- const dir = join3(this.toolsDir, script.id, ".local-backup", String(at));
1357
- const backup = { dir, to: version, at, added: [], saved: [], ...script.localVersion === void 0 ? {} : { from: script.localVersion.version } };
1358
- ctl.phase("running", { message: `\u5907\u4EFD\u5C06\u88AB\u66FF\u6362\u7684\u6587\u4EF6\uFF08${target}\uFF09` });
1359
- for (const rel of writes) {
1360
- const path = join3(target, ...rel.split("/"));
1361
- if (await exists(path)) {
1362
- await saveCopy(path, join3(dir, "files", ...rel.split("/")));
1363
- backup.saved.push(rel);
1364
- } else {
1365
- backup.added.push(rel);
1366
- }
1367
- }
1368
- for (const rel of removes) {
1369
- await saveCopy(join3(target, ...rel.split("/")), join3(dir, "files", ...rel.split("/")));
1370
- backup.saved.push(rel);
1371
- }
1372
- await writeFile2(join3(dir, "manifest.json"), `${JSON.stringify({ script: script.id, target, ...backup }, null, 2)}
1373
- `);
1374
- ctl.phase("running", { message: `\u66F4\u65B0 ${target} \u5230 ${version}` });
1375
- let doing = "";
1376
- try {
1377
- for (const rel of writes) {
1378
- doing = rel;
1379
- const path = join3(target, ...rel.split("/"));
1380
- await mkdir2(dirname2(path), { recursive: true });
1381
- await copyFile(join3(from, ...rel.split("/")), path);
1382
- }
1383
- for (const rel of removes) {
1384
- doing = rel;
1385
- await rm(join3(target, ...rel.split("/")), { recursive: true, force: true });
1386
- }
1387
- } catch (error) {
1388
- const back = await putBack(target, backup).then(() => "\u5DF2\u6539\u56DE\u66F4\u65B0\u524D\u7684\u6587\u4EF6", (e) => `\u6539\u56DE\u65F6\u4E5F\u51FA\u9519\u4E86\uFF08${errorText(e)}\uFF09\uFF0C\u5907\u4EFD\u5728 ${dir}`);
1389
- await rm(dir, { recursive: true, force: true }).catch(() => {
1390
- });
1391
- const code = error.code;
1392
- throw new Error(code === "EBUSY" || code === "EPERM" || code === "EACCES" ? `${doing} \u6B63\u88AB\u5360\u7528\u6216\u6CA1\u6709\u5199\u5165\u6743\u9650\uFF0C\u8BF7\u5148\u5173\u95ED\u811A\u672C\u518D\u66F4\u65B0\uFF1B${back}` : `\u66F4\u65B0 ${doing} \u65F6\u51FA\u9519\uFF1A${errorText(error)}\uFF1B${back}`);
1393
- }
1394
- script.backups = [...script.backups ?? [], backup];
1395
- const keepBackups = this.#state.settings.keepVersions;
1396
- for (const old of script.backups.slice(0, -keepBackups))
1397
- await rm(old.dir, { recursive: true, force: true });
1398
- script.backups = script.backups.slice(-keepBackups);
1399
- script.localVersion = { version, from: "\u66F4\u65B0" };
1400
- delete script.update;
1401
- script.probe = await probeProject(target);
1402
- await this.#save();
1403
- this.#options.onChanged(script.id);
1404
- this.#options.log.info(`${script.id}: updated ${target} in place to ${version} (${backup.saved.length} replaced, ${backup.added.length} added)`);
1405
- return version;
1406
- } finally {
1407
- await rm(staging, { recursive: true, force: true });
1408
- await rm(archive, { force: true });
1409
- }
1410
- }
1411
- /** Undo a local import's last in-place update: the files it replaced or removed back, the ones it added deleted. */
1412
- async restore(id) {
1413
- const script = this.#script(id);
1414
- if (script.source.kind !== "local")
1415
- throw new Error("\u5B89\u88C5\u7684\u811A\u672C\u8BF7\u7528\u56DE\u6EDA\u5207\u6362\u7248\u672C");
1416
- if (this.#jobs.active(id) !== void 0)
1417
- throw new Error(`${id} \u6709\u4EFB\u52A1\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7A0D\u540E\u518D\u64A4\u9500`);
1418
- const backup = script.backups?.at(-1);
1419
- if (backup === void 0)
1420
- throw new Error("\u6CA1\u6709\u53EF\u4EE5\u64A4\u9500\u7684\u66F4\u65B0");
1421
- if (!await exists(join3(backup.dir, "manifest.json")))
1422
- throw new Error(`\u5907\u4EFD\u5DF2\u4E0D\u5B58\u5728\uFF1A${backup.dir}`);
1423
- try {
1424
- await putBack(script.source.path, backup);
1425
- } catch (error) {
1426
- throw new Error(`\u64A4\u9500\u5931\u8D25\uFF08${errorText(error)}\uFF09\uFF1A\u53EF\u80FD\u6709\u6587\u4EF6\u6B63\u88AB\u5360\u7528\uFF0C\u8BF7\u5148\u5173\u95ED\u811A\u672C\u518D\u8BD5`);
1427
- }
1428
- await rm(backup.dir, { recursive: true, force: true });
1429
- script.backups = script.backups.slice(0, -1);
1430
- const found = await this.#detectVersion(script);
1431
- if (found !== void 0)
1432
- script.localVersion = found;
1433
- else if (backup.from !== void 0)
1434
- script.localVersion = { version: backup.from, from: "\u64A4\u9500\u66F4\u65B0" };
1435
- else
1436
- delete script.localVersion;
1437
- delete script.update;
1438
- await this.#save();
1439
- this.#options.onChanged(id);
1440
- return this.#info(script);
1441
- }
1442
- /**
1443
- * A script's update channels, each on its own: what the user set (or
1444
- * turned off), how it was installed, its pack, the known project.
1445
- */
1446
- #channels(script) {
1447
- const pack = this.#packOf(script);
1448
- const known = knownById(script.known);
1449
- const source = script.source;
1450
- const github = source.kind === "github" ? { repo: source.repo, from: "install" } : script.updateFrom === null ? void 0 : script.updateFrom !== void 0 ? { repo: script.updateFrom, from: "user" } : pack?.manifest.source.github !== void 0 ? { repo: pack.manifest.source.github, from: "pack" } : known?.repo !== void 0 ? { repo: known.repo, from: "known" } : void 0;
1451
- const byRepo = mirrorResourceFor(pack, github?.repo);
1452
- const mirror = source.kind === "mirrorchyan" ? { resource: resourceOf(source), from: "install" } : script.mirrorchyan === null ? void 0 : script.mirrorchyan !== void 0 ? { resource: script.mirrorchyan, from: "user" } : pack?.manifest.source.mirrorchyan !== void 0 ? { resource: pack.manifest.source.mirrorchyan, from: "pack" } : known?.mirrorchyan !== void 0 ? { resource: known.mirrorchyan, from: "known" } : byRepo !== void 0 ? { resource: byRepo, from: "known" } : void 0;
1453
- return { ...github === void 0 ? {} : { github }, ...mirror === void 0 ? {} : { mirror } };
1454
- }
1455
- /** The channels a new install starts with. */
1456
- #newChannels(source, pack) {
1457
- const draft = {
1458
- id: "",
1459
- name: "",
1460
- source,
1461
- versions: [],
1462
- addedAt: 0,
1463
- ...pack === void 0 ? {} : { packId: pack.manifest.id },
1464
- ...(() => {
1465
- const known = source.kind === "github" ? knownByRepo(source.repo) : source.kind === "mirrorchyan" ? knownByMirror(source.rid) : void 0;
1466
- return pack === void 0 && known !== void 0 ? { known: known.id } : {};
1467
- })()
1468
- };
1469
- return this.#channels(draft);
1470
- }
1471
- /** A local import no pack describes: is it a known project? (Also for folders imported before it was known.) */
1472
- async #recognize(script) {
1473
- if (script.source.kind !== "local" || script.packId !== void 0 || script.known !== void 0)
1474
- return;
1475
- const known = await knownByDir(script.source.path);
1476
- if (known === void 0)
1477
- return;
1478
- script.known = known.id;
1479
- if (script.family === void 0 && known.family !== void 0)
1480
- script.family = known.family;
1481
- await this.#save();
1482
- }
1483
- #packOf(script) {
1484
- return script.packId === void 0 ? void 0 : this.#packs.get(script.packId);
1485
- }
1486
- #packForMirror(rid) {
1487
- const lower = rid.toLowerCase();
1488
- return [...this.#packs.values()].find((p) => p.manifest.source.mirrorchyan?.rid.toLowerCase() === lower) ?? (knownByMirror(rid)?.repo === void 0 ? void 0 : packForRepo(this.#packs, knownByMirror(rid).repo));
1489
- }
1490
- /** The version in a local import's directory: where its pack (or the known project) says, else the usual places and its main program's file version. */
1491
- #detectVersion(script) {
1492
- const pack = this.#packOf(script);
1493
- const known = knownById(script.known);
1494
- const top = (script.probe?.executables ?? []).filter((e) => !/[\\/]/.test(e) && !/unins|update|crash|adb|setup|helper/i.test(e));
1495
- const main = pack?.manifest.launch?.exe;
1496
- const executables = [...main === void 0 ? [] : [main], ...top];
1497
- const spec = pack?.manifest.install.version ?? known?.version;
1498
- return detectVersion(script.source.path, {
1499
- ...spec === void 0 ? {} : { spec },
1500
- executables: [...new Set(executables)],
1501
- host: this.#options.envHost ?? systemHost
1502
- });
1503
- }
1504
- /**
1505
- * The release file over the script's channels: Mirror酱 with a CDK (an
1506
- * incremental package from `from` when it has one), else GitHub. A script
1507
- * only on Mirror酱 needs the CDK, and says so.
1508
- */
1509
- async #fetch(scriptId, channels, pack, from, ctl, request = {}, have) {
1510
- const onlyMirror = channels.github === void 0;
1511
- if (channels.mirror !== void 0 && request.branch === void 0) {
1512
- const fetched = await this.#fromMirror(scriptId, channels.mirror.resource, from, ctl, onlyMirror, have);
1513
- if (fetched !== void 0)
1514
- return fetched;
1515
- }
1516
- if (channels.github === void 0)
1517
- throw new Error("\u8FD9\u4E2A\u811A\u672C\u6CA1\u6709\u53EF\u4EE5\u4E0B\u8F7D\u7684\u66F4\u65B0\u6E20\u9053");
1518
- return this.#fromGitHub(scriptId, { repo: channels.github.repo, ...request }, pack, ctl, have);
1519
- }
1520
- /**
1521
- * The release's file from GitHub (through the download mirror); no download when `have` says the version is already there.
1522
- * A repository without releases (or a branch asked for) gets its source instead (`#fromSource`).
1523
- */
1524
- async #fromGitHub(scriptId, request, pack, ctl, have) {
1525
- const settings = this.#state.settings;
1526
- if (request.branch !== void 0)
1527
- return this.#fromSource(scriptId, request.repo, { branch: request.branch }, ctl, have);
1528
- ctl.phase("resolving", { message: `\u8BFB\u53D6 ${request.repo} \u7684\u53D1\u5E03\u4FE1\u606F` });
1529
- const github = this.#github();
1530
- let release;
1531
- try {
1532
- release = request.tag === void 0 ? await github.latest(request.repo, { includePrereleases: this.#prereleases(pack), signal: ctl.signal }) : await github.release(request.repo, request.tag, ctl.signal);
1533
- } catch (error) {
1534
- if (!(error instanceof GitHubError) || error.status !== 404)
1535
- throw error;
1536
- if (request.tag !== void 0)
1537
- return this.#fromSource(scriptId, request.repo, { tag: request.tag }, ctl, have);
1538
- if ((await github.releases(request.repo, 1, ctl.signal)).length > 0) {
1539
- throw new Error(`${request.repo} \u53EA\u6709\u9884\u53D1\u5E03\u7248\u672C\uFF1A\u5728\u300C\u8BBE\u7F6E \u2192 \u811A\u672C\u5B89\u88C5\u300D\u6253\u5F00\u300C\u5B89\u88C5\u9884\u53D1\u5E03\u7248\u672C\u300D\uFF0C\u6216\u6307\u5B9A\u4E00\u4E2A\u7248\u672C\u6807\u7B7E`);
1540
- }
1541
- return this.#fromSource(scriptId, request.repo, {}, ctl, have);
1542
- }
1543
- const asset = request.asset === void 0 ? (() => {
1544
- const choice = chooseAsset(release.assets, { ...globsOf(pack), tag: release.tag });
1545
- if (choice.asset === void 0)
1546
- throw new Error(`${choice.reason}\u3002\u53EF\u9009\u6587\u4EF6\uFF1A${release.assets.map((a) => a.name).join("\u3001") || "\uFF08\u65E0\uFF09"}`);
1547
- if (choice.alternatives === void 0)
1548
- return choice.asset;
1549
- const shape = (name) => name.toLowerCase().replace(/\d+/g, "#");
1550
- const same = request.previousAsset === void 0 ? void 0 : choice.alternatives.find((a) => shape(a.name) === shape(request.previousAsset));
1551
- if (same !== void 0)
1552
- return same;
1553
- if (request.byAgent === true) {
1554
- throw new AssetChoiceError(`${release.tag} \u6709\u51E0\u4E2A\u6587\u4EF6\u90FD\u9002\u5408\u672C\u673A\uFF1A${choice.alternatives.map((a) => a.name).join("\u3001")}\u3002\u5148\u95EE\u7528\u6237\u8981\u54EA\u4E00\u4E2A\uFF08\u8BF4\u660E\u5B83\u4EEC\u7684\u533A\u522B\uFF0C\u4F8B\u5982 CPU / GPU \u7248\u3001\u5B8C\u6574 / \u7CBE\u7B80\u7248\uFF09\uFF0C\u518D\u7528 asset \u53C2\u6570\u6307\u5B9A\u540E\u91CD\u65B0\u5B89\u88C5`);
1555
- }
1556
- return choice.asset;
1557
- })() : release.assets.find((a) => a.name === request.asset) ?? (() => {
1558
- throw new Error(`${release.tag} \u91CC\u6CA1\u6709\u6587\u4EF6 ${request.asset}`);
1559
- })();
1560
- const version = versionOfTag(release.tag);
1561
- if (have?.(version) === true)
1562
- return { version, asset: { name: asset.name, size: asset.size }, incremental: false };
1563
- const archive = join3(this.toolsDir, scriptId, ".downloads", asset.name);
1564
- ctl.phase("downloading", { message: asset.name, received: 0, total: asset.size });
1565
- await download({
1566
- url: asset.downloadUrl,
1567
- dest: archive,
1568
- mirror: settings.downloadMirror,
1569
- mirrorFallback: settings.mirrorFallback,
1570
- expectedSize: asset.size,
1571
- ...asset.digest === void 0 ? {} : { digest: asset.digest },
1572
- signal: ctl.signal,
1573
- onProgress: (received, total) => ctl.phase("downloading", { message: asset.name, received, ...total === void 0 ? {} : { total } }),
1574
- ...this.#options.fetch === void 0 ? {} : { fetch: this.#options.fetch }
1575
- });
1576
- return { version, archive, asset: { name: asset.name, size: asset.size }, incremental: false };
1577
- }
1578
- /**
1579
- * A commit's source as the "release": for repositories that publish none
1580
- * (scripts run from source, e.g. Python projects) or a branch asked for.
1581
- * Versions are the commit's date and id (`2026.10.31-1a2b3c4`), so a newer
1582
- * commit counts as newer; a tag keeps its own version.
1583
- */
1584
- async #fromSource(scriptId, repo, ref, ctl, have) {
1585
- const github = this.#github();
1586
- const branch = ref.tag !== void 0 ? void 0 : ref.branch ?? (await github.repoInfo(repo, ctl.signal)).defaultBranch;
1587
- const name = ref.tag ?? branch;
1588
- ctl.phase("resolving", { message: ref.branch === void 0 && ref.tag === void 0 ? `${repo} \u6CA1\u6709\u53D1\u5E03\u7248\u672C\uFF1A\u7528 ${name} \u5206\u652F\u7684\u6E90\u7801` : `\u8BFB\u53D6 ${repo} \u7684 ${name}` });
1589
- const head = await github.commit(repo, name, ctl.signal);
1590
- const version = ref.tag !== void 0 ? versionOfTag(ref.tag) : sourceVersion(head.date, head.sha);
1591
- const file = `${repo.split("/")[1]}-${head.sha.slice(0, 7)}.zip`;
1592
- if (have?.(version) === true)
1593
- return { version, asset: { name: file, size: 0 }, incremental: false, ...branch === void 0 ? {} : { branch } };
1594
- const settings = this.#state.settings;
1595
- const archive = join3(this.toolsDir, scriptId, ".downloads", file);
1596
- ctl.phase("downloading", { message: `${file}\uFF08${name} \u7684\u6E90\u7801\uFF09`, received: 0 });
1597
- await download({
1598
- url: github.sourceZipUrl(repo, head.sha),
1599
- dest: archive,
1600
- mirror: settings.downloadMirror,
1601
- mirrorFallback: settings.mirrorFallback,
1602
- signal: ctl.signal,
1603
- onProgress: (received, total) => ctl.phase("downloading", { message: file, received, ...total === void 0 ? {} : { total } }),
1604
- ...this.#options.fetch === void 0 ? {} : { fetch: this.#options.fetch }
1605
- });
1606
- const size = await stat(archive).then((s) => s.size, () => 0);
1607
- return { version, archive, asset: { name: file, size }, incremental: false, ...branch === void 0 ? {} : { branch } };
1608
- }
1609
- /** What a repository is, for deciding whether to trust one that no pack describes. */
1610
- async repoFacts(repo, signal) {
1611
- try {
1612
- const info = await this.#github().repoInfo(repo, signal);
1613
- const pushed = info.pushedAt === void 0 ? void 0 : new Date(info.pushedAt).toLocaleDateString("zh-CN");
1614
- return [
1615
- `${info.stars} \u661F`,
1616
- ...pushed === void 0 ? [] : [`\u6700\u8FD1\u66F4\u65B0 ${pushed}`],
1617
- ...info.fork ? ["\u662F\u522B\u4EBA\u9879\u76EE\u7684\u5206\u652F\uFF08fork\uFF09"] : [],
1618
- ...info.archived ? ["\u5DF2\u5F52\u6863\u3001\u4E0D\u518D\u7EF4\u62A4"] : [],
1619
- ...info.description === void 0 ? [] : [`\u7B80\u4ECB\uFF1A${info.description}`]
1620
- ].join("\uFF0C");
1621
- } catch {
1622
- return "\u8BFB\u4E0D\u5230\u4ED3\u5E93\u4FE1\u606F";
1623
- }
1624
- }
1625
- /**
1626
- * With the user's CDK: the latest release from Mirror酱, as an incremental
1627
- * package over `from` (the version there now) when it has one.
1628
- * @returns undefined to use GitHub instead (no CDK, a CDK problem, no
1629
- * download link — said in the job's message); with `required` (no GitHub
1630
- * channel) those are errors instead.
1631
- */
1632
- async #fromMirror(scriptId, resource, from, ctl, required, have) {
1633
- const cdk = await this.#cdk(scriptId);
1634
- if (cdk === void 0) {
1635
- if (required)
1636
- throw new Error(`${resource.rid} \u53EA\u80FD\u4ECE Mirror\u9171 \u4E0B\u8F7D\uFF1A\u8BF7\u5148\u5728\u300C\u8BBE\u7F6E \u2192 \u811A\u672C\u5B89\u88C5\u300D\u586B\u5199 Mirror\u9171 CDK\uFF0C\u6216\u5728\u811A\u672C\u81EA\u5DF1\u7684\u8BBE\u7F6E\u91CC\u586B\u597D`);
1637
- return void 0;
1638
- }
1639
- const options = this.#mirrorOptions(cdk, ctl.signal);
1640
- let latest;
1641
- try {
1642
- ctl.phase("resolving", { message: `\u4ECE Mirror\u9171 \u67E5\u8BE2 ${resource.rid} \u7684\u6700\u65B0\u7248\u672C` });
1643
- latest = await mirrorLatest(resource, options);
1644
- if (from !== void 0 && compareVersions(versionOfTag(latest.version), from) > 0) {
1645
- const current = latest.version.startsWith("v") ? `v${from}` : from;
1646
- const incremental2 = await mirrorLatest(resource, { ...options, currentVersion: current }).catch(() => void 0);
1647
- if (incremental2?.url !== void 0 && incremental2.version === latest.version)
1648
- latest = incremental2;
1649
- }
1650
- } catch (error) {
1651
- if (ctl.signal.aborted || required)
1652
- throw error;
1653
- this.#options.log.warn(`${scriptId}: Mirror\u9171: ${errorText(error)}`);
1654
- ctl.phase("resolving", { message: `${errorText(error)}\uFF1B\u6539\u4ECE GitHub \u4E0B\u8F7D` });
1655
- return void 0;
1656
- }
1657
- const version = versionOfTag(latest.version);
1658
- const incremental = latest.updateType === "incremental" && from !== void 0;
1659
- const name = `Mirror\u9171 ${incremental ? "\u589E\u91CF\u5305" : "\u5B8C\u6574\u5305"} ${latest.version}`;
1660
- if (have?.(version) === true)
1661
- return { version, asset: { name, size: latest.size ?? 0 }, incremental: false };
1662
- if (latest.url === void 0) {
1663
- if (required)
1664
- throw new Error(`Mirror\u9171 \u6CA1\u6709\u7ED9\u51FA ${resource.rid} \u7684\u4E0B\u8F7D\u5730\u5740`);
1665
- ctl.phase("resolving", { message: "Mirror\u9171 \u6CA1\u6709\u7ED9\u51FA\u4E0B\u8F7D\u5730\u5740\uFF1B\u6539\u4ECE GitHub \u4E0B\u8F7D" });
1666
- return void 0;
1667
- }
1668
- let archive = join3(this.toolsDir, scriptId, ".downloads", mirrorFileName(latest.url, resource.rid, latest.version));
1669
- ctl.phase("downloading", { message: `${name}\uFF08Mirror\u9171\uFF09`, received: 0, ...latest.size === void 0 ? {} : { total: latest.size } });
1670
- const downloaded = await download({
1671
- url: latest.url,
1672
- dest: archive,
1673
- ...latest.size === void 0 ? {} : { expectedSize: latest.size },
1674
- ...latest.sha256 === void 0 ? {} : { digest: `sha256:${latest.sha256}` },
1675
- signal: ctl.signal,
1676
- onProgress: (received, total) => ctl.phase("downloading", { message: `${name}\uFF08Mirror\u9171\uFF09`, received, ...total === void 0 ? {} : { total } }),
1677
- ...this.#options.fetch === void 0 ? {} : { fetch: this.#options.fetch }
1678
- });
1679
- archive = await realName(archive, downloaded.finalUrl);
1680
- return { version, archive, asset: { name, size: latest.size ?? 0 }, incremental };
1681
- }
1682
- /**
1683
- * The newest version where the update will come from: Mirror酱 with a CDK
1684
- * (or when it is the only channel; asking needs no CDK), else GitHub.
1685
- */
1686
- async #latestVersion(scriptId, channels, pack, signal, sourceBranch) {
1687
- if (sourceBranch !== void 0 && channels.github !== void 0) {
1688
- const head = await this.#github().commit(channels.github.repo, sourceBranch, signal);
1689
- return sourceVersion(head.date, head.sha);
1690
- }
1691
- const mirror = channels.mirror?.resource;
1692
- const cdk = mirror === void 0 ? void 0 : await this.#cdk(scriptId);
1693
- if (mirror !== void 0 && (cdk !== void 0 || channels.github === void 0)) {
1694
- try {
1695
- return versionOfTag((await mirrorLatest(mirror, this.#mirrorOptions(void 0, signal))).version);
1696
- } catch (error) {
1697
- if (signal?.aborted === true || channels.github === void 0)
1698
- throw error;
1699
- this.#options.log.warn(`${mirror.rid}: Mirror\u9171: ${errorText(error)}; asking GitHub`);
1700
- }
1701
- }
1702
- const latest = await this.#github().latest(channels.github.repo, { includePrereleases: this.#prereleases(pack), ...signal === void 0 ? {} : { signal } });
1703
- return versionOfTag(latest.tag);
1704
- }
1705
- /**
1706
- * The Mirror酱 CDK: the one filled in here (设置 → 脚本安装), else the one
1707
- * the script keeps in its own settings — so a script already set up for
1708
- * Mirror酱 updates from there without asking again.
1709
- */
1710
- async #cdk(scriptId) {
1711
- const own = await this.#options.credential(this.#state.settings.cdkRef);
1712
- if (own !== void 0 && own !== "")
1713
- return own;
1714
- const script = this.#state.scripts.find((s) => s.id === scriptId);
1715
- const pack = script === void 0 ? void 0 : this.#packOf(script);
1716
- const dir = script === void 0 ? void 0 : this.#info(script).dir;
1717
- return pack === void 0 || dir === void 0 ? void 0 : scriptCdk(pack, dir);
1718
- }
1719
- #mirrorOptions(cdk, signal) {
1720
- return {
1721
- ...cdk === void 0 ? {} : { cdk },
1722
- ...signal === void 0 ? {} : { signal },
1723
- ...this.#options.mirrorchyanBase === void 0 ? {} : { base: this.#options.mirrorchyanBase },
1724
- ...this.#options.fetch === void 0 ? {} : { fetch: this.#options.fetch }
1725
- };
1726
- }
1727
- /** Keep the newest `keepVersions` versions, always including the current one. */
1728
- async #prune(script) {
1729
- const keep = this.#state.settings.keepVersions;
1730
- const ordered = [...script.versions].sort((a, b) => b.installedAt - a.installedAt);
1731
- const kept = new Set(ordered.slice(0, keep).map((v) => v.version));
1732
- if (script.current !== void 0)
1733
- kept.add(script.current);
1734
- for (const version of ordered.filter((v) => !kept.has(v.version))) {
1735
- if (this.#ownsDir(version.dir))
1736
- await rm(version.dir, { recursive: true, force: true });
1737
- }
1738
- script.versions = script.versions.filter((v) => kept.has(v.version));
1739
- }
1740
- async rollback(id, version) {
1741
- const script = this.#script(id);
1742
- if (script.source.kind === "local")
1743
- throw new Error("\u672C\u5730\u5BFC\u5165\u7684\u811A\u672C\u53EA\u6709\u4E00\u4E2A\u76EE\u5F55\uFF0C\u65E0\u6CD5\u56DE\u6EDA\uFF1B\u5728\u8FD9\u91CC\u66F4\u65B0\u8FC7\u7684\u53EF\u4EE5\u300C\u64A4\u9500\u4E0A\u6B21\u66F4\u65B0\u300D");
1744
- if (this.#jobs.active(id) !== void 0)
1745
- throw new Error(`${id} \u6709\u4EFB\u52A1\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7A0D\u540E\u518D\u56DE\u6EDA`);
1746
- const ordered = [...script.versions].sort((a, b) => b.installedAt - a.installedAt);
1747
- const target = version === void 0 ? ordered.find((v) => v.version !== script.current) : ordered.find((v) => v.version === version);
1748
- if (target === void 0)
1749
- throw new Error(version === void 0 ? "\u6CA1\u6709\u53EF\u4EE5\u56DE\u6EDA\u5230\u7684\u65E7\u7248\u672C" : `\u6CA1\u6709\u5B89\u88C5\u7248\u672C ${version}`);
1750
- if (!await exists(target.dir))
1751
- throw new Error(`\u7248\u672C\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728\uFF1A${target.dir}`);
1752
- script.current = target.version;
1753
- await this.#save();
1754
- this.#options.onChanged(id);
1755
- return this.#info(script);
1756
- }
1757
- // ── local import ──────────────────────────────────────────────────────
1758
- /** Where library state lives; plugins keep their own files beside it. */
1759
- get dataDir() {
1760
- return this.#options.dataDir;
1761
- }
1762
- /** The user's pack directory: packs here override built-in ones by id. */
1763
- get userPackDir() {
1764
- return join3(this.#options.dataDir, "packs");
1765
- }
1766
- /** Describe a script with a (reloaded) pack, e.g. after the user accepted a draft. */
1767
- async attachPack(scriptId, packId) {
1768
- const script = this.#script(scriptId);
1769
- const pack = this.#packs.get(packId);
1770
- if (pack === void 0)
1771
- throw new Error(`\u6CA1\u6709\u811A\u672C\u5305 ${packId}`);
1772
- script.packId = packId;
1773
- const version = versionOf(script);
1774
- if (version === void 0)
1775
- delete script.packVersion;
1776
- else
1777
- script.packVersion = version;
1778
- if (pack.manifest.family !== void 0)
1779
- script.family = pack.manifest.family;
1780
- await this.#save();
1781
- this.#options.onChanged(scriptId);
1782
- if (pack.manifest.install.requires.length > 0)
1783
- await this.envCheck(scriptId);
1784
- return this.#info(script);
1785
- }
1786
- /** Register a folder in place; the folder a waiting setup program installed into (by id, or by its folder) finishes that install instead. */
1787
- async import(request) {
1788
- const path = resolve(request.path);
1789
- const setup = (request.id === void 0 ? void 0 : this.pendingSetup(request.id)) ?? this.#state.setups.find((s) => samePath(s.dir, path));
1790
- if (setup !== void 0)
1791
- return this.#finishSetup(setup, path, request);
1792
- return this.#importLocal(path, request);
1793
- }
1794
- async #importLocal(path, request) {
1795
- if (!await stat(path).then((s) => s.isDirectory(), () => false))
1796
- throw new Error(`\u4E0D\u662F\u4E00\u4E2A\u5B58\u5728\u7684\u76EE\u5F55\uFF1A${path}`);
1797
- if (this.#ownsDir(path, false))
1798
- throw new Error("\u8FD9\u4E2A\u76EE\u5F55\u5728\u5DE5\u5177\u76EE\u5F55\u91CC\uFF0C\u7531\u5B89\u88C5\u5668\u7BA1\u7406\uFF0C\u4E0D\u9700\u8981\u5BFC\u5165");
1799
- const same = this.#state.scripts.find((s) => s.source.kind === "local" && samePath(s.source.path, path));
1800
- if (same !== void 0)
1801
- return this.#info(same);
1802
- await this.reloadPacks();
1803
- let pack;
1804
- if (request.packId !== void 0) {
1805
- pack = this.#packs.get(request.packId);
1806
- if (pack === void 0)
1807
- throw new Error(`\u6CA1\u6709\u811A\u672C\u5305 ${request.packId}`);
1808
- } else {
1809
- for (const candidate of this.#packs.values()) {
1810
- const files = candidate.manifest.detect?.files;
1811
- if (files !== void 0 && await matchesDetect(path, files)) {
1812
- pack = candidate;
1813
- break;
1814
- }
1815
- }
1816
- }
1817
- const probe = await probeProject(path);
1818
- const known = pack === void 0 ? await knownByDir(path) : void 0;
1819
- const base = request.id ?? pack?.manifest.id ?? known?.id ?? slug(basename2(path));
1820
- const id = this.#freeId(base);
1821
- const script = {
1822
- id,
1823
- name: request.name ?? pack?.manifest.name ?? known?.name ?? basename2(path),
1824
- source: { kind: "local", path },
1825
- current: "local",
1826
- versions: [{ version: "local", dir: path, installedAt: this.#now() }],
1827
- probe,
1828
- addedAt: this.#now(),
1829
- ...pack === void 0 ? {} : { packId: pack.manifest.id },
1830
- ...known === void 0 ? {} : { known: known.id },
1831
- ...(pack?.manifest.family ?? known?.family ?? probe.family) === void 0 ? {} : { family: pack?.manifest.family ?? known?.family ?? probe.family }
1832
- };
1833
- const found = await this.#detectVersion(script);
1834
- if (found !== void 0)
1835
- script.localVersion = found;
1836
- this.#state.scripts.push(script);
1837
- await this.#save();
1838
- this.#options.onChanged(id);
1839
- if (pack !== void 0 && pack.manifest.install.requires.length > 0)
1840
- await this.envCheck(id);
1841
- return this.#info(script);
1842
- }
1843
- /** Forget a script; installed versions are deleted only with `deleteFiles`, imported directories never. */
1844
- async remove(id, deleteFiles = false) {
1845
- const script = this.#script(id);
1846
- if (this.#jobs.active(id) !== void 0)
1847
- throw new Error(`${id} \u6709\u4EFB\u52A1\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5148\u53D6\u6D88`);
1848
- for (const root of [this.toolsDir, ...this.formerToolsDirs]) {
1849
- if (deleteFiles && script.source.kind !== "local") {
1850
- const dir = join3(root, id);
1851
- if (this.#ownsDir(dir))
1852
- await rm(dir, { recursive: true, force: true });
1853
- }
1854
- if (script.source.kind === "local")
1855
- await rm(join3(root, id, ".local-backup"), { recursive: true, force: true });
1856
- }
1857
- for (const setup of this.#state.setups.filter((s) => s.scriptId === id))
1858
- await rm(setup.file, { force: true });
1859
- this.#state.setups = this.#state.setups.filter((s) => s.scriptId !== id);
1860
- this.#state.scripts = this.#state.scripts.filter((s) => s.id !== id);
1861
- await this.#save();
1862
- this.#options.onChanged(id);
1863
- }
1864
- // ── environment ───────────────────────────────────────────────────────
1865
- async envCheck(id) {
1866
- const { report } = await this.#check(this.#script(id));
1867
- return report;
1868
- }
1869
- /** What fixing `kind` would run, from a fresh check; undefined when it is already fine. */
1870
- async envFixPlan(id, kind) {
1871
- const { plans } = await this.#check(this.#script(id));
1872
- return plans.get(kind);
1873
- }
1874
- envFix(id, kind, plan) {
1875
- return this.#jobs.start("env-fix", id, async (ctl) => {
1876
- ctl.phase("running", { message: plan.description });
1877
- await applyFix(plan, {
1878
- sharedDir: this.sharedDir,
1879
- signal: ctl.signal,
1880
- download: async (url, dest, onProgress) => {
1881
- const github = /^https:\/\/(github\.com|objects\.githubusercontent\.com)\//.test(url);
1882
- await download({
1883
- url,
1884
- dest,
1885
- signal: ctl.signal,
1886
- onProgress,
1887
- ...github ? { mirror: this.#state.settings.downloadMirror, mirrorFallback: this.#state.settings.mirrorFallback } : {},
1888
- ...this.#options.fetch === void 0 ? {} : { fetch: this.#options.fetch }
1889
- });
1890
- },
1891
- onPhase: (phase, received, total) => ctl.phase(phase, {
1892
- message: plan.description,
1893
- ...received === void 0 ? {} : { received },
1894
- ...total === void 0 ? {} : { total }
1895
- }),
1896
- ...this.#options.runElevated === void 0 ? {} : { runElevated: this.#options.runElevated }
1897
- });
1898
- ctl.phase("checking", { message: "\u91CD\u65B0\u68C0\u67E5\u8FD0\u884C\u73AF\u5883" });
1899
- const report = await this.envCheck(id);
1900
- const item = report.items.find((i) => i.kind === kind);
1901
- if (item !== void 0 && item.status !== "ok")
1902
- throw new Error(`\u5904\u7406\u5B8C\u6210\uFF0C\u4F46 ${item.label} \u4ECD\u4E3A\u300C${item.status}\u300D${item.detail === void 0 ? "" : `\uFF1A${item.detail}`}`);
1903
- return void 0;
1904
- });
1905
- }
1906
- async #check(script) {
1907
- const pack = script.packId === void 0 ? void 0 : this.#packs.get(script.packId);
1908
- const result = await checkEnvironment(pack?.manifest.install.requires ?? [], { host: this.#options.envHost ?? systemHost, sharedDir: this.sharedDir, checkers: Object.fromEntries(this.#checkers) }, this.#now());
1909
- script.env = result.report;
1910
- await this.#save();
1911
- this.#options.onChanged(script.id);
1912
- return result;
1913
- }
1914
- // ── helpers ───────────────────────────────────────────────────────────
1915
- #github() {
1916
- const settings = this.#state.settings;
1917
- return new GitHubClient({
1918
- apiBase: settings.apiBase,
1919
- token: () => this.#options.credential(settings.tokenRef),
1920
- ...this.#options.fetch === void 0 ? {} : { fetch: this.#options.fetch }
1921
- });
1922
- }
1923
- #prereleases(pack) {
1924
- return this.#state.settings.includePrereleases || pack?.manifest.source.release?.channel === "prerelease";
1925
- }
1926
- #script(id) {
1927
- const script = this.#state.scripts.find((s) => s.id === id);
1928
- if (script === void 0)
1929
- throw new Error(`\u811A\u672C\u5E93\u91CC\u6CA1\u6709 ${id}`);
1930
- return script;
1931
- }
1932
- #info(script) {
1933
- const current = currentVersion(script);
1934
- const job = this.#jobs.active(script.id);
1935
- const channels = this.#channels(script);
1936
- const last = script.backups?.at(-1);
1937
- return {
1938
- id: script.id,
1939
- name: script.name,
1940
- source: script.source,
1941
- versions: [...script.versions].sort((a, b) => b.installedAt - a.installedAt).map((v) => ({ ...v, current: v.version === script.current })),
1942
- addedAt: script.addedAt,
1943
- ...script.packId === void 0 ? {} : { packId: script.packId },
1944
- channels: {
1945
- ...channels.github === void 0 ? {} : { github: channels.github },
1946
- ...channels.mirror === void 0 ? {} : { mirrorchyan: { rid: channels.mirror.resource.rid, from: channels.mirror.from } }
1947
- },
1948
- ...script.known === void 0 ? {} : { known: script.known },
1949
- ...script.localVersion === void 0 ? {} : { localVersion: script.localVersion },
1950
- ...last === void 0 ? {} : { undo: { to: last.to, at: last.at, ...last.from === void 0 ? {} : { from: last.from } } },
1951
- ...script.family === void 0 ? {} : { family: script.family },
1952
- ...current === void 0 ? {} : { current: current.version, dir: current.dir },
1953
- ...script.env === void 0 ? {} : { env: script.env },
1954
- ...script.probe === void 0 ? {} : { probe: script.probe },
1955
- ...script.update === void 0 ? {} : { update: script.update },
1956
- ...job === void 0 ? {} : { jobId: job.id },
1957
- ...script.summary === void 0 ? {} : { summary: script.summary },
1958
- ...this.#packReview(script) === void 0 ? {} : { packReview: this.#packReview(script) },
1959
- ...script.optimize === void 0 ? {} : { optimize: { runs: script.optimize.runs, ...script.optimize.at === void 0 ? {} : { at: script.optimize.at }, ...optimizeDue(script) === void 0 ? {} : { due: optimizeDue(script) } } }
1960
- };
1961
- }
1962
- /** One of its tasks went through: one more run to learn from; enough of them, or the first on a new version, offers 优化脚本. */
1963
- async ranClean(id, now = Date.now()) {
1964
- const script = this.#state.scripts.find((s) => s.id === id);
1965
- if (script === void 0)
1966
- return;
1967
- const version = versionOf(script);
1968
- const before = script.optimize ?? { runs: 0, since: now, ...version === void 0 ? {} : { version } };
1969
- script.optimize = { ...before, runs: before.runs + 1 };
1970
- const due = optimizeDue(script);
1971
- const key = due === void 0 || due === "updated" && this.#packReview(script) !== void 0 ? void 0 : `${due}:${script.optimize.since}:${version ?? ""}`;
1972
- const ask = key !== void 0 && script.optimize.asked !== key;
1973
- if (ask)
1974
- script.optimize.asked = key;
1975
- await this.#save();
1976
- this.#options.onChanged(id);
1977
- if (ask)
1978
- this.#options.onOptimize?.(this.#info(script));
1979
- }
1980
- /** 优化脚本 was started (`run`) or this offer turned down (`keep`): counting starts again at the version it is at. */
1981
- async optimizeDone(id, decision, now = Date.now()) {
1982
- const script = this.#script(id);
1983
- const version = versionOf(script);
1984
- const at = decision === "run" ? now : script.optimize?.at;
1985
- script.optimize = { runs: 0, since: now, ...version === void 0 ? {} : { version }, ...at === void 0 ? {} : { at } };
1986
- await this.#save();
1987
- this.#options.onChanged(id);
1988
- return this.#info(script);
1989
- }
1990
- /**
1991
- * The script is at a newer version than its pack was written for. Built-in
1992
- * packs are kept up to date with the app, so only the user's (and the
1993
- * agent's) packs are asked about.
1994
- */
1995
- #packReview(script) {
1996
- const pack = script.packId === void 0 ? void 0 : this.#packs.get(script.packId);
1997
- const now = versionOf(script);
1998
- if (pack === void 0 || pack.builtin || now === void 0 || script.packVersion === void 0)
1999
- return void 0;
2000
- if (compareVersions(now, script.packVersion) <= 0)
2001
- return void 0;
2002
- return { from: script.packVersion, to: now };
2003
- }
2004
- /** The pack was checked against the version the script is at now (and needs no change, or was just changed). */
2005
- async packReviewed(id) {
2006
- const script = this.#script(id);
2007
- const version = versionOf(script);
2008
- if (version !== void 0)
2009
- script.packVersion = version;
2010
- await this.#save();
2011
- this.#options.onChanged(id);
2012
- return this.#info(script);
2013
- }
2014
- /**
2015
- * What changed between two versions, for checking a pack after an update:
2016
- * the release notes on GitHub (each release after `from` up to `to`),
2017
- * Mirror酱's note for its latest version, and the changelog files in the
2018
- * script's folder. `from` defaults to the version its pack was written for,
2019
- * `to` to the version it is at.
2020
- */
2021
- async changelog(id, options = {}) {
2022
- const script = this.#script(id);
2023
- const from = options.from ?? script.packVersion;
2024
- const to = options.to ?? versionOf(script);
2025
- const channels = this.#channels(script);
2026
- const problems = [];
2027
- const releases = [];
2028
- let budget = CHANGELOG_BUDGET;
2029
- if (channels.github !== void 0) {
2030
- try {
2031
- for (const release of await this.#github().releases(channels.github.repo, 40, options.signal)) {
2032
- const version = versionOfTag(release.tag);
2033
- if (from !== void 0 && compareVersions(version, from) <= 0)
2034
- continue;
2035
- if (to !== void 0 && compareVersions(version, to) > 0)
2036
- continue;
2037
- const notes = (release.notes ?? "\uFF08\u8FD9\u4E2A\u7248\u672C\u6CA1\u6709\u5199\u53D1\u5E03\u8BF4\u660E\uFF09").slice(0, Math.max(0, Math.min(RELEASE_NOTES_MAX, budget)));
2038
- budget -= notes.length;
2039
- releases.push({ version, name: release.name, notes, ...release.publishedAt === void 0 ? {} : { publishedAt: release.publishedAt }, ...release.url === void 0 ? {} : { url: release.url } });
2040
- if (budget <= 0 || releases.length >= 20)
2041
- break;
2042
- }
2043
- } catch (error) {
2044
- problems.push(`GitHub\uFF08${channels.github.repo}\uFF09\uFF1A${errorText(error)}`);
2045
- }
2046
- }
2047
- let mirror;
2048
- if (channels.mirror !== void 0 && releases.length === 0) {
2049
- try {
2050
- const latest = await mirrorLatest(channels.mirror.resource, this.#mirrorOptions(void 0, options.signal ?? void 0));
2051
- if (latest.releaseNote !== void 0)
2052
- mirror = { version: versionOfTag(latest.version), notes: latest.releaseNote.slice(0, RELEASE_NOTES_MAX) };
2053
- } catch (error) {
2054
- problems.push(`Mirror\u9171\uFF08${channels.mirror.resource.rid}\uFF09\uFF1A${errorText(error)}`);
2055
- }
2056
- }
2057
- const dir = this.#info(script).dir;
2058
- const files = [];
2059
- for (const rel of dir === void 0 ? [] : await changelogFiles(dir)) {
2060
- const text = await readFile3(join3(dir, rel), "utf8").catch(() => void 0);
2061
- if (text !== void 0)
2062
- files.push({ file: rel, text: text.slice(0, CHANGELOG_FILE_MAX), truncated: text.length > CHANGELOG_FILE_MAX });
2063
- }
2064
- return {
2065
- ...from === void 0 ? {} : { from },
2066
- ...to === void 0 ? {} : { to },
2067
- releases,
2068
- files,
2069
- ...mirror === void 0 ? {} : { mirror },
2070
- ...problems.length === 0 ? {} : { problems },
2071
- ...releases.length === 0 && mirror === void 0 && files.length === 0 ? { note: "\u6CA1\u6709\u627E\u5230\u66F4\u65B0\u65E5\u5FD7\uFF1A\u53BB\u9879\u76EE\u4E3B\u9875\u6216\u4ED3\u5E93\u7684 Releases\u3001CHANGELOG \u770B\u770B\uFF0C\u8FD8\u662F\u6CA1\u6709\u518D\u76F4\u63A5\u6BD4\u8F83\u65B0\u65E7\u7248\u672C\u7684\u6587\u4EF6" } : {}
2072
- };
2073
- }
2074
- /**
2075
- * What the agent gets to sum a script up: where it came from, its pack, the
2076
- * files at the top of its folder and its README (the start of it).
2077
- */
2078
- async summaryMaterial(id) {
2079
- const script = this.#state.scripts.find((s) => s.id === id);
2080
- if (script === void 0)
2081
- throw new Error(`\u811A\u672C\u5E93\u91CC\u6CA1\u6709 ${id}`);
2082
- const info = this.#info(script);
2083
- const pack = this.packOf(id);
2084
- const known = knownById(script.known);
2085
- const lines = [
2086
- `\u540D\u5B57\uFF1A${script.name}\uFF08id ${script.id}\uFF09`,
2087
- `\u6765\u6E90\uFF1A${script.source.kind === "github" ? `GitHub ${script.source.repo}` : script.source.kind === "mirrorchyan" ? `Mirror\u9171 ${script.source.rid}` : `\u672C\u5730\u5BFC\u5165 ${script.source.path}`}`,
2088
- ...info.current === void 0 ? [] : [`\u7248\u672C\uFF1A${info.current}`],
2089
- ...known === void 0 ? [] : [`\u8BA4\u51FA\u6765\u662F\uFF1A${known.name}${known.repo === void 0 ? "" : `\uFF08${known.repo}\uFF09`}`],
2090
- ...info.channels.github === void 0 ? [] : [`GitHub \u66F4\u65B0\u6E20\u9053\uFF1A${info.channels.github.repo}`]
2091
- ];
2092
- if (pack !== void 0) {
2093
- const m = pack.manifest;
2094
- lines.push(`\u811A\u672C\u5305\uFF1A${m.name}${m.description === void 0 ? "" : `\u2014\u2014${m.description}`}`);
2095
- if (m.game?.name !== void 0)
2096
- lines.push(`\u73A9\u7684\u6E38\u620F\uFF1A${m.game.name}`);
2097
- if (m.tasks.length > 0)
2098
- lines.push(`\u811A\u672C\u5305\u91CC\u7684\u4EFB\u52A1\uFF1A${m.tasks.map((t) => t.title).join("\u3001")}`);
2099
- }
2100
- if (info.dir !== void 0) {
2101
- const entries = await readdir2(info.dir, { withFileTypes: true }).catch(() => []);
2102
- const names = entries.map((e) => e.isDirectory() ? `${e.name}/` : e.name).sort();
2103
- lines.push(`\u6587\u4EF6\u5939\u91CC\uFF08${names.length} \u9879\uFF09\uFF1A${names.slice(0, 60).join(" ")}${names.length > 60 ? " \u2026" : ""}`);
2104
- const readme = entries.filter((e) => e.isFile() && /^read[ _-]?me.*\.(md|txt)$|^read[ _-]?me$/i.test(e.name)).sort((a, b) => Number(/zh|cn|中文/i.test(b.name)) - Number(/zh|cn|中文/i.test(a.name)) || a.name.length - b.name.length)[0];
2105
- if (readme !== void 0) {
2106
- const text = (await readFile3(join3(info.dir, readme.name), "utf8").catch(() => "")).replace(/<!--[\s\S]*?-->/g, "").replace(/\n{3,}/g, "\n\n").trim();
2107
- if (text !== "")
2108
- lines.push("", `${readme.name}\uFF08\u5F00\u5934\u90E8\u5206\uFF09\uFF1A`, text.slice(0, 6e3));
2109
- }
2110
- }
2111
- return lines.join("\n");
2112
- }
2113
- /** Keep the agent's summary of a script (or how getting it went). */
2114
- async setSummary(id, summary) {
2115
- const script = this.#state.scripts.find((s) => s.id === id);
2116
- if (script === void 0)
2117
- return;
2118
- script.summary = summary;
2119
- await this.#save();
2120
- this.#options.onChanged(id);
2121
- }
2122
- #freeId(base) {
2123
- const taken = new Set(this.#state.scripts.map((s) => s.id));
2124
- if (!taken.has(base))
2125
- return base;
2126
- for (let n = 2; ; n++)
2127
- if (!taken.has(`${base}-${n}`))
2128
- return `${base}-${n}`;
2129
- }
2130
- /** Inside the tools directory (or a former one, unless `former` is false): installed by the library, its to delete. */
2131
- #ownsDir(dir, former = true) {
2132
- return [this.toolsDir, ...former ? this.formerToolsDirs : []].some((root) => {
2133
- const rel = relative(root, resolve(dir));
2134
- return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
2135
- });
2136
- }
2137
- /** Write the state; a script that moved past its pack's version is asked about once (onPackReview). */
2138
- async #save() {
2139
- const ask = [];
2140
- for (const script of this.#state.scripts) {
2141
- const version = versionOf(script);
2142
- if (script.packId !== void 0 && script.packVersion === void 0 && version !== void 0)
2143
- script.packVersion = version;
2144
- const review = this.#packReview(script);
2145
- if (review !== void 0 && script.packReviewAsked !== review.to) {
2146
- script.packReviewAsked = review.to;
2147
- ask.push(script);
2148
- }
2149
- }
2150
- await this.#store.save(this.#state);
2151
- for (const script of ask)
2152
- this.#options.onPackReview?.(this.#info(script));
2153
- }
2154
- };
2155
- var CHANGELOG_BUDGET = 3e4;
2156
- var RELEASE_NOTES_MAX = 4e3;
2157
- var CHANGELOG_FILE_MAX = 8e3;
2158
- var CHANGELOG_NAME = /^(changelog|changes|history|release[-_ ]?notes?|更新日志|更新说明|版本说明)[^/]*.(md|txt|markdown)$/i;
2159
- async function changelogFiles(dir) {
2160
- const out = [];
2161
- for (const sub of ["", "docs", "doc", "\u6587\u6863"]) {
2162
- for (const name of await readdir2(join3(dir, sub)).catch(() => [])) {
2163
- if (CHANGELOG_NAME.test(name))
2164
- out.push(sub === "" ? name : `${sub}/${name}`);
2165
- }
2166
- }
2167
- return out.slice(0, 4);
2168
- }
2169
- function versionOf(script) {
2170
- return script.source.kind === "local" ? script.localVersion?.version : script.current;
2171
- }
2172
- var OPTIMIZE_AFTER_RUNS = 5;
2173
- function optimizeDue(script) {
2174
- const o = script.optimize;
2175
- if (o === void 0)
2176
- return void 0;
2177
- const version = versionOf(script);
2178
- if (o.version !== void 0 && version !== void 0 && version !== o.version && o.runs > 0)
2179
- return "updated";
2180
- return o.runs >= OPTIMIZE_AFTER_RUNS ? "runs" : void 0;
2181
- }
2182
- function resourceOf(r) {
2183
- return { rid: r.rid, platform: r.platform, ...r.os === void 0 ? {} : { os: r.os }, ...r.arch === void 0 ? {} : { arch: r.arch } };
2184
- }
2185
- function squash(text) {
2186
- return text.toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, "");
2187
- }
2188
- function sameSource(a, b) {
2189
- if (a.kind === "github" && b.kind === "github")
2190
- return a.repo.toLowerCase() === b.repo.toLowerCase();
2191
- if (a.kind === "mirrorchyan" && b.kind === "mirrorchyan")
2192
- return a.rid.toLowerCase() === b.rid.toLowerCase();
2193
- return false;
2194
- }
2195
- function describeSource(source) {
2196
- return source.kind === "github" ? source.repo : source.kind === "mirrorchyan" ? `Mirror\u9171 ${source.rid}` : source.path;
2197
- }
2198
- var AssetChoiceError = class extends Error {
2199
- name = "AssetChoiceError";
2200
- };
2201
- function sourceVersion(date, sha) {
2202
- const d = new Date(date);
2203
- const day = Number.isNaN(d.getTime()) ? "0.0.0" : `${d.getUTCFullYear()}.${d.getUTCMonth() + 1}.${d.getUTCDate()}`;
2204
- return `${day}-${sha.slice(0, 7)}`;
2205
- }
2206
- async function patchPrefix(patch, baseDir, root) {
2207
- if (root !== void 0 && await exists(join3(patch, root)))
2208
- return root.replace(/\\/g, "/");
2209
- const entries = (await readdir2(patch, { withFileTypes: true })).filter((e) => e.name !== "changes.json");
2210
- return entries.length === 1 && entries[0].isDirectory() && !await exists(join3(baseDir, entries[0].name)) ? entries[0].name : void 0;
2211
- }
2212
- async function listFiles(dir, sub = "") {
2213
- const files = [];
2214
- for (const entry of await readdir2(join3(dir, sub), { withFileTypes: true })) {
2215
- const rel = sub === "" ? entry.name : `${sub}/${entry.name}`;
2216
- if (entry.isDirectory())
2217
- files.push(...await listFiles(dir, rel));
2218
- else if (entry.isFile())
2219
- files.push(rel);
2220
- }
2221
- return files;
2222
- }
2223
- var USER_DATA = /* @__PURE__ */ new Set(["config", "configs", "user", "userdata", "settings", "cache", "log", "logs", "debug"]);
2224
- async function keptFiles(pack, dir) {
2225
- const kept = /* @__PURE__ */ new Set();
2226
- for (const entry of await readdir2(dir, { withFileTypes: true }).catch(() => [])) {
2227
- if (entry.isDirectory() && USER_DATA.has(entry.name.toLowerCase())) {
2228
- for (const rel of await listFiles(dir, entry.name).catch(() => []))
2229
- kept.add(rel.toLowerCase());
2230
- }
2231
- }
2232
- for (const file of pack?.manifest.config.files ?? []) {
2233
- if (file.keepOnUpdate === false)
2234
- continue;
2235
- const parts = file.path.split(/[\\/]/);
2236
- const last = parts.pop();
2237
- const sub = parts.join("/");
2238
- const names = last.includes("*") || last.includes("?") ? (await readdir2(join3(dir, sub)).catch(() => [])).filter((n) => globToRegExp(last).test(n)) : [last];
2239
- for (const name of names) {
2240
- if (await stat(join3(dir, sub, name)).then((s) => s.isFile(), () => false))
2241
- kept.add((sub === "" ? name : `${sub}/${name}`).toLowerCase());
2242
- }
2243
- }
2244
- return kept;
2245
- }
2246
- async function saveCopy(path, dest) {
2247
- await mkdir2(dirname2(dest), { recursive: true });
2248
- await cp(path, dest, { recursive: true, force: true });
2249
- }
2250
- async function putBack(target, backup) {
2251
- for (const rel of backup.added)
2252
- await rm(join3(target, ...rel.split("/")), { force: true });
2253
- for (const rel of backup.saved) {
2254
- const saved = join3(backup.dir, "files", ...rel.split("/"));
2255
- if (await exists(saved))
2256
- await saveCopy(saved, join3(target, ...rel.split("/")));
2257
- }
2258
- }
2259
- function newName(scriptId, source, pack) {
2260
- const known = source.kind === "github" ? knownByRepo(source.repo) : source.kind === "mirrorchyan" ? knownByMirror(source.rid) : void 0;
2261
- return pack?.manifest.name ?? known?.name ?? (source.kind === "github" ? source.repo.split("/")[1] : void 0) ?? (source.kind === "mirrorchyan" ? source.rid : scriptId);
2262
- }
2263
- async function realName(file, finalUrl) {
2264
- let name;
2265
- try {
2266
- const served = decodeURIComponent(basename2(new URL(finalUrl).pathname));
2267
- if (archiveKind(served) !== void 0 && !/[\\/:*?"<>|]/.test(served))
2268
- name = served;
2269
- } catch {
2270
- }
2271
- if (name === void 0) {
2272
- const found = await contentKind(file);
2273
- if (found === void 0 || archiveKind(basename2(file)) === found.kind)
2274
- return file;
2275
- name = basename2(file).replace(/\.(zip|7z|tar(\.\w+)?|exe|msi)$/i, "") + found.ext;
2276
- }
2277
- if (name === basename2(file))
2278
- return file;
2279
- const renamed = join3(dirname2(file), name);
2280
- await rm(renamed, { force: true });
2281
- await rename2(file, renamed);
2282
- return renamed;
2283
- }
2284
- function mirrorFileName(url, rid, version) {
2285
- try {
2286
- const name = basename2(new URL(url).pathname);
2287
- if (archiveKind(name) !== void 0)
2288
- return name;
2289
- } catch {
2290
- }
2291
- return `mirrorchyan-${rid}-${version}.zip`.replace(/[\\/:*?"<>|]/g, "_");
2292
- }
2293
- function currentVersion(script) {
2294
- return script.versions.find((v) => v.version === script.current);
2295
- }
2296
- function globsOf(pack) {
2297
- const asset = pack?.manifest.source.release?.asset;
2298
- return asset === void 0 ? {} : { globs: Array.isArray(asset) ? asset : [asset] };
2299
- }
2300
- function dirName(version) {
2301
- return version.replace(/[\\/:*?"<>|]/g, "_");
2302
- }
2303
- function slug(name) {
2304
- const s = name.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[-._]+|[-._]+$/g, "").slice(0, 64);
2305
- return s === "" ? "script" : s;
2306
- }
2307
- function samePath(a, b) {
2308
- const norm = (p) => resolve(p).replace(/[\\/]+$/, "");
2309
- return process.platform === "win32" ? norm(a).toLowerCase() === norm(b).toLowerCase() : norm(a) === norm(b);
2310
- }
2311
- function exists(path) {
2312
- return stat(path).then(() => true, () => false);
2313
- }
2314
- async function carryConfig(pack, fromDir, toDir) {
2315
- const copied = [];
2316
- for (const file of pack.manifest.config.files) {
2317
- if (file.keepOnUpdate === false)
2318
- continue;
2319
- const parts = file.path.split(/[\\/]/);
2320
- const last = parts.pop();
2321
- const sub = parts.join("/");
2322
- const names = last.includes("*") || last.includes("?") ? (await readdir2(join3(fromDir, sub)).catch(() => [])).filter((n) => globToRegExp(last).test(n)) : [last];
2323
- for (const name of names) {
2324
- const source = join3(fromDir, sub, name);
2325
- if (!await stat(source).then((s) => s.isFile(), () => false))
2326
- continue;
2327
- const target = join3(toDir, sub, name);
2328
- await mkdir2(dirname2(target), { recursive: true });
2329
- await copyFile(source, target);
2330
- copied.push(sub === "" ? name : `${sub}/${name}`);
2331
- }
2332
- }
2333
- return copied;
2334
- }
2335
- var CDK_ENTRY = /["']?[\w.-]*cdk["']?\s*[:=]\s*["']?([A-Za-z0-9_-]{8,64})["']?/i;
2336
- async function scriptCdk(pack, dir) {
2337
- for (const file of pack.manifest.config.files) {
2338
- const parts = file.path.split(/[\\/]/);
2339
- const last = parts.pop();
2340
- const sub = parts.join("/");
2341
- const names = last.includes("*") || last.includes("?") ? (await readdir2(join3(dir, sub)).catch(() => [])).filter((n) => globToRegExp(last).test(n)) : [last];
2342
- for (const name of names) {
2343
- const text = await readFile3(join3(dir, sub, name), "utf8").catch(() => "");
2344
- const found = CDK_ENTRY.exec(text)?.[1];
2345
- if (found !== void 0)
2346
- return found;
2347
- }
2348
- }
2349
- return void 0;
2350
- }
2351
- function errorText(error) {
2352
- return error instanceof Error ? error.message : String(error);
2353
- }
2354
-
2355
- // packages/script-registry/lib/pack-review.js
2356
- var PACK_REVIEW_SCOPE = "pack-review";
2357
- var noticeIdOf = (scriptId, version) => `${PACK_REVIEW_SCOPE}:${scriptId}:${version}`;
2358
- var REVIEW_TIMEOUT_MS = 30 * 6e4;
2359
- function packReview(ctx, library, log) {
2360
- const decide = async (id, decision) => {
2361
- const lib = library();
2362
- const script = lib.get(id);
2363
- const close = (done) => {
2364
- if (script.packReview === void 0)
2365
- return;
2366
- void ctx.get("adgNotify")?.update(noticeIdOf(id, script.packReview.to), { done }).catch(() => {
2367
- });
2368
- };
2369
- if (decision === "keep") {
2370
- close("\u811A\u672C\u5305\u4FDD\u6301\u4E0D\u53D8");
2371
- await lib.packReviewed(id);
2372
- return {};
2373
- }
2374
- const sessions = ctx.get("sessionController");
2375
- if (sessions === void 0)
2376
- throw new Error("agent \u73B0\u5728\u4E0D\u53EF\u7528\uFF08\u4F1A\u8BDD\u670D\u52A1\u6CA1\u6709\u52A0\u8F7D\uFF09");
2377
- const gateway = ctx.get("adgGateway");
2378
- const conversations = sessionConversations(sessions, () => gateway?.workspaceDir(), (sessionId2, focus) => gateway?.skillScope.setFocus(sessionId2, focus) ?? Promise.resolve(), () => gateway);
2379
- const sessionId = await conversations.home(SCRIPT_ROLE.id, { focus: { scripts: [id] } });
2380
- const from = script.packReview?.from ?? "\u65E7\u7248\u672C";
2381
- const to = script.packReview?.to ?? script.localVersion?.version ?? script.current ?? "\u65B0\u7248\u672C";
2382
- const prompt = [
2383
- `\u300C${script.name}\u300D\uFF08\u811A\u672C id ${id}\uFF09\u4ECE ${from} \u66F4\u65B0\u5230\u4E86 ${to}\uFF0C\u5B83\u7684\u811A\u672C\u5305 ${script.packId ?? ""} \u662F\u6309 ${from} \u5199\u7684\u3002`,
2384
- "\u8BF7\u6309\u6280\u80FD script-analysis \u91CC\u300C\u811A\u672C\u66F4\u65B0\u540E\u68C0\u67E5\u811A\u672C\u5305\u300D\u7684\u6B65\u9AA4\u505A\uFF1A",
2385
- `1. \u5148\u7528 script_changelog\uFF08id=${id}\uFF09\u8BFB\u8FD9\u51E0\u4E2A\u7248\u672C\u7684\u66F4\u65B0\u65E5\u5FD7\uFF0C\u6311\u51FA\u53EF\u80FD\u5F71\u54CD\u811A\u672C\u5305\u7684\u6539\u52A8\uFF08\u4EFB\u52A1\u3001\u53C2\u6570\u3001\u914D\u7F6E\u6587\u4EF6\u548C\u952E\u3001\u542F\u52A8\u65B9\u5F0F\u3001\u65E5\u5FD7\u91CC\u7684\u5B8C\u6210\u548C\u51FA\u9519\u6587\u5B57\u3001\u8FD0\u884C\u73AF\u5883\uFF09\uFF1B`,
2386
- "2. \u53EA\u9488\u5BF9\u8FD9\u4E9B\u6539\u52A8\u6838\u5BF9\u65B0\u7248\u672C\u7684\u6587\u4EF6\uFF0C\u66F4\u65B0\u65E5\u5FD7\u6CA1\u5199\u6E05\u695A\u7684\u518D\u770B\u4EE3\u7801\uFF1B",
2387
- "3. \u8981\u6539\u5C31\u7528\u539F\u6765\u7684\u811A\u672C\u5305 id \u8C03\u7528 pack_propose \u4FDD\u5B58\uFF08\u76F4\u63A5\u751F\u6548\uFF1Bsummary \u5199\u660E\u4F9D\u636E\u66F4\u65B0\u65E5\u5FD7\u6539\u4E86\u4EC0\u4E48\uFF09\uFF1B\u4E0D\u7528\u6539\u5C31\u8C03\u7528 pack_reviewed \u8BF4\u660E\u7406\u7531\uFF1B",
2388
- "4. \u6700\u540E\u7528\u4E24\u4E09\u53E5\u8BDD\u544A\u8BC9\u7528\u6237\u7ED3\u8BBA\u3002"
2389
- ].join("\n");
2390
- void conversations.ask(sessionId, taskMessage("\u4F60", `\u68C0\u67E5\u811A\u672C\u5305\uFF1A${script.name}`, prompt), AbortSignal.timeout(REVIEW_TIMEOUT_MS)).catch((error) => log.warn(`pack review for ${id}: ${error instanceof Error ? error.message : String(error)}`));
2391
- close("\u5DF2\u4EA4\u7ED9\u300C\u811A\u672C\u300D\u68C0\u67E5\uFF0C\u8981\u6539\u7684\u5B83\u4F1A\u76F4\u63A5\u6539\u597D\uFF0C\u7ED3\u679C\u4F1A\u544A\u8BC9\u4F60");
2392
- return { sessionId };
2393
- };
2394
- ctx.inject(["adgNotify"], (scoped) => {
2395
- scoped.effect(() => scoped.adgNotify.onAction(PACK_REVIEW_SCOPE, async (noticeId, actionId) => {
2396
- const id = noticeId.split(":")[1];
2397
- if (id === void 0 || actionId !== "check" && actionId !== "keep")
2398
- throw new Error(`\u672A\u77E5\u64CD\u4F5C ${actionId}`);
2399
- const { sessionId } = await decide(id, actionId);
2400
- return sessionId === void 0 ? "\u597D\u7684\uFF0C\u811A\u672C\u5305\u4FDD\u6301\u4E0D\u53D8" : "\u597D\u7684\uFF0Cagent \u5148\u8BFB\u66F4\u65B0\u65E5\u5FD7\uFF0C\u518D\u68C0\u67E5\u811A\u672C\u5305\uFF1B\u8981\u6539\u7684\u5B83\u4F1A\u76F4\u63A5\u6539\u597D\uFF0C\u7ED3\u679C\u4F1A\u544A\u8BC9\u4F60";
2401
- }), "adg-scripts pack review actions");
2402
- });
2403
- return {
2404
- ask(script) {
2405
- const review = script.packReview;
2406
- if (review === void 0)
2407
- return;
2408
- const notify = ctx.get("adgNotify");
2409
- if (notify === void 0)
2410
- return;
2411
- void notify.send({
2412
- id: noticeIdOf(script.id, review.to),
2413
- scope: PACK_REVIEW_SCOPE,
2414
- title: `${script.name} \u66F4\u65B0\u4E86\uFF1A\u811A\u672C\u5305\u8981\u4E0D\u8981\u8DDF\u7740\u6539\uFF1F`,
2415
- text: [
2416
- `${script.name} \u4ECE ${review.from ?? "\u65E7\u7248\u672C"} \u66F4\u65B0\u5230\u4E86 ${review.to}\uFF0C\u5B83\u7684\u811A\u672C\u5305\u662F\u6309\u65E7\u7248\u672C\u5199\u7684\uFF0C\u65B0\u7248\u672C\u7684\u4EFB\u52A1\u3001\u914D\u7F6E\u6216\u65E5\u5FD7\u53EF\u80FD\u53D8\u4E86\u3002`,
2417
- "\u8981\u8BA9 agent \u5148\u8BFB\u8FD9\u6B21\u7684\u66F4\u65B0\u65E5\u5FD7\uFF0C\u518D\u68C0\u67E5\u811A\u672C\u5305\u5417\uFF1F\u8981\u6539\u7684\u5B83\u4F1A\u76F4\u63A5\u6539\u597D\uFF08\u4E4B\u524D\u7684\u7248\u672C\u7559\u5728\u5386\u53F2\u91CC\uFF09\uFF0C\u7ED3\u679C\u4F1A\u544A\u8BC9\u4F60\u3002"
2418
- ].join("\n"),
2419
- severity: "info",
2420
- actions: [{ id: "check", label: "\u8BA9 agent \u68C0\u67E5", style: "primary" }, { id: "keep", label: "\u4E0D\u7528\u6539" }]
2421
- }).catch((error) => log.warn(`pack review notice for ${script.id}: ${error instanceof Error ? error.message : String(error)}`));
2422
- },
2423
- decide
2424
- };
2425
- }
2426
-
2427
- // packages/script-registry/lib/optimize.js
2428
- var OPTIMIZE_SCOPE = "script-optimize";
2429
- var OPTIMIZE_TIMEOUT_MS = 30 * 6e4;
2430
- var noticeIdOf2 = (scriptId, runs, at) => `${OPTIMIZE_SCOPE}:${scriptId}:${at ?? 0}:${runs}`;
2431
- function optimizer(ctx, library, log) {
2432
- const open = /* @__PURE__ */ new Map();
2433
- const close = (id, done) => {
2434
- const noticeId = open.get(id);
2435
- if (noticeId === void 0)
2436
- return;
2437
- open.delete(id);
2438
- void ctx.get("adgNotify")?.update(noticeId, { done }).catch(() => {
2439
- });
2440
- };
2441
- const why = (script) => script.optimize?.due === "updated" ? `\u66F4\u65B0\u5230 ${script.current ?? script.localVersion?.version ?? "\u65B0\u7248\u672C"} \u540E\u5DF2\u7ECF\u8DD1\u901A\u4E86\uFF0C\u5148\u8BFB\u66F4\u65B0\u65E5\u5FD7` : script.optimize === void 0 ? void 0 : `${script.optimize.at === void 0 ? "\u88C5\u597D\u4EE5\u6765" : "\u4E0A\u6B21\u4F18\u5316\u4EE5\u6765"}\u5DF2\u7ECF\u8DD1\u6210\u529F ${script.optimize.runs} \u6B21`;
2442
- const decide = async (id, decision, by) => {
2443
- const lib = library();
2444
- const script = lib.get(id);
2445
- if (decision === "keep") {
2446
- close(id, "\u8FD9\u6B21\u4E0D\u4F18\u5316");
2447
- await lib.optimizeDone(id, "keep");
2448
- return {};
2449
- }
2450
- const sessions = ctx.get("sessionController");
2451
- if (sessions === void 0)
2452
- throw new Error("agent \u73B0\u5728\u4E0D\u53EF\u7528\uFF08\u4F1A\u8BDD\u670D\u52A1\u6CA1\u6709\u52A0\u8F7D\uFF09");
2453
- const gateway = ctx.get("adgGateway");
2454
- const conversations = sessionConversations(sessions, () => gateway?.workspaceDir(), (sessionId2, focus) => gateway?.skillScope.setFocus(sessionId2, focus) ?? Promise.resolve(), () => gateway);
2455
- const sessionId = await conversations.home(SCRIPT_ROLE.id, { focus: { scripts: [id] } });
2456
- const prompt = optimizeScriptPrompt(script.name, why(script), id);
2457
- await lib.optimizeDone(id, "run");
2458
- void conversations.ask(sessionId, taskMessage(by, `\u4F18\u5316\u811A\u672C\uFF1A${script.name}`, prompt), AbortSignal.timeout(OPTIMIZE_TIMEOUT_MS)).catch((error) => log.warn(`optimizing ${id}: ${error instanceof Error ? error.message : String(error)}`));
2459
- close(id, "\u5DF2\u4EA4\u7ED9\u300C\u811A\u672C\u300D\u4F18\u5316\uFF0C\u811A\u672C\u5305\u7684\u6539\u52A8\u4F1A\u5728\u300C\u811A\u672C\u300D\u9875\u7B49\u4F60\u786E\u8BA4");
2460
- return { sessionId };
2461
- };
2462
- ctx.inject(["adgNotify"], (scoped) => {
2463
- scoped.effect(() => scoped.adgNotify.onAction(OPTIMIZE_SCOPE, async (noticeId, actionId, actor) => {
2464
- const id = noticeId.split(":")[1];
2465
- if (id === void 0 || actionId !== "run" && actionId !== "keep")
2466
- throw new Error(`\u672A\u77E5\u64CD\u4F5C ${actionId}`);
2467
- const { sessionId } = await decide(id, actionId, actor.channel === "agent" ? actor.name ?? "\u52A9\u624B" : "\u4F60");
2468
- return sessionId === void 0 ? "\u597D\u7684\uFF0C\u8FD9\u6B21\u4E0D\u4F18\u5316\uFF0C\u4E4B\u540E\u8DD1\u591F\u4E86\u518D\u95EE" : "\u597D\u7684\uFF0C\u300C\u811A\u672C\u300D\u4F1A\u91CD\u65B0\u603B\u7ED3\u811A\u672C\u5305\u3001\u8C03\u5361\u4F4F\u65F6\u95F4\u3001\u628A\u8D70\u901A\u7684\u6B65\u9AA4\u5B58\u6210\u6280\u80FD\uFF1B\u811A\u672C\u5305\u7684\u6539\u52A8\u4F1A\u5728\u300C\u811A\u672C\u300D\u9875\u7B49\u4F60\u786E\u8BA4";
2469
- }), "adg-scripts optimize actions");
2470
- });
2471
- return {
2472
- ask(script) {
2473
- const notify = ctx.get("adgNotify");
2474
- if (notify === void 0 || script.optimize?.due === void 0)
2475
- return;
2476
- const noticeId = noticeIdOf2(script.id, script.optimize.runs, script.optimize.at);
2477
- close(script.id, "\u6709\u4E86\u65B0\u7684\u63D0\u8BAE");
2478
- open.set(script.id, noticeId);
2479
- void notify.send({
2480
- id: noticeId,
2481
- scope: OPTIMIZE_SCOPE,
2482
- title: `\u8981\u4F18\u5316\u300C${script.name}\u300D\u5417\uFF1F`,
2483
- text: [
2484
- `${script.name} ${why(script) ?? ""}\uFF0C\u6512\u4E0B\u7684\u8FD0\u884C\u8BB0\u5F55\u591F\u7528\u6765\u4F18\u5316\u5B83\u4E86\u3002`,
2485
- "\u8981\u8BA9\u300C\u811A\u672C\u300Dagent \u4E00\u6B21\u505A\u5B8C\uFF1A\u6309\u8FD9\u4E9B\u8FD0\u884C\u91CD\u65B0\u603B\u7ED3\u811A\u672C\u5305\u3001\u6309\u6B63\u5E38\u65F6\u7684\u65E5\u5FD7\u8282\u594F\u8C03\u300C\u591A\u4E45\u6CA1\u52A8\u9759\u7B97\u5361\u4F4F\u300D\u3001\u628A\u53CD\u590D\u8D70\u901A\u7684\u6B65\u9AA4\u5B58\u6210\u53EA\u7ED9\u5B83\u7528\u7684\u6280\u80FD\u5417\uFF1F\u811A\u672C\u5305\u8981\u6539\u7684\u5B83\u4F1A\u76F4\u63A5\u6539\u597D\uFF08\u4E4B\u524D\u7684\u7248\u672C\u7559\u5728\u5386\u53F2\u91CC\uFF09\uFF0C\u7ED3\u679C\u4F1A\u544A\u8BC9\u4F60\u3002"
2486
- ].join("\n"),
2487
- severity: "info",
2488
- actions: [{ id: "run", label: "\u4F18\u5316\u811A\u672C", style: "primary" }, { id: "keep", label: "\u8FD9\u6B21\u4E0D\u7528" }]
2489
- }).catch((error) => log.warn(`optimize notice for ${script.id}: ${error instanceof Error ? error.message : String(error)}`));
2490
- },
2491
- decide
2492
- };
2493
- }
2494
-
2495
- // packages/script-registry/lib/skill-hub-plugin.js
2496
- import { join as join5 } from "node:path";
2497
-
2498
- // packages/script-registry/lib/skill-hub.js
2499
- import { createHash } from "node:crypto";
2500
- import { cp as cp2, mkdir as mkdir3, readdir as readdir3, readFile as readFile4, rename as rename3, rm as rm2, stat as stat2 } from "node:fs/promises";
2501
- import { join as join4, relative as relative2, resolve as resolve2, sep } from "node:path";
2502
- var DEFAULT_HUB_REPO = { repo: "MultiGameAssistant/skills", branch: "main" };
2503
- var REFRESH_MS = 24 * 60 * 6e4;
2504
- var SKILL_FILE2 = "SKILL.md";
2505
- var NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
2506
- var Owner = external_exports.object({ games: external_exports.array(external_exports.string()).optional(), scripts: external_exports.array(external_exports.string()).optional() });
2507
- var Installed = external_exports.object({ repo: external_exports.string(), path: external_exports.string(), hash: external_exports.string(), at: external_exports.number(), owner: Owner.optional() });
2508
- var State = external_exports.object({
2509
- repos: external_exports.array(external_exports.object({ repo: external_exports.string(), branch: external_exports.string() })).optional(),
2510
- installed: external_exports.record(external_exports.string(), Installed).default({}),
2511
- read: external_exports.record(external_exports.string(), external_exports.object({ at: external_exports.number(), skills: external_exports.array(external_exports.looseObject({ name: external_exports.string(), repo: external_exports.string(), path: external_exports.string(), hash: external_exports.string() })) })).default({})
2512
- });
2513
- var Index = external_exports.object({
2514
- skills: external_exports.array(external_exports.object({
2515
- name: external_exports.string().regex(NAME),
2516
- path: external_exports.string().min(1),
2517
- title: external_exports.string().optional(),
2518
- kind: external_exports.enum(["game", "script", "general"]).optional(),
2519
- games: external_exports.array(external_exports.string()).optional(),
2520
- scripts: external_exports.array(external_exports.string()).optional()
2521
- }))
2522
- });
2523
- var SkillHub = class {
2524
- #options;
2525
- #now;
2526
- #state = { installed: {}, read: {} };
2527
- #loading;
2528
- constructor(options) {
2529
- this.#options = options;
2530
- this.#now = options.now ?? Date.now;
2531
- }
2532
- get skillsDir() {
2533
- return join4(this.#options.dir, "skills");
2534
- }
2535
- /** Read the state and register the downloaded skills. */
2536
- start() {
2537
- this.#loading ??= (async () => {
2538
- try {
2539
- this.#state = State.parse(JSON.parse(await readFile4(join4(this.#options.dir, "state.json"), "utf8")));
2540
- } catch {
2541
- }
2542
- await rm2(join4(this.#options.dir, "base"), { recursive: true, force: true });
2543
- for (const name of Object.keys(this.#state.installed))
2544
- await this.#register(name);
2545
- })();
2546
- return this.#loading;
2547
- }
2548
- repos() {
2549
- return this.#state.repos ?? [DEFAULT_HUB_REPO];
2550
- }
2551
- async setRepos(repos) {
2552
- await this.start();
2553
- const seen = /* @__PURE__ */ new Set();
2554
- this.#state.repos = repos.filter((r) => {
2555
- const key = r.repo.toLowerCase();
2556
- if (seen.has(key))
2557
- return false;
2558
- seen.add(key);
2559
- return true;
2560
- }).map((r) => ({ repo: r.repo, branch: r.branch }));
2561
- await this.#save();
2562
- return this.repos();
2563
- }
2564
- /**
2565
- * What the repositories have, and how each stands here. `refresh` reads
2566
- * them now; otherwise what was read today (a repository that cannot be
2567
- * read gives what was read before, and says so in `errors`).
2568
- */
2569
- async list(options = {}) {
2570
- await this.start();
2571
- const errors = [];
2572
- const skills = [];
2573
- let fetchedAt;
2574
- for (const repo of this.repos()) {
2575
- const key = repoKey(repo);
2576
- let read = this.#state.read[key];
2577
- if (options.refresh === true || read === void 0 || this.#now() - read.at >= REFRESH_MS) {
2578
- try {
2579
- const fresh = { at: this.#now(), skills: await this.#readRepo(repo, options.signal) };
2580
- this.#state.read[key] = fresh;
2581
- read = fresh;
2582
- await this.#save();
2583
- } catch (error) {
2584
- if (options.signal?.aborted === true)
2585
- throw error;
2586
- errors.push(`${repo.repo}\uFF1A${errorText2(error)}`);
2587
- this.#options.log.warn(`skill hub ${repo.repo}: ${errorText2(error)}`);
2588
- }
2589
- }
2590
- if (read === void 0)
2591
- continue;
2592
- fetchedAt = Math.min(fetchedAt ?? Infinity, read.at);
2593
- for (const skill of read.skills)
2594
- if (!skills.some((s) => s.name === skill.name))
2595
- skills.push(skill);
2596
- }
2597
- const taken = await this.#options.taken();
2598
- const items = [];
2599
- for (const skill of skills)
2600
- items.push(await this.#item(skill, taken));
2601
- for (const [name, record] of Object.entries(this.#state.installed)) {
2602
- if (items.some((i) => i.name === name))
2603
- continue;
2604
- const content = await readFile4(join4(this.skillsDir, name, SKILL_FILE2), "utf8").catch(() => "");
2605
- const front = frontmatter(content);
2606
- items.push({ name, description: front?.description ?? "", kind: "general", games: [], scripts: [], repo: record.repo, path: record.path, hash: record.hash, installed: { at: record.at, update: false } });
2607
- }
2608
- return { items, repos: this.repos(), errors, ...fetchedAt === void 0 ? {} : { fetchedAt } };
2609
- }
2610
- /** Download a skill from the repository (the first that has it, or `repo`). */
2611
- async install(name, repo, signal) {
2612
- const skill = await this.#find(name, repo, signal);
2613
- const blocked = (await this.#options.taken()).get(name);
2614
- if (blocked !== void 0)
2615
- throw new Error(`\u5DF2\u6709\u540C\u540D\u7684${blocked}\u300C${name}\u300D\uFF0C\u6CA1\u6709\u4E0B\u8F7D`);
2616
- await this.#put(skill);
2617
- this.#options.log.info(`skill hub: downloaded ${name} from ${skill.repo}`);
2618
- return this.#item(skill, await this.#options.taken());
2619
- }
2620
- /** Take the repository's newer version, in place of this one (changed here or not). */
2621
- async update(name, signal) {
2622
- const record = this.#record(name);
2623
- const skill = await this.#find(name, record.repo, signal);
2624
- if (skill.hash === record.hash)
2625
- return { state: "current", item: await this.#item(skill, await this.#options.taken()) };
2626
- await this.#put(skill);
2627
- return { state: "updated", item: await this.#item(skill, await this.#options.taken()) };
2628
- }
2629
- async remove(name) {
2630
- this.#record(name);
2631
- this.#options.register(name, void 0);
2632
- await rm2(join4(this.skillsDir, name), { recursive: true, force: true });
2633
- delete this.#state.installed[name];
2634
- await this.#save();
2635
- }
2636
- /** Put a downloaded skill under other games and scripts (empty: general); `null`: back to the repository's. */
2637
- async setOwner(name, owner) {
2638
- const record = this.#record(name);
2639
- if (owner === null)
2640
- delete record.owner;
2641
- else
2642
- record.owner = { games: [...new Set(owner.games ?? [])], scripts: [...new Set(owner.scripts ?? [])] };
2643
- await this.#save();
2644
- await this.#register(name);
2645
- }
2646
- /** Re-read a downloaded skill after its file changed (the agent or the user edited it). */
2647
- async reload(name) {
2648
- if (this.#state.installed[name] !== void 0)
2649
- await this.#register(name);
2650
- }
2651
- isInstalled(name) {
2652
- return this.#state.installed[name] !== void 0;
2653
- }
2654
- // ── internals ──
2655
- #record(name) {
2656
- const record = this.#state.installed[name];
2657
- if (record === void 0)
2658
- throw new Error(`\u6CA1\u6709\u4ECE\u6280\u80FD\u5E93\u4E0B\u8F7D\u8FC7\u300C${name}\u300D`);
2659
- return record;
2660
- }
2661
- async #find(name, repo, signal) {
2662
- let { items } = await this.list(signal === void 0 ? {} : { signal });
2663
- let found = items.find((i) => i.name === name && (repo === void 0 || i.repo.toLowerCase() === repo.toLowerCase()) && !isOrphan(i, this.#state));
2664
- if (found === void 0) {
2665
- ;
2666
- ({ items } = await this.list({ refresh: true, ...signal === void 0 ? {} : { signal } }));
2667
- found = items.find((i) => i.name === name && (repo === void 0 || i.repo.toLowerCase() === repo.toLowerCase()) && !isOrphan(i, this.#state));
2668
- }
2669
- if (found === void 0)
2670
- throw new Error(`\u6280\u80FD\u5E93\u91CC\u6CA1\u6709\u300C${name}\u300D`);
2671
- if (!await stat2(this.#repoFile(found)).then((s) => s.isFile(), () => false)) {
2672
- await this.list({ refresh: true, ...signal === void 0 ? {} : { signal } });
2673
- }
2674
- const { installed: _installed, blocked: _blocked, ...skill } = found;
2675
- return skill;
2676
- }
2677
- #repoFile(skill) {
2678
- return join4(this.#options.dir, "repos", repoKey({ repo: skill.repo, branch: "" }), ...skill.path.split("/"), SKILL_FILE2);
2679
- }
2680
- /** Copy the repository's version in as the downloaded skill. */
2681
- async #put(skill) {
2682
- const from = join4(this.#options.dir, "repos", repoKey({ repo: skill.repo, branch: "" }), ...skill.path.split("/"));
2683
- const to = join4(this.skillsDir, skill.name);
2684
- await rm2(to, { recursive: true, force: true });
2685
- await mkdir3(this.skillsDir, { recursive: true });
2686
- await cp2(from, to, { recursive: true });
2687
- const owner = this.#state.installed[skill.name]?.owner;
2688
- this.#state.installed[skill.name] = { repo: skill.repo, path: skill.path, hash: skill.hash, at: this.#now(), ...owner === void 0 ? {} : { owner } };
2689
- await this.#save();
2690
- await this.#register(skill.name);
2691
- }
2692
- async #register(name) {
2693
- const path = join4(this.skillsDir, name, SKILL_FILE2);
2694
- const content = await readFile4(path, "utf8").catch(() => void 0);
2695
- const front = content === void 0 ? void 0 : frontmatter(content);
2696
- if (content === void 0 || front === void 0) {
2697
- this.#options.log.warn(`skill hub: ${name} has no usable SKILL.md; not registered`);
2698
- this.#options.register(name, void 0);
2699
- return;
2700
- }
2701
- const record = this.#state.installed[name];
2702
- const listed = record?.owner ?? (record === void 0 ? void 0 : Object.values(this.#state.read).flatMap((r) => r.skills).find((s) => s.name === name && s.repo === record.repo));
2703
- const ids = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
2704
- const games = ids(listed?.games);
2705
- const scripts = ids(listed?.scripts);
2706
- const owner = games.length + scripts.length === 0 ? void 0 : { ...games.length === 0 ? {} : { games }, ...scripts.length === 0 ? {} : { scripts } };
2707
- this.#options.register(name, { description: front.description, content: front.body, path, dir: join4(this.skillsDir, name), ...owner === void 0 ? {} : { owner } });
2708
- }
2709
- async #item(skill, taken) {
2710
- const record = this.#state.installed[skill.name];
2711
- if (record === void 0) {
2712
- const blocked = taken.get(skill.name);
2713
- return { ...skill, ...blocked === void 0 ? {} : { blocked: `\u5DF2\u6709\u540C\u540D\u7684${blocked}` } };
2714
- }
2715
- return { ...skill, installed: { at: record.at, update: skill.repo === record.repo && skill.hash !== record.hash } };
2716
- }
2717
- /** Download the repository and list its skills; the copy replaces the one before. */
2718
- async #readRepo(repo, signal) {
2719
- const key = repoKey(repo);
2720
- const work = join4(this.#options.dir, "downloads");
2721
- await mkdir3(work, { recursive: true });
2722
- const archive = join4(work, `${key}.zip`);
2723
- const unpacked = join4(work, `${key}-${this.#now()}`);
2724
- await this.#options.download(`https://codeload.github.com/${repo.repo}/zip/refs/heads/${encodeURIComponent(repo.branch)}`, archive, signal);
2725
- try {
2726
- await this.#options.extract(archive, unpacked, signal);
2727
- const skills = await readSkills(unpacked, repo.repo);
2728
- const target = join4(this.#options.dir, "repos", key);
2729
- await rm2(target, { recursive: true, force: true });
2730
- await mkdir3(join4(this.#options.dir, "repos"), { recursive: true });
2731
- await rename3(unpacked, target);
2732
- return skills;
2733
- } finally {
2734
- await rm2(archive, { force: true });
2735
- await rm2(unpacked, { recursive: true, force: true });
2736
- }
2737
- }
2738
- #save() {
2739
- return mkdir3(this.#options.dir, { recursive: true }).then(() => writeFileAtomic(join4(this.#options.dir, "state.json"), `${JSON.stringify(this.#state, null, 1)}
2740
- `));
2741
- }
2742
- };
2743
- async function readSkills(root, repo) {
2744
- const indexText = await readFile4(join4(root, "index.json"), "utf8").catch(() => void 0);
2745
- const listed = [];
2746
- if (indexText !== void 0) {
2747
- const parsed = Index.safeParse(JSON.parse(indexText.replace(/^/, "")));
2748
- if (!parsed.success)
2749
- throw new Error(`index.json \u683C\u5F0F\u4E0D\u5BF9\uFF1A${parsed.error.issues.map((i) => `${i.path.join(".")} ${i.message}`).join("; ")}`);
2750
- listed.push(...parsed.data.skills);
2751
- } else {
2752
- for (const path of await findSkillFolders(root, "", 3))
2753
- listed.push({ path });
2754
- }
2755
- const skills = [];
2756
- for (const entry of listed) {
2757
- const path = entry.path.replace(/\\/g, "/").replace(/^\.?\/+|\/+$/g, "");
2758
- const full = resolve2(root, ...path.split("/"));
2759
- const rel = relative2(resolve2(root), full);
2760
- if (path === "" || rel.startsWith("..") || rel.split(sep).includes(".."))
2761
- continue;
2762
- const content = await readFile4(join4(full, SKILL_FILE2), "utf8").catch(() => void 0);
2763
- const front = content === void 0 ? void 0 : frontmatter(content);
2764
- if (content === void 0 || front === void 0)
2765
- continue;
2766
- const name = entry.name ?? front.name;
2767
- if (name === void 0 || !NAME.test(name) || skills.some((s) => s.name === name))
2768
- continue;
2769
- if (front.name !== void 0 && front.name !== name)
2770
- continue;
2771
- skills.push({
2772
- name,
2773
- description: front.description,
2774
- kind: entry.kind ?? (name.startsWith("game-") ? "game" : "general"),
2775
- games: entry.games ?? [],
2776
- scripts: entry.scripts ?? [],
2777
- repo,
2778
- path,
2779
- hash: hash(content),
2780
- ...entry.title === void 0 ? {} : { title: entry.title }
2781
- });
2782
- }
2783
- return skills;
2784
- }
2785
- async function findSkillFolders(root, sub, depth) {
2786
- const out = [];
2787
- const entries = await readdir3(join4(root, sub), { withFileTypes: true }).catch(() => []);
2788
- if (sub !== "" && entries.some((e) => e.isFile() && e.name === SKILL_FILE2))
2789
- out.push(sub);
2790
- if (depth === 0)
2791
- return out;
2792
- for (const entry of entries) {
2793
- if (entry.isDirectory() && !entry.name.startsWith("."))
2794
- out.push(...await findSkillFolders(root, sub === "" ? entry.name : `${sub}/${entry.name}`, depth - 1));
2795
- }
2796
- return out;
2797
- }
2798
- function frontmatter(text) {
2799
- const match = /^?---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(text);
2800
- if (match === null)
2801
- return void 0;
2802
- const field = (key) => {
2803
- const raw = new RegExp(`^${key}:\\s*(.+)$`, "m").exec(match[1])?.[1]?.trim();
2804
- if (raw === void 0)
2805
- return void 0;
2806
- if (raw.startsWith('"')) {
2807
- try {
2808
- return JSON.parse(raw);
2809
- } catch {
2810
- return raw;
2811
- }
2812
- }
2813
- return raw.replace(/^'(.*)'$/, "$1");
2814
- };
2815
- const description = field("description");
2816
- if (description === void 0 || description === "")
2817
- return void 0;
2818
- const name = field("name");
2819
- return { ...name === void 0 ? {} : { name }, description, body: match[2] };
2820
- }
2821
- function hash(text) {
2822
- return createHash("sha256").update(text.replace(/\r\n/g, "\n")).digest("hex").slice(0, 16);
2823
- }
2824
- function repoKey(repo) {
2825
- return repo.repo.toLowerCase().replace(/[^a-z0-9._-]+/g, "__");
2826
- }
2827
- function isOrphan(item, state) {
2828
- return item.installed !== void 0 && !Object.values(state.read).some((r) => r.skills.some((s) => s.name === item.name));
2829
- }
2830
- function errorText2(error) {
2831
- return error instanceof Error ? error.message : String(error);
2832
- }
2833
-
2834
- // packages/script-registry/lib/skill-hub-plugin.js
2835
- function takenLabel(source) {
2836
- if (source === "bundled")
2837
- return "\u5185\u7F6E\u6280\u80FD";
2838
- if (source === "custom")
2839
- return "\u6280\u80FD\uFF08\u4F60\u4FDD\u5B58\u7684\u6216\u811A\u672C\u5305\u3001\u6E38\u620F\u5305\u7684\uFF09";
2840
- if (source.startsWith("user-"))
2841
- return "\u6280\u80FD\uFF08\u4F60\u7684\u6280\u80FD\u6587\u4EF6\u5939\uFF09";
2842
- return "\u6280\u80FD";
2843
- }
2844
- function startSkillHub(ctx, library, ready, approve, log) {
2845
- const entries = /* @__PURE__ */ new Map();
2846
- const disposers = /* @__PURE__ */ new Map();
2847
- let skills;
2848
- const changed = () => ctx.get("adgGateway")?.broadcast("skillhub/changed", {});
2849
- const apply = (name) => {
2850
- disposers.get(name)?.();
2851
- disposers.delete(name);
2852
- const entry = entries.get(name);
2853
- const scope = ctx.get("adgGateway")?.skillScope;
2854
- if (entry === void 0 || scope === void 0)
2855
- return;
2856
- try {
2857
- disposers.set(name, scope.register({ name, description: entry.description, content: entry.content, source: "hub", path: entry.path, resourceBase: { kind: "directory", path: entry.dir }, ...entry.owner === void 0 ? {} : { owner: entry.owner } }));
2858
- } catch (error) {
2859
- log.warn(`skill hub: ${name} not registered: ${error instanceof Error ? error.message : String(error)}`);
2860
- }
2861
- };
2862
- const hub = new SkillHub({
2863
- dir: join5(library.dataDir, "skill-hub"),
2864
- download: (url, dest, signal) => library.downloadFromGitHub(url, dest, signal),
2865
- extract: async (archive, dest, signal) => {
2866
- await library.unpack(archive, dest, signal);
2867
- },
2868
- taken: async () => {
2869
- const out = /* @__PURE__ */ new Map();
2870
- for (const skill of await skills?.list({}) ?? [])
2871
- if (skill.source !== "hub")
2872
- out.set(skill.name, takenLabel(skill.source));
2873
- return out;
2874
- },
2875
- register: (name, skill) => {
2876
- if (skill === void 0)
2877
- entries.delete(name);
2878
- else
2879
- entries.set(name, skill);
2880
- apply(name);
2881
- },
2882
- log
2883
- });
2884
- const started = ready.then(() => hub.start());
2885
- ctx.inject(["skills", "adgGateway"], (scoped) => {
2886
- skills = scoped.skills;
2887
- for (const name of entries.keys())
2888
- apply(name);
2889
- scoped.effect(() => () => {
2890
- for (const dispose of disposers.values())
2891
- dispose();
2892
- disposers.clear();
2893
- skills = void 0;
2894
- }, "adg-skill-hub skills");
2895
- });
2896
- ctx.inject(["adgGateway"], (scoped) => {
2897
- const methods = {
2898
- "skillhub/list": (params, call) => hub.list({ refresh: params.refresh === true, signal: call.signal }),
2899
- "skillhub/install": async (params, call) => {
2900
- const p = params;
2901
- const item = await hub.install(p.name, p.repo, call.signal);
2902
- changed();
2903
- return item;
2904
- },
2905
- "skillhub/update": async (params, call) => {
2906
- const result = await hub.update(params.name, call.signal);
2907
- changed();
2908
- return result;
2909
- },
2910
- "skillhub/remove": async (params) => {
2911
- await hub.remove(params.name);
2912
- changed();
2913
- return {};
2914
- },
2915
- "skillhub/owner": async (params) => {
2916
- const p = params;
2917
- await hub.setOwner(p.name, p.owner);
2918
- changed();
2919
- ctx.get("adgGateway")?.broadcast("skills/changed", {});
2920
- return {};
2921
- },
2922
- "skillhub/repos/set": async (params) => {
2923
- const repos = await hub.setRepos(params.repos);
2924
- changed();
2925
- return { repos };
2926
- }
2927
- };
2928
- scoped.adgGateway.register({
2929
- id: SKILLHUB_CAPABILITY,
2930
- version: 1,
2931
- methods: Object.fromEntries(Object.entries(methods).map(([name, handler]) => [name, async (params, call) => {
2932
- await started;
2933
- return handler(params, call);
2934
- }]))
2935
- });
2936
- });
2937
- ctx.inject(["adgGateway"], (gateway) => gateway.adgGateway.agentPart("adg-skill-hub tools", (agent) => {
2938
- const registered = [];
2939
- for (const tool2 of hubTools(hub, approve, changed)) {
2940
- registered.push(agent.tools.register({ ...tool2, execute: async (args, exec) => {
2941
- await started;
2942
- await ctx.get("adgGateway")?.guardTool(exec);
2943
- return tool2.execute(args, exec);
2944
- } }));
2945
- }
2946
- return () => {
2947
- for (const dispose of registered)
2948
- dispose();
2949
- };
2950
- }));
2951
- return hub;
2952
- }
2953
- function hubTools(hub, approve, changed) {
2954
- const render = (_args, value) => [{ type: "text", text: JSON.stringify(value, null, 1) }];
2955
- return [
2956
- {
2957
- name: "skill_hub_list",
2958
- description: "\u67E5\u770B\u6280\u80FD\u5E93\uFF08MultiGameAssistant/skills \u7B49 GitHub \u4ED3\u5E93\uFF09\u91CC\u6709\u54EA\u4E9B\u6E38\u620F\u548C\u811A\u672C\u7684\u6280\u80FD\u3001\u54EA\u4E9B\u5DF2\u7ECF\u4E0B\u8F7D\u3001\u54EA\u4E9B\u6709\u65B0\u7248\u672C\u3002\u53EF\u4EE5\u6309\u6E38\u620F id \u6216\u811A\u672C id \u7B5B\u9009\u3002",
2959
- parameters: {
2960
- type: "object",
2961
- properties: {
2962
- game: { type: "string", description: "\u6E38\u620F id\uFF08game_list \u53EF\u67E5\uFF09\uFF0C\u53EA\u770B\u5B83\u7684\u6280\u80FD\u3002" },
2963
- script: { type: "string", description: "\u811A\u672C\u6216\u811A\u672C\u5305 id\uFF0C\u53EA\u770B\u5B83\u7684\u6280\u80FD\u3002" }
2964
- },
2965
- additionalProperties: false
2966
- },
2967
- output: { schema: {}, render },
2968
- timeoutMs: 12e4,
2969
- isConcurrencySafe: () => true,
2970
- execute: async (args) => {
2971
- const a = external_exports.object({ game: external_exports.string().nullish(), script: external_exports.string().nullish() }).parse(args ?? {});
2972
- const { items, errors } = await hub.list();
2973
- const shown = items.filter((i) => (a.game == null || i.games.includes(a.game)) && (a.script == null || i.scripts.includes(a.script)));
2974
- return {
2975
- errors,
2976
- skills: shown.map((i) => ({ name: i.name, description: i.description, kind: i.kind, games: i.games, scripts: i.scripts, repo: i.repo, installed: i.installed, blocked: i.blocked }))
2977
- };
2978
- },
2979
- presentCall: () => ({ card: "generic", title: "\u67E5\u770B\u6280\u80FD\u5E93", kind: "read" })
2980
- },
2981
- {
2982
- name: "skill_hub_install",
2983
- description: "\u4ECE\u6280\u80FD\u5E93\u4E0B\u8F7D\u4E00\u4E2A\u6280\u80FD\uFF08\u4F1A\u5148\u8BF7\u7528\u6237\u786E\u8BA4\uFF09\u3002\u4E0B\u8F7D\u540E agent \u9A6C\u4E0A\u5C31\u80FD\u7528\uFF1B\u4E0B\u8F7D\u7684\u6280\u80FD\u8DDF\u7740\u6280\u80FD\u5E93\u8D70\uFF0C\u66F4\u65B0\u65F6\u6574\u4E2A\u6362\u6210\u6280\u80FD\u5E93\u7684\u65B0\u7248\u672C\uFF0C\u5728\u8FD9\u91CC\u6539\u7684\u4E0D\u4FDD\u7559\u3002",
2984
- parameters: {
2985
- type: "object",
2986
- properties: { name: { type: "string", description: "\u6280\u80FD\u540D\uFF08skill_hub_list \u53EF\u67E5\uFF09\u3002" } },
2987
- required: ["name"],
2988
- additionalProperties: false
2989
- },
2990
- output: { schema: {}, render },
2991
- timeoutMs: 12e4,
2992
- isConcurrencySafe: () => false,
2993
- execute: async (args, exec) => {
2994
- const { name } = external_exports.object({ name: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/) }).parse(args);
2995
- const { items } = await hub.list();
2996
- const item = items.find((i) => i.name === name);
2997
- if (item === void 0)
2998
- throw new Error(`\u6280\u80FD\u5E93\u91CC\u6CA1\u6709\u300C${name}\u300D`);
2999
- if (item.installed !== void 0)
3000
- return { ok: true, already: true, name };
3001
- if (item.blocked !== void 0)
3002
- throw new Error(`${item.blocked}\u300C${name}\u300D\uFF0C\u4E0D\u80FD\u4E0B\u8F7D`);
3003
- await approve(exec, `\u4ECE\u6280\u80FD\u5E93 ${item.repo} \u4E0B\u8F7D\u6280\u80FD\u300C${name}\u300D\uFF1A${item.description}`);
3004
- await hub.install(name, item.repo, exec.signal);
3005
- changed();
3006
- return { ok: true, name };
3007
- },
3008
- presentCall: (args) => ({ card: "generic", title: `\u4E0B\u8F7D\u6280\u80FD\uFF1A${String(args?.name ?? "")}`, kind: "execute" })
3009
- }
3010
- ];
3011
- }
3012
-
3013
- // packages/script-registry/lib/script-summary.js
3014
- var SUMMARY_TIMEOUT_MS = 10 * 6e4;
3015
- var MAX_SUMMARY = 800;
3016
- function scriptSummaries(ctx, library, log) {
3017
- const running = /* @__PURE__ */ new Set();
3018
- return {
3019
- async summarize(id) {
3020
- const sessions = ctx.get("sessionController");
3021
- if (sessions === void 0)
3022
- throw new Error("agent \u73B0\u5728\u4E0D\u53EF\u7528\uFF08\u4F1A\u8BDD\u670D\u52A1\u6CA1\u6709\u52A0\u8F7D\uFF09");
3023
- const previous = library.get(id).summary;
3024
- if (running.has(id) && previous?.state === "running" && previous.sessionId !== void 0)
3025
- return previous.sessionId;
3026
- const material = await library.summaryMaterial(id);
3027
- const name = library.get(id).name;
3028
- const conversations = sessionConversations(sessions, () => ctx.get("adgGateway")?.workspaceDir(), (sessionId2, focus) => ctx.get("adgGateway")?.skillScope.setFocus(sessionId2, focus) ?? Promise.resolve(), () => ctx.get("adgGateway"));
3029
- const sessionId = await conversations.home(SCRIPT_ROLE.id, { focus: { scripts: [id] } });
3030
- running.add(id);
3031
- await library.setSummary(id, { state: "running", at: Date.now(), sessionId, ...previous?.text === void 0 || previous.state !== "done" ? {} : { text: previous.text } });
3032
- const prompt = [
3033
- `\u7528\u6237\u60F3\u77E5\u9053\u811A\u672C\u5E93\u91CC\u7684\u300C${name}\u300D\u662F\u4EC0\u4E48\u3002\u6839\u636E\u4E0B\u9762\u7684\u6750\u6599\u5199\u4E00\u6BB5\u7B80\u4ECB\uFF0C\u7ED9\u4E0D\u61C2\u6280\u672F\u7684\u73A9\u5BB6\u770B\uFF1A`,
3034
- "1. \u5B83\u662F\u4EC0\u4E48\uFF08\u81EA\u52A8\u5316\u5DE5\u5177\u3001\u8F85\u52A9\u3001\u542F\u52A8\u5668\u2026\u2026\uFF09\u3001\u7ED9\u54EA\u4E2A\u6E38\u620F\u7528\u3001\u5728\u7535\u8111\u4E0A\u8FD8\u662F\u6A21\u62DF\u5668\u91CC\u8DD1\uFF1B",
3035
- "2. \u4E3B\u8981\u80FD\u505A\u4EC0\u4E48\uFF08\u65E5\u5E38\u3001\u5237\u4F53\u529B\u3001\u6D3B\u52A8\u2026\u2026\u6311\u6700\u91CD\u8981\u7684\u51E0\u9879\uFF09\uFF1B",
3036
- "3. \u600E\u4E48\u7528\uFF1A\u6709\u754C\u9762\u8FD8\u662F\u547D\u4EE4\u884C\uFF0C\u9700\u8981\u6CE8\u610F\u4EC0\u4E48\uFF08\u8981\u7BA1\u7406\u5458\u3001\u8981\u5F00\u6A21\u62DF\u5668\u3001\u5206\u8FA8\u7387\u3001\u4F1A\u5360\u7528\u9F20\u6807\u952E\u76D8\u7B49\uFF0C\u6750\u6599\u91CC\u63D0\u5230\u7684\u624D\u5199\uFF09\u3002",
3037
- "\u6750\u6599\u4E0D\u591F\u65F6\u53EF\u4EE5\u7528\u7F51\u9875\u5DE5\u5177\u770B\u5B83\u7684 GitHub \u4ED3\u5E93\u6216\u5B98\u7F51\u8BF4\u660E\uFF1B\u4E0D\u8981\u8FD0\u884C\u5B83\uFF0C\u4E0D\u8981\u6539\u4EFB\u4F55\u6587\u4EF6\uFF0C\u4E0D\u8981\u5411\u7528\u6237\u63D0\u95EE\u3002",
3038
- `\u6700\u540E\u53EA\u8F93\u51FA\u7B80\u4ECB\u672C\u8EAB\uFF1A\u4E09\u5230\u4E94\u53E5\u4E2D\u6587\uFF0C\u4E0D\u52A0\u6807\u9898\u3001\u4E0D\u7528\u5217\u8868\uFF0C\u4E0D\u8D85\u8FC7 ${MAX_SUMMARY / 2} \u5B57\u3002`,
3039
- "",
3040
- "\u6750\u6599\uFF1A",
3041
- material
3042
- ].join("\n");
3043
- void conversations.ask(sessionId, taskMessage("\u4F60", `\u811A\u672C\u4ECB\u7ECD\uFF1A${name}`, prompt), AbortSignal.timeout(SUMMARY_TIMEOUT_MS)).then(
3044
- // A turn that did not finish (no model set up, cut off) comes back as a note, not a summary.
3045
- (answer) => library.setSummary(id, answer.startsWith("\uFF08\u8FD9\u4E00\u8F6E\u6CA1\u6709\u5B8C\u6210") || answer.startsWith("\uFF08agent \u6CA1\u6709\u56DE\u590D\u6587\u5B57") ? { state: "failed", at: Date.now(), sessionId, text: answer.replace(/^(这一轮没有完成:?|)$/g, "") } : { state: "done", at: Date.now(), sessionId, text: tidy(answer) }),
3046
- (error) => {
3047
- log.warn(`script summary ${id}: ${error instanceof Error ? error.message : String(error)}`);
3048
- return library.setSummary(id, { state: "failed", at: Date.now(), sessionId, text: error instanceof Error ? error.message : String(error) });
3049
- }
3050
- ).finally(() => running.delete(id));
3051
- return sessionId;
3052
- }
3053
- };
3054
- }
3055
- function tidy(answer) {
3056
- const text = answer.trim().replace(/^#+\s.*\n+/, "").replace(/^["“「](.*)["”」]$/s, "$1").trim();
3057
- return text.length > MAX_SUMMARY ? `${text.slice(0, MAX_SUMMARY)}\u2026` : text;
3058
- }
3059
-
3060
- // packages/script-registry/lib/tools.js
3061
- var TOOL_NAMES = {
3062
- list: "script_list",
3063
- search: "script_search",
3064
- releases: "script_releases",
3065
- install: "script_install",
3066
- update: "script_update",
3067
- rollback: "script_rollback",
3068
- import: "script_import",
3069
- remove: "script_remove",
3070
- envCheck: "script_env_check",
3071
- envFix: "script_env_fix",
3072
- setupRun: "script_setup_run"
3073
- };
3074
- var INSTALL_TIMEOUT_MS = 60 * 6e4;
3075
- function json(value) {
3076
- return JSON.parse(JSON.stringify(value ?? null));
3077
- }
3078
- function parse(schema, args) {
3079
- const parsed = schema.safeParse(args);
3080
- if (!parsed.success)
3081
- throw new Error(`\u53C2\u6570\u65E0\u6548\uFF1A${parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"} ${i.message}`).join("; ")}`);
3082
- return parsed.data;
3083
- }
3084
- function errorOf(error) {
3085
- return error instanceof Error ? error.message : String(error);
3086
- }
3087
- function blankToUndefined(value) {
3088
- return value === null || typeof value === "string" && value.trim() === "" ? void 0 : value;
3089
- }
3090
- var opt = (schema) => external_exports.preprocess(blankToUndefined, schema.optional());
3091
- function tool(spec) {
3092
- return {
3093
- name: spec.name,
3094
- description: spec.description,
3095
- parameters: {
3096
- type: "object",
3097
- properties: spec.properties,
3098
- ...spec.required === void 0 ? {} : { required: spec.required },
3099
- additionalProperties: false
3100
- },
3101
- output: {
3102
- schema: {},
3103
- render: (_args, value) => [{ type: "text", text: JSON.stringify(value, null, 1) }]
3104
- },
3105
- timeoutMs: spec.timeoutMs ?? 12e4,
3106
- isConcurrencySafe: () => spec.readOnly === true,
3107
- execute: async (args, exec) => json(await spec.execute(args, exec)),
3108
- presentCall: (args) => ({ card: "generic", title: spec.title(args ?? {}), kind: spec.kind })
3109
- };
3110
- }
3111
- async function followJob(library, started, signal) {
3112
- const onAbort = () => {
3113
- try {
3114
- library.cancelJob(started.job.id);
3115
- } catch {
3116
- }
3117
- };
3118
- signal.addEventListener("abort", onAbort, { once: true });
3119
- try {
3120
- return await started.done;
3121
- } finally {
3122
- signal.removeEventListener("abort", onAbort);
3123
- }
3124
- }
3125
- function setupOf(library, scriptId) {
3126
- const setup = library.pendingSetup(scriptId);
3127
- if (setup === void 0)
3128
- return void 0;
3129
- return {
3130
- installer: setup.file,
3131
- kind: setup.kind,
3132
- version: setup.version,
3133
- dir: setup.dir,
3134
- next: `\u8FD9\u662F\u5B89\u88C5\u7A0B\u5E8F\uFF0C\u8FD8\u6CA1\u88C5\u597D\uFF1A\u7528 ${TOOL_NAMES.setupRun}\uFF08id=${scriptId}\uFF09\u8FD0\u884C\u5B83\uFF0C\u88C5\u597D\u540E\u7528 ${TOOL_NAMES.import}\uFF08path=${setup.dir}\uFF0Cid=${scriptId}\uFF09\u5BFC\u5165`
3135
- };
3136
- }
3137
- var describeJob = (job) => job.phase === "done" ? { ok: true, script: job.scriptId, version: job.version } : { ok: false, script: job.scriptId, phase: job.phase, error: job.error };
3138
- function scriptTools(library, approve) {
3139
- const repo = { type: "string", description: "GitHub \u4ED3\u5E93\uFF0C\u683C\u5F0F owner/repo\uFF0C\u4F8B\u5982 MaaAssistantArknights/MaaAssistantArknights\u3002" };
3140
- const id = { type: "string", description: "\u811A\u672C\u5E93\u91CC\u7684\u811A\u672C id\uFF08script_list \u53EF\u67E5\uFF09\u3002" };
3141
- const AUTO_UPDATE_NOTE = {
3142
- auto: "\u7528\u6237\u8BBE\u7F6E\u4E3A\u81EA\u52A8\u66F4\u65B0\uFF1A\u6709\u65B0\u7248\u672C\u65F6\u8FD0\u884C\u524D\u4F1A\u81EA\u52A8\u66F4\u65B0\uFF0C\u4F60\u4E5F\u53EF\u4EE5\u81EA\u5DF1\u51B3\u5B9A\u66F4\u65B0",
3143
- ask: "\u7528\u6237\u8BBE\u7F6E\u4E3A\u5148\u95EE\u518D\u66F4\u65B0\uFF1A\u6709\u65B0\u7248\u672C\u65F6\u8F6F\u4EF6\u4F1A\u5F39\u51FA\u63D0\u793A\u8BA9\u7528\u6237\u51B3\u5B9A\uFF1B\u53EA\u5728\u7528\u6237\u8981\u6C42\u65F6\u66F4\u65B0",
3144
- off: "\u7528\u6237\u8BBE\u7F6E\u4E3A\u4E0D\u81EA\u52A8\u66F4\u65B0\uFF1A\u53EA\u5728\u7528\u6237\u8981\u6C42\u65F6\u66F4\u65B0"
3145
- };
3146
- return [
3147
- tool({
3148
- name: TOOL_NAMES.list,
3149
- description: "\u5217\u51FA\u811A\u672C\u5E93\uFF1A\u5DF2\u5B89\u88C5\u6216\u5DF2\u5BFC\u5165\u7684\u811A\u672C\uFF08id\u3001\u7248\u672C\u3001\u76EE\u5F55\u3001\u8FD0\u884C\u73AF\u5883\u68C0\u67E5\u7ED3\u679C\uFF09\uFF0C\u4EE5\u53CA\u5185\u7F6E\u811A\u672C\u5305\u91CC\u8FD8\u6CA1\u5B89\u88C5\u7684\u811A\u672C\u3002\u7528\u6237\u63D0\u5230\u67D0\u4E2A\u811A\u672C\u65F6\u5148\u8C03\u7528\u5B83\u3002",
3150
- properties: {},
3151
- readOnly: true,
3152
- kind: "read",
3153
- title: () => "\u67E5\u770B\u811A\u672C\u5E93",
3154
- execute: async () => {
3155
- const { scripts, packs, toolsDir } = library.list();
3156
- const { autoUpdate } = await library.settings();
3157
- return {
3158
- toolsDir,
3159
- autoUpdate: AUTO_UPDATE_NOTE[autoUpdate],
3160
- scripts: scripts.map((s) => ({ id: s.id, name: s.name, source: s.source, version: s.source.kind === "local" ? s.localVersion?.version ?? "\uFF08\u8BA4\u4E0D\u51FA\uFF09" : s.current, channels: s.channels, dir: s.dir, family: s.family, versions: s.versions.map((v) => v.version), env: s.env === void 0 ? void 0 : { ok: s.env.ok, problems: s.env.items.filter((i) => i.status !== "ok" && i.status !== "unsupported").map((i) => `${i.label}: ${i.status}`) }, update: s.update })),
3161
- availablePacks: packs.filter((p) => !p.installed && p.error === void 0).map((p) => ({ id: p.id, name: p.name, repo: p.repo, description: p.description }))
3162
- };
3163
- }
3164
- }),
3165
- tool({
3166
- name: TOOL_NAMES.search,
3167
- description: "\u6309\u6E38\u620F\u540D\u6216\u811A\u672C\u540D\u641C\u7D22\u811A\u672C\uFF1AGitHub \u4ED3\u5E93\uFF08\u6309\u661F\u6570\u6392\u5E8F\uFF0C\u6807\u51FA\u6709\u5185\u7F6E\u811A\u672C\u5305\u7684\uFF09\uFF0C\u4EE5\u53CA Mirror\u9171 \u4E0A\u6709 Windows \u7248\u7684\u5DE5\u5177\uFF08\u8D44\u6E90 id \u53EF\u76F4\u63A5\u7528\u4E8E script_install \u7684 mirrorchyan\uFF1B\u67E5\u8BE2\u4E0D\u9700\u8981 CDK\uFF09\u3002",
3168
- properties: { query: { type: "string", description: '\u5173\u952E\u8BCD\uFF0C\u4F8B\u5982 "\u539F\u795E"\u3001"MAA \u660E\u65E5\u65B9\u821F" \u6216 "\u661F\u7A79\u94C1\u9053 \u81EA\u52A8\u5316"\u3002' } },
3169
- required: ["query"],
3170
- readOnly: true,
3171
- kind: "search",
3172
- title: (a) => `\u641C\u7D22\u811A\u672C\uFF1A${String(a["query"] ?? "")}`,
3173
- execute: async (args, exec) => {
3174
- const { query } = parse(external_exports.object({ query: external_exports.string().trim().min(1).max(200) }), args);
3175
- const [github, mirror] = await Promise.allSettled([library.search(query, exec.signal), library.searchMirror(query, exec.signal)]);
3176
- return {
3177
- github: github.status === "fulfilled" ? github.value.items : { error: errorOf(github.reason) },
3178
- mirrorchyan: mirror.status === "fulfilled" ? mirror.value.items.slice(0, 10).map((i) => ({ rid: i.rid, name: i.name, description: i.description.slice(0, 120), repo: i.repo, installed: i.installed })) : { error: errorOf(mirror.reason) }
3179
- };
3180
- }
3181
- }),
3182
- tool({
3183
- name: TOOL_NAMES.releases,
3184
- description: "\u67E5\u770B\u4E00\u4E2A GitHub \u4ED3\u5E93\u6700\u8FD1\u7684\u53D1\u5E03\u7248\u672C\u548C\u5176\u4E2D\u7684\u6587\u4EF6\uFF0C\u4EE5\u53CA\u9002\u5408\u672C\u673A\uFF08Windows x64\uFF09\u7684\u63A8\u8350\u6587\u4EF6\u3002",
3185
- properties: { repo, limit: { type: "integer", description: "\u6700\u591A\u8FD4\u56DE\u51E0\u4E2A\u7248\u672C\uFF0C\u9ED8\u8BA4 5\u3002" } },
3186
- required: ["repo"],
3187
- readOnly: true,
3188
- kind: "fetch",
3189
- title: (a) => `\u67E5\u770B\u53D1\u5E03\uFF1A${String(a["repo"] ?? "")}`,
3190
- execute: async (args, exec) => {
3191
- const a = parse(external_exports.object({ repo: GitHubRepo, limit: opt(external_exports.number().int().min(1).max(30)) }), args);
3192
- const result = await library.releases(a.repo, a.limit ?? 5, exec.signal);
3193
- return { ...result, releases: result.releases.map((r) => ({ tag: r.tag, prerelease: r.prerelease, publishedAt: r.publishedAt, suggestedAsset: r.suggestedAsset, assets: r.assets.map((x) => `${x.name} (${Math.round(x.size / 1024 / 1024)} MB)`) })) };
3194
- }
3195
- }),
3196
- tool({
3197
- name: TOOL_NAMES.install,
3198
- description: [
3199
- "\u4ECE GitHub\uFF08repo \u6216\u7528\u6237\u7ED9\u7684\u94FE\u63A5 url\uFF09\u6216 Mirror\u9171\uFF08mirrorchyan\uFF0C\u8D44\u6E90 id\uFF09\u5B89\u88C5\u811A\u672C\u5230\u7EDF\u4E00\u7684\u5DE5\u5177\u76EE\u5F55\uFF08tools/<id>/<\u7248\u672C>/\uFF09\uFF0C\u81EA\u52A8\u9009\u62E9\u9002\u5408\u672C\u673A\u7684\u6587\u4EF6\u3001\u6821\u9A8C\u3001\u89E3\u538B\uFF0C\u5E76\u68C0\u67E5\u8FD0\u884C\u73AF\u5883\u3002",
3200
- "\u7528\u6237\u8D34\u4E86 GitHub \u94FE\u63A5\u5C31\u539F\u6837\u653E\u8FDB url\uFF1A\u4ED3\u5E93\u4E3B\u9875\u3001\u53D1\u5E03\u9875\uFF08/releases/tag/\u2026\uFF09\u3001\u67D0\u4E2A\u6587\u4EF6\u7684\u4E0B\u8F7D\u94FE\u63A5\u3001\u5206\u652F\uFF08/tree/\u2026\uFF09\u3001.git \u5730\u5740\u3001\u52A0\u4E86\u4E0B\u8F7D\u52A0\u901F\u524D\u7F00\u7684\u94FE\u63A5\u90FD\u53EF\u4EE5\uFF0C\u7248\u672C\u548C\u6587\u4EF6\u4F1A\u4ECE\u94FE\u63A5\u91CC\u8BFB\u51FA\u6765\u3002",
3201
- "\u9ED8\u8BA4\u88C5\u6700\u65B0\u6B63\u5F0F\u7248\uFF1B\u4ED3\u5E93\u6CA1\u6709\u53D1\u5E03\u7248\u672C\u65F6\u88C5\u9ED8\u8BA4\u5206\u652F\u7684\u6E90\u7801\uFF08\u4E4B\u540E\u8DDF\u7740\u8FD9\u4E2A\u5206\u652F\u66F4\u65B0\uFF09\u2014\u2014\u8FD9\u7B49\u4E8E\u62C9\u4EE3\u7801\uFF0C\u53EA\u5728\u786E\u5B9E\u6CA1\u6709\u53D1\u5E03\u7248\u672C\u3001\u5E76\u4E14\u7528\u6237\u540C\u610F\u65F6\u8FD9\u6837\u88C5\u3002\u51E0\u4E2A\u6587\u4EF6\u90FD\u9002\u5408\u672C\u673A\u65F6\u4F1A\u8FD4\u56DE\u8BA9\u4F60\u5148\u95EE\u7528\u6237\u9009\u54EA\u4E00\u4E2A\u3002\u586B\u4E86 Mirror\u9171 CDK \u4E14\u811A\u672C\u5728 Mirror\u9171 \u53D1\u5E03\u65F6 GitHub \u5B89\u88C5\u4E5F\u4ECE Mirror\u9171 \u4E0B\u8F7D\u3002",
3202
- "\u4E0D\u5728\u5185\u7F6E\u811A\u672C\u5305\u6216\u5DF2\u77E5\u5217\u8868\u91CC\u7684\u4ED3\u5E93 / \u8D44\u6E90\u4F1A\u5148\u8BF7\u7528\u6237\u786E\u8BA4\u3002\u5DF2\u5B89\u88C5\u7684\u811A\u672C\u518D\u6B21\u8C03\u7528\u5373\u4E3A\u66F4\u65B0\u5230\u6307\u5B9A\u7248\u672C\u3002\u88C5\u597D\u540E\u8FD8\u6CA1\u6709\u811A\u672C\u5305\u7684\uFF0C\u6309\u7ED3\u679C\u91CC\u7684 next \u53BB\u5206\u6790\u3002"
3203
- ].join(""),
3204
- properties: {
3205
- repo,
3206
- url: { type: "string", description: "\u7528\u6237\u7ED9\u7684 GitHub \u94FE\u63A5\uFF0C\u539F\u6837\u4F20\u5165\uFF08\u4EE3\u66FF repo\uFF09\u3002" },
3207
- branch: { type: "string", description: "\u88C5\u8FD9\u4E2A\u5206\u652F\u7684\u6E90\u7801\u800C\u4E0D\u662F\u53D1\u5E03\u7248\u672C\uFF08\u94FE\u63A5\u662F /tree/<\u5206\u652F> \u65F6\u4F1A\u81EA\u52A8\u8BFB\u51FA\uFF09\u3002" },
3208
- mirrorchyan: { type: "string", description: "\u6539\u4ECE Mirror\u9171 \u5B89\u88C5\uFF1A\u8D44\u6E90 id\uFF08\u4F8B\u5982 BGI\u3001MAA\uFF09\uFF0C\u4EE3\u66FF repo\uFF1B\u9700\u8981\u7528\u6237\u586B\u8FC7 Mirror\u9171 CDK\u3002" },
3209
- tag: { type: "string", description: "\u6307\u5B9A\u7248\u672C\u6807\u7B7E\uFF1B\u7701\u7565\u4E3A\u6700\u65B0\u6B63\u5F0F\u7248\u3002" },
3210
- asset: { type: "string", description: "\u6307\u5B9A\u8981\u4E0B\u8F7D\u7684\u6587\u4EF6\u540D\uFF1B\u7701\u7565\u5219\u81EA\u52A8\u9009\u62E9\u3002" },
3211
- id: { type: "string", description: "\u811A\u672C id\uFF1B\u7701\u7565\u65F6\u4F7F\u7528\u811A\u672C\u5305 id \u6216\u4ED3\u5E93\u540D\u3002" }
3212
- },
3213
- timeoutMs: INSTALL_TIMEOUT_MS,
3214
- kind: "execute",
3215
- title: (a) => `\u5B89\u88C5\u811A\u672C\uFF1A${String(a["repo"] ?? (a["mirrorchyan"] === void 0 ? "" : `Mirror\u9171 ${String(a["mirrorchyan"])}`))}${a["tag"] === void 0 ? "" : ` ${String(a["tag"])}`}`,
3216
- execute: async (args, exec) => {
3217
- const raw = parse(external_exports.object({ repo: opt(external_exports.string().min(1).max(500)), url: opt(external_exports.string().min(1).max(1e3)), mirrorchyan: opt(MirrorRid), tag: opt(external_exports.string().min(1).max(200)), asset: opt(external_exports.string().min(1).max(300)), branch: opt(external_exports.string().min(1).max(200)), id: opt(ScriptId) }), args);
3218
- const linkText = raw.url ?? (raw.repo !== void 0 && !GitHubRepo.safeParse(raw.repo).success ? raw.repo : void 0);
3219
- const link = linkText === void 0 ? void 0 : parseGitHubLink(linkText);
3220
- if (linkText !== void 0 && link === void 0)
3221
- throw new Error(`\u770B\u4E0D\u51FA\u8FD9\u662F\u54EA\u4E2A GitHub \u4ED3\u5E93\uFF1A${linkText}\u3002\u53EA\u652F\u6301 GitHub\uFF08github.com\uFF09\u7684\u4ED3\u5E93\u94FE\u63A5\uFF1B\u5176\u4ED6\u7F51\u7AD9\u7684\u9879\u76EE\u5148\u4E0B\u8F7D\u5230\u672C\u5730\uFF0C\u518D\u7528 script_import \u5BFC\u5165`);
3222
- const a = {
3223
- ...raw,
3224
- repo: link?.repo ?? raw.repo,
3225
- tag: raw.tag ?? link?.tag,
3226
- asset: raw.asset ?? link?.asset,
3227
- branch: raw.branch ?? link?.branch
3228
- };
3229
- let started;
3230
- if (a.mirrorchyan !== void 0) {
3231
- if (a.repo !== void 0)
3232
- throw new Error("repo \u548C mirrorchyan \u53EA\u80FD\u7ED9\u4E00\u4E2A");
3233
- const found = await library.lookupMirror(a.mirrorchyan, exec.signal);
3234
- if (!library.isKnownMirror(found.rid)) {
3235
- await approve(exec, `\u4ECE Mirror\u9171 \u4E0B\u8F7D\u5E76\u5B89\u88C5\u8D44\u6E90 ${found.rid}\uFF08\u6700\u65B0 ${found.version}\uFF09\u3002\u8FD9\u4E2A\u8D44\u6E90\u4E0D\u5728\u5DF2\u77E5\u5217\u8868\u91CC\uFF0C\u8BF7\u786E\u8BA4\u5B83\u6765\u6E90\u53EF\u4FE1\u3002`);
3236
- }
3237
- started = library.install({ mirrorchyan: found, id: a.id, byAgent: true });
3238
- } else {
3239
- if (a.repo === void 0)
3240
- throw new Error("\u8BF7\u7ED9\u51FA repo\uFF08GitHub \u4ED3\u5E93\uFF09\u6216 mirrorchyan\uFF08Mirror\u9171 \u8D44\u6E90 id\uFF09");
3241
- const what = a.branch !== void 0 ? `${a.branch} \u5206\u652F\u7684\u6E90\u7801` : a.tag === void 0 ? "\u6700\u65B0\u53D1\u5E03\u7248\u672C\uFF08\u6CA1\u6709\u53D1\u5E03\u7248\u672C\u65F6\u88C5\u9ED8\u8BA4\u5206\u652F\u7684\u6E90\u7801\uFF09" : ` ${a.tag}${a.asset === void 0 ? "" : ` \u7684 ${a.asset}`}`;
3242
- if (!library.isKnownRepo(a.repo)) {
3243
- await approve(exec, `\u4ECE GitHub \u4ED3\u5E93 ${a.repo} \u4E0B\u8F7D\u5E76\u5B89\u88C5${what}\u3002\u8FD9\u4E2A\u4ED3\u5E93\u4E0D\u5728\u5185\u7F6E\u811A\u672C\u5305\u91CC\uFF0C\u8BF7\u786E\u8BA4\u5B83\u6765\u6E90\u53EF\u4FE1\uFF08${await library.repoFacts(a.repo, exec.signal)}\uFF09\u3002`);
3244
- }
3245
- started = library.install({ repo: a.repo, tag: a.tag, asset: a.asset, branch: a.branch, id: a.id, byAgent: true });
3246
- }
3247
- const job = await followJob(library, started, exec.signal);
3248
- const setup = setupOf(library, job.scriptId);
3249
- if (setup !== void 0)
3250
- return { ...describeJob(job), setup };
3251
- const info = job.phase === "done" ? library.get(job.scriptId) : void 0;
3252
- const next = info !== void 0 && info.packId === void 0 ? { next: `\u88C5\u597D\u4E86\uFF0C\u4F46\u8FD8\u6CA1\u6709\u811A\u672C\u5305\uFF0C\u8FD8\u4E0D\u80FD\u7528 script_run \u8FD0\u884C\u3002\u544A\u8BC9\u7528\u6237\u4E4B\u540E\uFF0C\u6309\u6280\u80FD script-analysis \u5206\u6790\u5B83\uFF08skill_focus \u8BBE\u6210 ${info.id}\uFF0C\u5148\u8BFB\u9879\u76EE\u6587\u6863\uFF1A\u4ED3\u5E93 README\u3001Wiki\u3001\u76EE\u5F55\u91CC\u7684\u8BF4\u660E\uFF0C\u518D\u770B\u4EE3\u7801\uFF09\uFF0C\u7528 pack_propose \u4FDD\u5B58\u811A\u672C\u5305\uFF08\u76F4\u63A5\u751F\u6548\uFF0C\u4E0D\u7528\u7528\u6237\u786E\u8BA4\uFF09\u3002` } : {};
3253
- return { ...describeJob(job), dir: info?.dir, env: info?.env, family: info?.family, ...next };
3254
- }
3255
- }),
3256
- tool({
3257
- name: TOOL_NAMES.update,
3258
- description: "\u68C0\u67E5\u5E76\u66F4\u65B0\u811A\u672C\u5230\u6700\u65B0\u53D1\u5E03\u7248\u672C\uFF08\u586B\u4E86 Mirror\u9171 CDK \u4E14\u811A\u672C\u5728 Mirror\u9171 \u53D1\u5E03\u65F6\u4ECE\u90A3\u91CC\u4E0B\u8F7D\uFF0C\u5426\u5219\u4ECE GitHub\uFF09\u3002\u5B89\u88C5\u7684\u811A\u672C\uFF1A\u65B0\u7248\u672C\u88C5\u5728\u65E7\u7248\u672C\u65C1\u8FB9\uFF0C\u914D\u7F6E\u6587\u4EF6\u5E26\u8FC7\u53BB\uFF0C\u65E7\u7248\u672C\u4FDD\u7559\u7528\u4E8E\u56DE\u6EDA\u3002\u672C\u5730\u5BFC\u5165\u7684\u811A\u672C\uFF1A\u5728\u5B83\u81EA\u5DF1\u7684\u76EE\u5F55\u91CC\u66F4\u65B0\uFF08\u4F1A\u5148\u8BF7\u7528\u6237\u786E\u8BA4\uFF09\uFF0C\u88AB\u66FF\u6362\u7684\u6587\u4EF6\u5148\u5907\u4EFD\uFF0C\u5DF2\u6709\u7684\u914D\u7F6E\u6587\u4EF6\u4E0D\u52A8\uFF0C\u53EF\u7528 script_rollback \u64A4\u9500\uFF1B\u6CA1\u6709\u66F4\u65B0\u6765\u6E90\u65F6\u7528 repo \u6307\u5B9A\u5B83\u7684 GitHub \u4ED3\u5E93\u3002\u53EA\u66F4\u65B0\u5B98\u65B9\u53D1\u5E03\uFF0C\u4E0D\u4FEE\u6539\u811A\u672C\u4EE3\u7801\u3002\u7528\u6237\u5728\u300C\u8BBE\u7F6E \u2192 \u6743\u9650\u300D\u628A\u300C\u811A\u672C\u6709\u65B0\u7248\u672C\u65F6\u300D\u8BBE\u4E3A\u300C\u81EA\u52A8\u66F4\u65B0\u300D\u65F6\u53EF\u4EE5\u81EA\u5DF1\u51B3\u5B9A\u66F4\u65B0\uFF1B\u8BBE\u4E3A\u300C\u5148\u95EE\u6211\u300D\u6216\u300C\u4E0D\u81EA\u52A8\u66F4\u65B0\u300D\u65F6\uFF0C\u53EA\u5728\u7528\u6237\u8981\u6C42\u65F6\u66F4\u65B0\u3002",
3259
- properties: {
3260
- id,
3261
- repo: { ...repo, description: "\u8BBE\u7F6E\u5B83\u7684 GitHub \u66F4\u65B0\u6E20\u9053\uFF08owner/repo\uFF09\uFF1B\u7701\u7565\u5219\u7528\u5DF2\u6709\u7684\u3002\u4ECE GitHub \u5B89\u88C5\u7684\u811A\u672C\u4E0D\u80FD\u6539\u3002" },
3262
- mirrorchyan: { type: "string", description: "\u8BBE\u7F6E\u5B83\u7684 Mirror\u9171 \u66F4\u65B0\u6E20\u9053\uFF08\u8D44\u6E90 id\uFF0C\u4F8B\u5982 BGI\uFF09\uFF1B\u7701\u7565\u5219\u7528\u5DF2\u6709\u7684\u3002" }
3263
- },
3264
- required: ["id"],
3265
- timeoutMs: INSTALL_TIMEOUT_MS,
3266
- kind: "execute",
3267
- title: (a) => `\u66F4\u65B0\u811A\u672C\uFF1A${String(a["id"] ?? "")}`,
3268
- execute: async (args, exec) => {
3269
- const a = parse(external_exports.object({ id: ScriptId, repo: opt(GitHubRepo), mirrorchyan: opt(MirrorRid) }), args);
3270
- let before = library.get(a.id);
3271
- if (a.repo !== void 0 && a.repo.toLowerCase() !== before.channels.github?.repo.toLowerCase()) {
3272
- await approve(exec, `\u628A ${before.name} \u7684 GitHub \u66F4\u65B0\u6E20\u9053\u8BBE\u4E3A ${a.repo}${library.isKnownRepo(a.repo) ? "" : "\uFF08\u4E0D\u5728\u5185\u7F6E\u811A\u672C\u5305\u91CC\uFF0C\u8BF7\u786E\u8BA4\u5B83\u5C31\u662F\u8FD9\u4E2A\u811A\u672C\u3001\u6765\u6E90\u53EF\u4FE1\uFF09"}\u3002`);
3273
- before = await library.setUpdateSource(a.id, { repo: a.repo });
3274
- }
3275
- if (a.mirrorchyan !== void 0 && a.mirrorchyan.toLowerCase() !== before.channels.mirrorchyan?.rid.toLowerCase()) {
3276
- const found = await library.lookupMirror(a.mirrorchyan, exec.signal);
3277
- await approve(exec, `\u628A ${before.name} \u7684 Mirror\u9171 \u66F4\u65B0\u6E20\u9053\u8BBE\u4E3A ${found.rid}\uFF08\u6700\u65B0 ${found.version}${found.name === void 0 ? "" : `\uFF0C${found.name}`}\uFF09${library.isKnownMirror(found.rid) ? "" : "\uFF1B\u8FD9\u4E2A\u8D44\u6E90\u4E0D\u5728\u5DF2\u77E5\u5217\u8868\u91CC\uFF0C\u8BF7\u786E\u8BA4\u5B83\u5C31\u662F\u8FD9\u4E2A\u811A\u672C"}\u3002`);
3278
- before = await library.setUpdateSource(a.id, { mirrorchyan: found });
3279
- }
3280
- if (before.source.kind === "local") {
3281
- const check = await library.checkUpdate(a.id, exec.signal);
3282
- if (!check.available)
3283
- return { ok: true, upToDate: true, version: check.current };
3284
- await approve(exec, `\u5728 ${before.source.path} \u91CC\u628A ${before.name} \u4ECE ${check.current ?? "\uFF08\u8BA4\u4E0D\u51FA\u7684\u7248\u672C\uFF09"} \u66F4\u65B0\u5230 ${check.latest}\u3002\u4F1A\u66FF\u6362\u8FD9\u4E2A\u76EE\u5F55\u91CC\u7684\u7A0B\u5E8F\u6587\u4EF6\uFF08\u5148\u5907\u4EFD\uFF0C\u53EF\u64A4\u9500\uFF09\uFF0C\u5DF2\u6709\u7684\u914D\u7F6E\u6587\u4EF6\u4E0D\u52A8\uFF1B\u66F4\u65B0\u524D\u8BF7\u5173\u95ED\u8FD9\u4E2A\u811A\u672C\u3002`);
3285
- }
3286
- const result = await library.update(a.id, exec.signal, { byAgent: true });
3287
- if (result.upToDate)
3288
- return { ok: true, upToDate: true, version: library.get(a.id).current };
3289
- const job = await followJob(library, result, exec.signal);
3290
- const setup = setupOf(library, a.id);
3291
- const review = library.get(a.id).packReview;
3292
- const packReview2 = review === void 0 ? {} : { packReview: `\u8FD9\u4E2A\u811A\u672C\u7684\u811A\u672C\u5305\u662F\u6309 ${review.from ?? "\u65E7\u7248\u672C"} \u5199\u7684\uFF0C\u73B0\u5728\u662F ${review.to}\uFF1A\u95EE\u7528\u6237\u8981\u4E0D\u8981\u68C0\u67E5\u811A\u672C\u5305\u3002\u7528\u6237\u540C\u610F\u5C31\u6309\u6280\u80FD script-analysis \u7684\u300C\u811A\u672C\u66F4\u65B0\u540E\u68C0\u67E5\u811A\u672C\u5305\u300D\u505A\uFF0C\u5148\u7528 script_changelog \u8BFB\u66F4\u65B0\u65E5\u5FD7\u3002` };
3293
- return setup === void 0 ? { ...describeJob(job), ...packReview2 } : { ...describeJob(job), setup, ...packReview2 };
3294
- }
3295
- }),
3296
- tool({
3297
- name: TOOL_NAMES.rollback,
3298
- description: "\u628A\u811A\u672C\u5207\u6362\u56DE\u5DF2\u5B89\u88C5\u7684\u53E6\u4E00\u4E2A\u7248\u672C\uFF08\u9ED8\u8BA4\u4E0A\u4E00\u4E2A\u7248\u672C\uFF09\u3002\u672C\u5730\u5BFC\u5165\u7684\u811A\u672C\uFF1A\u64A4\u9500\u4E0A\u6B21\u5728\u5B83\u76EE\u5F55\u91CC\u7684\u66F4\u65B0\uFF08\u6362\u56DE\u5907\u4EFD\u7684\u6587\u4EF6\uFF09\u3002",
3299
- properties: { id, version: { type: "string", description: "\u76EE\u6807\u7248\u672C\uFF1B\u7701\u7565\u4E3A\u4E0A\u4E00\u4E2A\u7248\u672C\u3002\u672C\u5730\u5BFC\u5165\u7684\u811A\u672C\u4E0D\u7528\u586B\u3002" } },
3300
- required: ["id"],
3301
- kind: "other",
3302
- title: (a) => `\u56DE\u6EDA\u811A\u672C\uFF1A${String(a["id"] ?? "")}`,
3303
- execute: async (args) => {
3304
- const a = parse(external_exports.object({ id: ScriptId, version: opt(external_exports.string()) }), args);
3305
- if (library.get(a.id).source.kind === "local") {
3306
- const info2 = await library.restore(a.id);
3307
- return { ok: true, id: info2.id, version: info2.localVersion?.version, dir: info2.dir };
3308
- }
3309
- const info = await library.rollback(a.id, a.version);
3310
- return { ok: true, id: info.id, version: info.current, dir: info.dir };
3311
- }
3312
- }),
3313
- tool({
3314
- name: TOOL_NAMES.setupRun,
3315
- description: `\u8FD0\u884C\u811A\u672C\u5B89\u88C5\u6216\u66F4\u65B0\u65F6\u4E0B\u8F7D\u5230\u7684\u5B89\u88C5\u7A0B\u5E8F\uFF08NSIS / Inno Setup / Kachina \u7684 setup.exe\uFF0C\u6216\u53EA\u88C5\u7740\u5B83\u7684\u538B\u7F29\u5305\uFF0C\u4F8B\u5982 Mirror\u9171 \u7684 BetterGI\uFF1B\u6709\u7684\u811A\u672C\u53EA\u53D1\u5E03\u8FD9\u79CD\u5B8C\u6574\u5305\uFF09\u3002quiet\uFF08\u9ED8\u8BA4 true\uFF09\uFF1A\u4E0D\u5F39\u7A97\u53E3\uFF0C\u9759\u9ED8\u88C5\u8FDB\u811A\u672C\u7684\u7248\u672C\u76EE\u5F55\u5E76\u7B49\u5B83\u88C5\u5B8C\uFF0C\u8FD4\u56DE\u9000\u51FA\u7801\u548C\u88C5\u51FA\u6765\u7684\u6587\u4EF6\uFF1Bfalse\uFF1A\u6253\u5F00\u5B89\u88C5\u7A0B\u5E8F\u81EA\u5DF1\u7684\u7A97\u53E3\uFF08\u5B89\u88C5\u4F4D\u7F6E\u5DF2\u9884\u5148\u586B\u597D\uFF09\u540E\u7ACB\u5373\u8FD4\u56DE\uFF0C\u518D\u7528 screen_capture / screen_tap \u4E00\u6B65\u6B65\u70B9\u5B8C\u3002\u88C5\u597D\u540E\u7528 ${TOOL_NAMES.import} \u5BFC\u5165\u90A3\u4E2A\u76EE\u5F55\uFF08path \u586B\u8FD4\u56DE\u7684 dir\uFF0Cid \u586B\u8FD9\u4E2A\u811A\u672C\u7684 id\uFF09\uFF0C\u5B89\u88C5\u624D\u7B97\u5B8C\u6210\u3002\u53EA\u80FD\u8FD0\u884C\u811A\u672C\u5E93\u4E0B\u8F7D\u7684\u5B89\u88C5\u7A0B\u5E8F\u3002`,
3316
- properties: {
3317
- id: { type: "string", description: "\u811A\u672C id\uFF08script_install / script_update \u7684\u7ED3\u679C\u91CC\u6709\uFF09\u3002" },
3318
- quiet: { type: "boolean", description: "\u9759\u9ED8\u5B89\u88C5\u5E76\u7B49\u5F85\u7ED3\u675F\uFF1B\u9ED8\u8BA4 true\u3002\u9759\u9ED8\u5931\u8D25\u6216\u9700\u8981\u5728\u754C\u9762\u91CC\u9009\u62E9\u65F6\u7528 false\u3002" }
3319
- },
3320
- required: ["id"],
3321
- timeoutMs: 35 * 6e4,
3322
- kind: "execute",
3323
- title: (a) => `\u8FD0\u884C\u5B89\u88C5\u7A0B\u5E8F\uFF1A${String(a["id"] ?? "")}${a["quiet"] === false ? "\uFF08\u6253\u5F00\u7A97\u53E3\uFF09" : ""}`,
3324
- execute: async (args, exec) => {
3325
- const a = parse(external_exports.object({ id: ScriptId, quiet: opt(external_exports.boolean()) }), args);
3326
- const quiet = a.quiet ?? true;
3327
- const ran = await library.runSetup(a.id, { quiet, signal: exec.signal });
3328
- const next = !quiet ? `\u7528 screen_capture \u770B\u5B89\u88C5\u7A97\u53E3\uFF0C\u4E00\u6B65\u6B65\u70B9\u5B8C\uFF08\u5B89\u88C5\u4F4D\u7F6E\u4FDD\u6301 ${ran.dir}\uFF0C\u4E0D\u52FE\u9009\u300C\u7ACB\u5373\u8FD0\u884C\u300D\uFF09\uFF1B\u88C5\u5B8C\u540E\u7528 ${TOOL_NAMES.import} \u5BFC\u5165 ${ran.dir}` : ran.exitCode === 0 && (ran.files ?? 0) > 0 ? `\u7528 ${TOOL_NAMES.import}\uFF08path=${ran.dir}\uFF0Cid=${a.id}\uFF09\u5BFC\u5165\uFF0C\u5B89\u88C5\u5C31\u5B8C\u6210\u4E86` : `\u9759\u9ED8\u5B89\u88C5\u6CA1\u6709\u6210\u529F\uFF1A\u53EF\u4EE5\u7528 quiet=false \u6253\u5F00\u5B89\u88C5\u7A97\u53E3\u624B\u52A8\u70B9\u5B8C`;
3329
- return { ok: !quiet || ran.exitCode === 0 && (ran.files ?? 0) > 0, ...ran, next };
3330
- }
3331
- }),
3332
- tool({
3333
- name: TOOL_NAMES.import,
3334
- description: `\u628A\u7528\u6237\u7535\u8111\u4E0A\u5DF2\u6709\u7684\u811A\u672C\u76EE\u5F55\u767B\u8BB0\u5230\u811A\u672C\u5E93\uFF08\u539F\u5730\u4F7F\u7528\uFF0C\u4E0D\u79FB\u52A8\u3001\u4E0D\u590D\u5236\u3001\u4E0D\u4FEE\u6539\uFF09\u3002\u4F1A\u6309\u5185\u7F6E\u811A\u672C\u5305\u81EA\u52A8\u8BC6\u522B\u662F\u54EA\u4E2A\u811A\u672C\u3002\u7528 ${TOOL_NAMES.setupRun} \u88C5\u597D\u7684\u76EE\u5F55\u4E5F\u7528\u5B83\u5BFC\u5165\uFF08id \u586B\u90A3\u4E2A\u811A\u672C\u7684 id\uFF09\uFF0C\u8FD9\u6837\u5B89\u88C5\u6216\u66F4\u65B0\u624D\u7B97\u5B8C\u6210\uFF0C\u7248\u672C\u548C\u66F4\u65B0\u6E20\u9053\u4F1A\u63A5\u4E0A\u3002`,
3335
- properties: {
3336
- path: { type: "string", description: "\u811A\u672C\u6240\u5728\u76EE\u5F55\u7684\u7EDD\u5BF9\u8DEF\u5F84\u3002" },
3337
- id: { type: "string", description: "\u811A\u672C id\uFF1B\u7701\u7565\u65F6\u81EA\u52A8\u751F\u6210\u3002" },
3338
- name: { type: "string", description: "\u663E\u793A\u540D\u79F0\u3002" },
3339
- pack_id: { type: "string", description: "\u6307\u5B9A\u7528\u54EA\u4E2A\u811A\u672C\u5305\u63CF\u8FF0\u5B83\uFF1B\u7701\u7565\u5219\u81EA\u52A8\u8BC6\u522B\u3002" }
3340
- },
3341
- required: ["path"],
3342
- kind: "read",
3343
- title: (a) => `\u5BFC\u5165\u672C\u5730\u811A\u672C\uFF1A${String(a["path"] ?? "")}`,
3344
- execute: async (args) => {
3345
- const a = parse(external_exports.object({ path: external_exports.string().trim().min(1).max(1e3), id: opt(ScriptId), name: opt(external_exports.string().trim().min(1).max(100)), pack_id: opt(ScriptId) }), args);
3346
- const info = await library.import({ path: a.path, id: a.id, name: a.name, packId: a.pack_id });
3347
- return { ok: true, id: info.id, name: info.name, pack: info.packId, family: info.family, probe: info.probe, env: info.env };
3348
- }
3349
- }),
3350
- tool({
3351
- name: TOOL_NAMES.remove,
3352
- description: "\u4ECE\u811A\u672C\u5E93\u79FB\u9664\u811A\u672C\u3002delete_files \u4E3A true \u65F6\u540C\u65F6\u5220\u9664\u5B89\u88C5\u5668\u88C5\u7684\u6240\u6709\u7248\u672C\uFF08\u4F1A\u5148\u8BF7\u7528\u6237\u786E\u8BA4\uFF09\uFF1B\u5BFC\u5165\u7684\u672C\u5730\u76EE\u5F55\u6C38\u8FDC\u4E0D\u4F1A\u88AB\u5220\u9664\u3002",
3353
- properties: { id, delete_files: { type: "boolean", description: "\u540C\u65F6\u5220\u9664\u5DF2\u5B89\u88C5\u7684\u6587\u4EF6\u3002" } },
3354
- required: ["id"],
3355
- kind: "delete",
3356
- title: (a) => `\u79FB\u9664\u811A\u672C\uFF1A${String(a["id"] ?? "")}`,
3357
- execute: async (args, exec) => {
3358
- const a = parse(external_exports.object({ id: ScriptId, delete_files: opt(external_exports.boolean()) }), args);
3359
- const info = library.get(a.id);
3360
- if (a.delete_files === true && info.source.kind === "github") {
3361
- await approve(exec, `\u5220\u9664 ${info.name} \u7684\u6240\u6709\u5DF2\u5B89\u88C5\u7248\u672C\uFF08${info.versions.map((v) => v.version).join("\u3001")}\uFF09\u3002`);
3362
- }
3363
- await library.remove(a.id, a.delete_files === true);
3364
- return { ok: true };
3365
- }
3366
- }),
3367
- tool({
3368
- name: TOOL_NAMES.envCheck,
3369
- description: "\u68C0\u67E5\u811A\u672C\u8FD0\u884C\u6240\u9700\u7684\u73AF\u5883\uFF08\u4F8B\u5982 .NET \u684C\u9762\u8FD0\u884C\u65F6\u3001VC++ \u8FD0\u884C\u5E93\u3001ADB\u3001Python\uFF09\u5728\u672C\u673A\u662F\u5426\u6EE1\u8DB3\uFF0C\u5E76\u7ED9\u51FA\u4FEE\u590D\u65B9\u5F0F\u3002",
3370
- properties: { id },
3371
- required: ["id"],
3372
- readOnly: true,
3373
- kind: "read",
3374
- title: (a) => `\u68C0\u67E5\u8FD0\u884C\u73AF\u5883\uFF1A${String(a["id"] ?? "")}`,
3375
- execute: async (args) => library.envCheck(parse(external_exports.object({ id: ScriptId }), args).id)
3376
- }),
3377
- tool({
3378
- name: TOOL_NAMES.envFix,
3379
- description: "\u4FEE\u590D\u4E00\u9879\u8FD0\u884C\u73AF\u5883\u4F9D\u8D56\uFF1A\u81EA\u52A8\u4E0B\u8F7D\u5B98\u65B9\u7EC4\u4EF6\uFF08\u4F8B\u5982 ADB\uFF09\u6216\u8FD0\u884C\u5B98\u65B9\u5B89\u88C5\u7A0B\u5E8F\uFF08\u4F8B\u5982 .NET\u3001VC++ \u8FD0\u884C\u5E93\uFF0C\u4F1A\u5148\u8BF7\u7528\u6237\u786E\u8BA4\uFF0C\u5E76\u5F39\u51FA\u7CFB\u7EDF\u7BA1\u7406\u5458\u6388\u6743\uFF09\u3002kind \u53D6\u81EA script_env_check \u7ED3\u679C\u3002",
3380
- properties: { id, kind: { type: "string", description: "\u4F9D\u8D56\u79CD\u7C7B\uFF0C\u4F8B\u5982 vcredist\u3001dotnet-desktop-runtime\u3001adb\u3002" } },
3381
- required: ["id", "kind"],
3382
- timeoutMs: INSTALL_TIMEOUT_MS,
3383
- kind: "execute",
3384
- title: (a) => `\u4FEE\u590D\u8FD0\u884C\u73AF\u5883\uFF1A${String(a["id"] ?? "")} / ${String(a["kind"] ?? "")}`,
3385
- execute: async (args, exec) => {
3386
- const a = parse(external_exports.object({ id: ScriptId, kind: external_exports.string().min(1).max(64) }), args);
3387
- const plan = await library.envFixPlan(a.id, a.kind);
3388
- if (plan === void 0)
3389
- return { ok: true, message: "\u8FD9\u4E00\u9879\u5DF2\u7ECF\u6EE1\u8DB3\uFF0C\u65E0\u9700\u5904\u7406" };
3390
- if (plan.kind === "manual")
3391
- return { ok: false, manual: true, message: plan.description };
3392
- if (plan.kind === "run-installer")
3393
- await approve(exec, `${plan.description}\uFF1A${plan.url}\uFF08Windows \u4F1A\u5F39\u51FA\u7BA1\u7406\u5458\u6388\u6743\uFF09`);
3394
- const job = await followJob(library, library.envFix(a.id, a.kind, plan), exec.signal);
3395
- return job.phase === "done" ? { ok: true } : { ok: false, phase: job.phase, error: job.error };
3396
- }
3397
- })
3398
- ];
3399
- }
3400
-
3401
- // packages/script-registry/lib/setup-handoff.js
3402
- var SETUP_TIMEOUT_MS = 60 * 6e4;
3403
- function setupHandOff(ctx, library, log) {
3404
- return async (setup) => {
3405
- const sessions = ctx.get("sessionController");
3406
- if (sessions === void 0)
3407
- throw new Error("agent \u73B0\u5728\u4E0D\u53EF\u7528\uFF08\u4F1A\u8BDD\u670D\u52A1\u6CA1\u6709\u52A0\u8F7D\uFF09");
3408
- const conversations = sessionConversations(sessions, () => ctx.get("adgGateway")?.workspaceDir(), (sessionId2, focus) => ctx.get("adgGateway")?.skillScope.setFocus(sessionId2, focus) ?? Promise.resolve(), () => ctx.get("adgGateway"));
3409
- const sessionId = await conversations.home(SCRIPT_ROLE.id, { focus: { scripts: [setup.scriptId] } });
3410
- log.info(`${setup.scriptId}: setup program handed to session ${sessionId}`);
3411
- await library().setSetupAgent(setup.scriptId, { sessionId, state: "running" });
3412
- const failed = async (reason) => {
3413
- if (library().pendingSetup(setup.scriptId)?.agent?.sessionId !== sessionId)
3414
- return;
3415
- log.warn(`${setup.scriptId}: setup session ${sessionId}: ${reason}`);
3416
- await library().setSetupAgent(setup.scriptId, { sessionId, state: "failed", reason });
3417
- };
3418
- void (async () => {
3419
- const prompt = [
3420
- `\u7528\u6237\u5728\u811A\u672C\u5E93\u91CC${setup.update ? "\u66F4\u65B0" : "\u5B89\u88C5"}\u300C${setup.name}\u300D${setup.version}\uFF0C\u4E0B\u8F7D\u5230\u7684\u662F ${SETUP_NAMES[setup.kind]} \u5B89\u88C5\u7A0B\u5E8F\uFF08${setup.file}\uFF09\uFF0C\u4E0D\u662F\u538B\u7F29\u5305\uFF0C\u9700\u8981\u4F60\u628A\u5B83\u88C5\u597D\uFF1A`,
3421
- `1. \u7528 ${TOOL_NAMES.setupRun}\uFF08id=${setup.scriptId}\uFF09\u8FD0\u884C\u5B83\uFF0C\u5148\u7528\u9ED8\u8BA4\u7684\u9759\u9ED8\u5B89\u88C5\uFF1A\u4F1A\u88C5\u8FDB ${setup.dir}\uFF0C\u7B49\u5B83\u7ED3\u675F\uFF1B`,
3422
- `2. \u9759\u9ED8\u5B89\u88C5\u5931\u8D25\u6216\u88C5\u51FA\u6765\u7684\u76EE\u5F55\u662F\u7A7A\u7684\uFF0C\u5C31\u7528 ${TOOL_NAMES.setupRun}\uFF08quiet=false\uFF09\u6253\u5F00\u5B89\u88C5\u7A97\u53E3\uFF0C\u7528 screen_capture / screen_tap \u4E00\u6B65\u6B65\u70B9\u5B8C\uFF1A\u5B89\u88C5\u4F4D\u7F6E\u4FDD\u6301 ${setup.dir}\uFF0C\u4E0D\u52FE\u9009\u300C\u7ACB\u5373\u8FD0\u884C\u300D\uFF0C\u5176\u4ED6\u4FDD\u6301\u9ED8\u8BA4\uFF1B\u9047\u5230\u8981\u7BA1\u7406\u5458\u6388\u6743\u7684\u5F39\u7A97\u5C31\u505C\u4E0B\u544A\u8BC9\u7528\u6237\uFF1B`,
3423
- `3. \u88C5\u597D\u540E\u7528 ${TOOL_NAMES.import}\uFF08path=${setup.dir}\uFF0Cid=${setup.scriptId}\uFF09\u5BFC\u5165\uFF0C\u811A\u672C\u5E93\u4F1A\u628A\u5B83\u8BB0\u4E3A ${setup.version}${setup.update ? "" : "\uFF0C\u5E76\u63A5\u4E0A\u66F4\u65B0\u6E20\u9053"}\uFF1B`,
3424
- "4. \u6700\u540E\u7528\u4E00\u4E24\u53E5\u8BDD\u544A\u8BC9\u7528\u6237\u7ED3\u679C\uFF08\u88C5\u5728\u54EA\u3001\u662F\u5426\u6210\u529F\uFF09\u3002",
3425
- "\u4E0D\u8981\u8FD0\u884C\u88C5\u597D\u7684\u7A0B\u5E8F\uFF0C\u4E0D\u8981\u6539\u5B83\u7684\u6587\u4EF6\uFF0C\u4E0D\u8981\u5411\u7528\u6237\u63D0\u95EE\uFF1B\u505A\u4E0D\u5230\u65F6\u8BF4\u660E\u5361\u5728\u54EA\u4E00\u6B65\u3002"
3426
- ].join("\n");
3427
- const answer = await conversations.ask(sessionId, taskMessage("\u4F60", `\u5B89\u88C5\u811A\u672C\uFF1A${setup.name}`, prompt), AbortSignal.timeout(SETUP_TIMEOUT_MS));
3428
- const cut = /^(这一轮没有完成:(.*))$/s.exec(answer.trim());
3429
- await failed(cut !== null ? cut[1] : "agent \u505C\u4E0B\u4E86\uFF0C\u4F46\u6CA1\u6709\u5BFC\u5165\u88C5\u597D\u7684\u76EE\u5F55");
3430
- })().catch((error) => failed(error instanceof Error ? error.message : String(error)));
3431
- return sessionId;
3432
- };
3433
- }
3434
-
3435
- // packages/script-registry/lib/index.js
3436
- var UPDATE_CHECK_FIRST_MS = 2 * 6e4;
3437
- var UPDATE_CHECK_EVERY_MS = 6 * 60 * 6e4;
3438
- var ConfigSchema = external_exports.object({
3439
- /** Where installed scripts live: `<toolsDir>/<id>/<version>/`. */
3440
- toolsDir: external_exports.string().min(1),
3441
- /** Where scripts were installed before `toolsDir` moved: still the library's (library.ts). */
3442
- formerToolsDirs: external_exports.array(external_exports.string().min(1)).optional(),
3443
- /** Library state (`scripts.json`) and the user's packs (`packs/`). */
3444
- dataDir: external_exports.string().min(1),
3445
- /** Built-in pack directories; default: the `@adg/packs` package. */
3446
- packDirs: external_exports.array(external_exports.string().min(1)).optional(),
3447
- /** Install settings used until the user changes them in the UI. */
3448
- defaults: InstallSettings.partial().optional()
3449
- });
3450
- var AdgScripts = class extends Service {
3451
- library;
3452
- /** The skills repository (技能库). */
3453
- skillHub;
3454
- /** Settles once the library state and packs are loaded. */
3455
- ready;
3456
- /** 优化脚本: offered after enough clean runs (the runner reports them to `library.ranClean`) or an update. */
3457
- optimizer;
3458
- constructor(ctx, config) {
3459
- super(ctx, "adgScripts");
3460
- const parsed = ConfigSchema.safeParse(config);
3461
- if (!parsed.success)
3462
- throw new Error(`adg-script-registry: invalid config: ${parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")}`);
3463
- const spec = parsed.data;
3464
- const log = ctx.logger("adg-scripts");
3465
- const ref = (value) => value;
3466
- const handOff = setupHandOff(ctx, () => this.library, { info: (message) => log.info(message), warn: (message) => log.warn(message) });
3467
- const review = packReview(ctx, () => this.library, { warn: (message) => log.warn(message) });
3468
- const optimizer2 = optimizer(ctx, () => this.library, { warn: (message) => log.warn(message) });
3469
- this.optimizer = optimizer2;
3470
- this.library = new ScriptLibrary({
3471
- toolsDir: spec.toolsDir,
3472
- ...spec.formerToolsDirs === void 0 ? {} : { formerToolsDirs: spec.formerToolsDirs },
3473
- dataDir: spec.dataDir,
3474
- packDirs: spec.packDirs ?? [PACKS_DIR],
3475
- ...spec.defaults === void 0 ? {} : { defaults: stripUndefined2(spec.defaults) },
3476
- credential: async (name) => (await ctx.get("credentials")?.resolve(ref(name)))?.value,
3477
- credentialConfigured: async (name) => (await ctx.get("credentials")?.describe(ref(name)))?.configured ?? false,
3478
- onChanged: (id) => ctx.get("adgGateway")?.broadcast("scripts/changed", id === void 0 ? {} : { id }),
3479
- onJob: (job) => ctx.get("adgGateway")?.broadcast("scripts/job", job),
3480
- onSetup: handOff,
3481
- onPackReview: (script) => review.ask(script),
3482
- onOptimize: (script) => optimizer2.ask(script),
3483
- log: { info: (message) => log.info(message), warn: (message) => log.warn(message) }
3484
- });
3485
- const library = this.library;
3486
- this.ready = library.start();
3487
- this.ready.then(() => log.info(`script library ready: ${library.list().scripts.length} script(s), tools in ${library.toolsDir}`), (error) => log.error(`script library failed to load: ${error instanceof Error ? error.message : String(error)}`));
3488
- ctx.effect(() => () => library.dispose(), "adg-scripts jobs");
3489
- ctx.effect(() => {
3490
- const stop = new AbortController();
3491
- const check = () => {
3492
- void this.ready.then(() => library.checkUpdates(stop.signal), () => {
3493
- });
3494
- };
3495
- const first = setTimeout(check, UPDATE_CHECK_FIRST_MS);
3496
- const every = setInterval(check, UPDATE_CHECK_EVERY_MS);
3497
- first.unref();
3498
- every.unref();
3499
- return () => {
3500
- stop.abort();
3501
- clearTimeout(first);
3502
- clearInterval(every);
3503
- };
3504
- }, "adg-scripts update checks");
3505
- const approve = async (exec, reason) => {
3506
- const approval = ctx.get("approval");
3507
- if (approval === void 0 || exec.agent === void 0)
3508
- throw new Error("\u8FD9\u4E2A\u64CD\u4F5C\u9700\u8981\u7528\u6237\u6279\u51C6\uFF0C\u4F46\u5F53\u524D\u6CA1\u6709\u53EF\u7528\u7684\u5BA1\u6279\u6E20\u9053");
3509
- const outcome = await approval.request({ agent: exec.agent, toolName: exec.name, callId: exec.callId, reason, signal: exec.signal });
3510
- if (outcome !== "allowed-once")
3511
- throw new Error(outcome === "rejected" ? "\u7528\u6237\u62D2\u7EDD\u4E86\u8FD9\u4E2A\u64CD\u4F5C" : `\u6CA1\u6709\u5F97\u5230\u7528\u6237\u6279\u51C6\uFF08${outcome}\uFF09`);
3512
- };
3513
- ctx.inject(["adgGateway"], (gateway) => gateway.adgGateway.agentPart("adg-script-registry tools", (agent) => {
3514
- const registered = [];
3515
- for (const tool2 of scriptTools(library, approve)) {
3516
- registered.push(agent.tools.register({ ...tool2, execute: async (args, exec) => {
3517
- await this.ready;
3518
- await ctx.get("adgGateway")?.guardTool(exec);
3519
- return tool2.execute(args, exec);
3520
- } }));
3521
- }
3522
- return () => {
3523
- for (const dispose of registered)
3524
- dispose();
3525
- };
3526
- }));
3527
- const summaries = scriptSummaries(ctx, library, { warn: (message) => log.warn(message) });
3528
- ctx.inject(["adgGateway"], (scoped) => {
3529
- scoped.effect(() => scoped.adgGateway.role(SCRIPT_ROLE), "adg-script-registry role");
3530
- scoped.adgGateway.skillScope.resolveScripts((id) => {
3531
- let pack;
3532
- try {
3533
- pack = library.packOf(id);
3534
- } catch {
3535
- pack = library.pack(id);
3536
- }
3537
- const game = pack?.manifest.game?.name;
3538
- return { aliases: pack === void 0 ? [] : [pack.manifest.id], games: game === void 0 ? [] : [game] };
3539
- });
3540
- const capability = scriptsCapability(library, summaries, async (id) => {
3541
- const setup = library.pendingSetup(id);
3542
- if (setup === void 0)
3543
- throw new Error(`${id} \u6CA1\u6709\u7B49\u5F85\u8FD0\u884C\u7684\u5B89\u88C5\u7A0B\u5E8F`);
3544
- return handOff(setup);
3545
- }, review, optimizer2, new ExeIcons(join6(spec.dataDir, "icons")));
3546
- scoped.adgGateway.register({
3547
- ...capability,
3548
- methods: Object.fromEntries(Object.entries(capability.methods).map(([name, handler]) => [name, async (params, call) => {
3549
- await this.ready;
3550
- return handler(params, call);
3551
- }]))
3552
- });
3553
- });
3554
- this.skillHub = startSkillHub(ctx, library, this.ready, approve, { info: (message) => log.info(message), warn: (message) => log.warn(message) });
3555
- log.debug(`tools: ${Object.values(TOOL_NAMES).join(", ")}`);
3556
- }
3557
- };
3558
- function stripUndefined2(value) {
3559
- return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== void 0));
3560
- }
3561
- var lib_default = AdgScripts;
3562
30
  export {
3563
31
  AdgScripts,
32
+ MCP_TOOL_NAMES,
3564
33
  OPTIMIZE_AFTER_RUNS,
34
+ ScriptIntegrations,
3565
35
  ScriptLibrary,
36
+ ScriptMcp,
3566
37
  SkillHub,
3567
38
  TOOL_NAMES,
3568
39
  lib_default as default,
40
+ discoverMcp,
41
+ discoverSkills,
3569
42
  frontmatter,
3570
43
  loadPacks,
44
+ mcpEndpoints,
3571
45
  packForRepo,
46
+ parseMcpConfig,
3572
47
  readSkills
3573
48
  };