dsh-multigameassistant 2.0.4 → 2.1.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 (40) hide show
  1. package/cordis.patch.yml +178 -4
  2. package/lib/analyzer.js +135 -26
  3. package/lib/browser.js +279 -0
  4. package/lib/{chunk-XHP3SLMO.js → chunk-77ZYHRN7.js} +292 -6
  5. package/lib/{chunk-UOVFYP7C.js → chunk-EOWM56PA.js} +398 -58
  6. package/lib/chunk-FH64SAZU.js +605 -0
  7. package/lib/{chunk-IZENRXQ6.js → chunk-MEKSHT6V.js} +1797 -575
  8. package/lib/chunk-RESS7WVY.js +157 -0
  9. package/lib/{chunk-SA72K6M2.js → chunk-SHTX4AGU.js} +1 -3572
  10. package/lib/{chunk-4PNYIZVU.js → chunk-TWUATN5X.js} +13 -9
  11. package/lib/chunk-V2X4PLF5.js +3730 -0
  12. package/lib/emulator.js +5 -3
  13. package/lib/feishu.js +8 -5
  14. package/lib/game-intel.js +91 -8
  15. package/lib/gateway.js +9 -5
  16. package/lib/guard.js +5 -3
  17. package/lib/intervene.js +62 -17
  18. package/lib/low-context.js +71 -87
  19. package/lib/monitor.js +90 -10
  20. package/lib/notify.js +6 -4
  21. package/lib/orchestrator.js +97 -27
  22. package/lib/packs/maa/adg.script.yaml +119 -1
  23. package/lib/packs/maaend/adg.script.yaml +74 -4
  24. package/lib/packs/march7th/adg.script.yaml +116 -0
  25. package/lib/qqbot.js +8 -5
  26. package/lib/runner.js +18 -5
  27. package/lib/scheduler.js +4 -2
  28. package/lib/script-registry.js +203 -214
  29. package/package.json +5 -4
  30. package/skills/pipeline-planning.md +8 -5
  31. package/skills/script-analysis.md +70 -10
  32. package/skills/web-reading.md +2 -0
  33. package/web/assets/index-C-csjWiw.js +244 -0
  34. package/web/assets/index-C-csjWiw.js.map +1 -0
  35. package/web/assets/index-CjtVfcDS.css +1 -0
  36. package/web/index.html +2 -2
  37. package/lib/chunk-CCAB6XXZ.js +0 -34
  38. package/web/assets/index-BqeCz6LB.css +0 -1
  39. package/web/assets/index-CCaVm9ks.js +0 -242
  40. package/web/assets/index-CCaVm9ks.js.map +0 -1
@@ -1,14 +1,17 @@
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
3
  globToRegExp,
4
+ guideView,
4
5
  renderTask,
5
6
  require_dist
6
- } from "./chunk-XHP3SLMO.js";
7
+ } from "./chunk-77ZYHRN7.js";
7
8
  import {
8
9
  RUNS_CAPABILITY,
9
- ScriptId,
10
+ ScriptId
11
+ } from "./chunk-V2X4PLF5.js";
12
+ import {
10
13
  external_exports
11
- } from "./chunk-SA72K6M2.js";
14
+ } from "./chunk-SHTX4AGU.js";
12
15
  import {
13
16
  __toESM
14
17
  } from "./chunk-2UFLGPDY.js";
@@ -18,8 +21,8 @@ import { Service } from "@deepseek-ai/cordis";
18
21
 
19
22
  // packages/runner/lib/runs.js
20
23
  import { spawn as spawn2, execFile as execFile4 } from "node:child_process";
21
- import { appendFile, mkdir as mkdir4, readdir as readdir3, readFile as readFile4, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
22
- import { basename as basename3, join as join5 } from "node:path";
24
+ import { appendFile, mkdir as mkdir4, readdir as readdir4, readFile as readFile5, rename as rename3, rm as rm3, stat as stat4, writeFile as writeFile4 } from "node:fs/promises";
25
+ import { basename as basename3, join as join6 } from "node:path";
23
26
 
24
27
  // packages/runner/lib/choices.js
25
28
  var import_yaml = __toESM(require_dist(), 1);
@@ -1062,7 +1065,13 @@ async function locateGame(options) {
1062
1065
  for (const path of probe.running)
1063
1066
  if (basename2(path).toLowerCase() === want)
1064
1067
  add(path, "\u6E38\u620F\u6B63\u5728\u8FD0\u884C");
1068
+ for (const { path, source } of probe.known ?? [])
1069
+ if (basename2(path).toLowerCase() === want)
1070
+ add(path, source);
1065
1071
  const seeds = [];
1072
+ for (const dir of probe.installs ?? [])
1073
+ if (dir.trim() !== "" && matches2(dir))
1074
+ seeds.push({ dir: dir.trim(), source: "\u6E38\u620F\u542F\u52A8\u5668\u8BB0\u4E0B\u7684\u5B89\u88C5\u76EE\u5F55" });
1066
1075
  for (const entry of probe.entries) {
1067
1076
  if (!matches2(entry.name))
1068
1077
  continue;
@@ -1078,8 +1087,12 @@ async function locateGame(options) {
1078
1087
  continue;
1079
1088
  if (basename2(link.target).toLowerCase() === want)
1080
1089
  add(link.target, `\u5FEB\u6377\u65B9\u5F0F\u300C${link.name}\u300D`);
1081
- else
1090
+ else {
1082
1091
  seeds.push({ dir: dirname4(link.target), source: `\u5FEB\u6377\u65B9\u5F0F\u300C${link.name}\u300D\u6240\u5728\u7684\u76EE\u5F55` });
1092
+ const above = dirname4(dirname4(link.target));
1093
+ if (above !== dirname4(above) && matches2(basename2(above)))
1094
+ seeds.push({ dir: above, source: `\u5FEB\u6377\u65B9\u5F0F\u300C${link.name}\u300D\u7684\u4E0A\u4E00\u7EA7\u76EE\u5F55` });
1095
+ }
1083
1096
  }
1084
1097
  const budget = { folders: options.maxFolders ?? 4e4, until: Date.now() + (options.maxMs ?? 2e4) };
1085
1098
  const walk = async (dir, depth, matched, source) => {
@@ -1126,14 +1139,44 @@ function drives() {
1126
1139
  var PROBE = `
1127
1140
  $ErrorActionPreference = 'SilentlyContinue'
1128
1141
  [Console]::OutputEncoding = [Text.Encoding]::UTF8
1129
- $stem = [IO.Path]::GetFileNameWithoutExtension($env:ADG_GAME_EXE)
1142
+ $exe = $env:ADG_GAME_EXE
1143
+ $stem = [IO.Path]::GetFileNameWithoutExtension($exe)
1130
1144
  $running = @(Get-Process -Name $stem | ForEach-Object { $_.Path } | Where-Object { $_ })
1131
1145
  $keys = 'HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*', 'HKLM:\\Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*', 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'
1132
1146
  $entries = @(Get-ItemProperty $keys | Where-Object { $_.DisplayName } | ForEach-Object { @{ name = [string]$_.DisplayName; location = [string]$_.InstallLocation; icon = [string]$_.DisplayIcon } })
1133
1147
  $shell = New-Object -ComObject WScript.Shell
1134
1148
  $dirs = @([Environment]::GetFolderPath('CommonStartMenu'), [Environment]::GetFolderPath('StartMenu'), [Environment]::GetFolderPath('Desktop'), [Environment]::GetFolderPath('CommonDesktopDirectory'))
1135
1149
  $shortcuts = @(foreach ($d in $dirs) { if ($d) { Get-ChildItem -LiteralPath $d -Filter *.lnk -Recurse | ForEach-Object { @{ name = $_.BaseName; target = [string]$shell.CreateShortcut($_.FullName).TargetPath } } } })
1136
- @{ running = $running; entries = $entries; shortcuts = $shortcuts } | ConvertTo-Json -Depth 4 -Compress
1150
+ # Where Windows noted a program with this file name: run before, App Paths, the search index.
1151
+ $known = New-Object System.Collections.ArrayList
1152
+ $tail = '\\' + $exe
1153
+ foreach ($k in 'HKCU:\\Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\MuiCache', 'HKCU:\\Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Compatibility Assistant\\Store') {
1154
+ $item = Get-Item -LiteralPath $k
1155
+ if ($item) { foreach ($n in $item.GetValueNames()) { $i = $n.IndexOf($tail, [StringComparison]::OrdinalIgnoreCase); if ($i -ge 0) { [void]$known.Add(@{ path = $n.Substring(0, $i + $tail.Length); source = '\u4EE5\u524D\u8FD0\u884C\u8FC7' }) } } }
1156
+ }
1157
+ foreach ($k in 'HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\', 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\') {
1158
+ $v = (Get-ItemProperty -LiteralPath ($k + $exe)).'(default)'
1159
+ if ($v) { [void]$known.Add(@{ path = ([string]$v).Trim('"'); source = 'App Paths' }) }
1160
+ }
1161
+ try {
1162
+ $db = New-Object -ComObject ADODB.Connection
1163
+ $db.Open("Provider=Search.CollatorDSO;Extended Properties='Application=Windows';")
1164
+ $rs = $db.Execute("SELECT System.ItemPathDisplay FROM SYSTEMINDEX WHERE System.FileName = '" + $exe.Replace("'", "''") + "'")
1165
+ while (-not $rs.EOF) { [void]$known.Add(@{ path = [string]$rs.Fields.Item(0).Value; source = 'Windows \u641C\u7D22' }); $rs.MoveNext() }
1166
+ $db.Close()
1167
+ } catch {}
1168
+ # Folders game launchers note games in (HoYoPlay: GameInstallPath per game).
1169
+ $installs = New-Object System.Collections.ArrayList
1170
+ foreach ($root in 'HKCU:\\Software\\Cognosphere', 'HKCU:\\Software\\miHoYo', 'HKCU:\\Software\\HYP', 'HKCU:\\Software\\Hypergryph', 'HKCU:\\Software\\HYPERGRYPH', 'HKCU:\\Software\\Kuro Games', 'HKCU:\\Software\\KuroGame') {
1171
+ if (Test-Path -LiteralPath $root) {
1172
+ foreach ($key in @(Get-Item -LiteralPath $root) + @(Get-ChildItem -LiteralPath $root -Recurse)) {
1173
+ foreach ($n in $key.GetValueNames()) {
1174
+ if ($n -match 'Install|Path|Dir') { $v = $key.GetValue($n); if ($v -is [string] -and $v -match '^[A-Za-z]:[\\\\/]') { [void]$installs.Add($v) } }
1175
+ }
1176
+ }
1177
+ }
1178
+ }
1179
+ @{ running = $running; entries = $entries; shortcuts = $shortcuts; known = @($known); installs = @($installs) } | ConvertTo-Json -Depth 4 -Compress
1137
1180
  `;
1138
1181
  function windowsProbe(exe) {
1139
1182
  if (process.platform !== "win32")
@@ -1150,7 +1193,7 @@ function windowsProbe(exe) {
1150
1193
  try {
1151
1194
  const raw = JSON.parse(String(stdout).trim());
1152
1195
  const list = (v) => Array.isArray(v) ? v : v === null || v === void 0 ? [] : [v];
1153
- resolve2({ running: list(raw.running), entries: list(raw.entries), shortcuts: list(raw.shortcuts) });
1196
+ resolve2({ running: list(raw.running), entries: list(raw.entries), shortcuts: list(raw.shortcuts), known: list(raw.known), installs: list(raw.installs) });
1154
1197
  } catch (e) {
1155
1198
  reject(e);
1156
1199
  }
@@ -1158,10 +1201,153 @@ function windowsProbe(exe) {
1158
1201
  });
1159
1202
  }
1160
1203
 
1204
+ // packages/runner/lib/retention.js
1205
+ import { createReadStream, createWriteStream } from "node:fs";
1206
+ import { copyFile as copyFile2, readdir as readdir3, readFile as readFile4, rename as rename2, rm as rm2, stat as stat3 } from "node:fs/promises";
1207
+ import { join as join5 } from "node:path";
1208
+ import { pipeline } from "node:stream/promises";
1209
+ import { promisify } from "node:util";
1210
+ import { createGzip, gunzip } from "node:zlib";
1211
+ var LOG_FILE = "log.jsonl";
1212
+ var PREV_LOG_FILE = "log.prev.jsonl";
1213
+ var PACKED_LOG_FILE = "log.jsonl.gz";
1214
+ var TEXT_LOG_FILE = "log.txt";
1215
+ var LOG_FILES = [LOG_FILE, PREV_LOG_FILE, PACKED_LOG_FILE, TEXT_LOG_FILE];
1216
+ var MiB = 1024 * 1024;
1217
+ var LIVE_LOG_MAX = 64 * MiB;
1218
+ var SCRIPT_LOG_BUDGET = 64 * MiB;
1219
+ var PACK_AFTER_MS = 10 * 6e4;
1220
+ var KEEP_DAYS = 30;
1221
+ var gunzipAsync = promisify(gunzip);
1222
+ async function tidyRuns(root, options) {
1223
+ const budget = options.budget ?? SCRIPT_LOG_BUDGET;
1224
+ let names;
1225
+ try {
1226
+ names = await readdir3(root);
1227
+ } catch {
1228
+ return { expired: 0, packed: 0, trimmed: 0, freed: 0 };
1229
+ }
1230
+ let expired = 0, packed = 0, trimmed = 0, freed = 0;
1231
+ const byScript = /* @__PURE__ */ new Map();
1232
+ for (const name of names) {
1233
+ const dir = join5(root, name);
1234
+ let info;
1235
+ try {
1236
+ info = JSON.parse(await readFile4(join5(dir, "run.json"), "utf8"));
1237
+ } catch {
1238
+ continue;
1239
+ }
1240
+ if (typeof info.scriptId !== "string" || typeof info.startedAt !== "number")
1241
+ continue;
1242
+ const busy = info.endedAt === void 0 || options.busy(info.id ?? name);
1243
+ if (!busy && options.now - info.endedAt > KEEP_DAYS * 864e5) {
1244
+ const size = await logBytes(dir);
1245
+ await rm2(dir, { recursive: true, force: true }).then(() => {
1246
+ expired++;
1247
+ freed += size;
1248
+ }, () => {
1249
+ });
1250
+ continue;
1251
+ }
1252
+ const list = byScript.get(info.scriptId) ?? [];
1253
+ list.push({ dir, startedAt: info.startedAt, endedAt: info.endedAt ?? Number.POSITIVE_INFINITY, busy });
1254
+ byScript.set(info.scriptId, list);
1255
+ }
1256
+ for (const runs of byScript.values()) {
1257
+ let total = 0;
1258
+ for (const [i, run] of runs.sort((a, b) => b.startedAt - a.startedAt).entries()) {
1259
+ const before = await logBytes(run.dir);
1260
+ if (run.busy) {
1261
+ total += before;
1262
+ continue;
1263
+ }
1264
+ if (i > 0 && total >= budget) {
1265
+ if (before === 0)
1266
+ continue;
1267
+ await Promise.all(LOG_FILES.map((file) => rm2(join5(run.dir, file), { force: true })));
1268
+ trimmed++;
1269
+ freed += before - await logBytes(run.dir);
1270
+ continue;
1271
+ }
1272
+ if (await exists(join5(run.dir, LOG_FILE)) || await exists(join5(run.dir, PACKED_LOG_FILE)))
1273
+ await rm2(join5(run.dir, TEXT_LOG_FILE), { force: true });
1274
+ if (options.now - run.endedAt >= PACK_AFTER_MS && await packLog(run.dir))
1275
+ packed++;
1276
+ const after = await logBytes(run.dir);
1277
+ freed += Math.max(0, before - after);
1278
+ total += after;
1279
+ }
1280
+ }
1281
+ return { expired, packed, trimmed, freed };
1282
+ }
1283
+ async function packLog(dir) {
1284
+ const parts = [PREV_LOG_FILE, LOG_FILE].map((file) => join5(dir, file));
1285
+ const present = [];
1286
+ for (const part of parts)
1287
+ if (await exists(part))
1288
+ present.push(part);
1289
+ if (present.length === 0)
1290
+ return false;
1291
+ const packed = join5(dir, PACKED_LOG_FILE);
1292
+ const temp = `${packed}.${process.pid}.tmp`;
1293
+ try {
1294
+ if (await exists(packed))
1295
+ await copyFile2(packed, temp);
1296
+ await pipeline(concat(present), createGzip(), createWriteStream(temp, { flags: "a" }));
1297
+ await rename2(temp, packed);
1298
+ } catch (error) {
1299
+ await rm2(temp, { force: true }).catch(() => {
1300
+ });
1301
+ throw error;
1302
+ }
1303
+ for (const part of present)
1304
+ await rm2(part, { force: true });
1305
+ return true;
1306
+ }
1307
+ async function readRunLog(dir) {
1308
+ const packed = await readFile4(join5(dir, PACKED_LOG_FILE)).then((bytes) => gunzipAsync(bytes), () => void 0);
1309
+ const prev = await readFile4(join5(dir, PREV_LOG_FILE), "utf8").catch(() => void 0);
1310
+ const current = await readFile4(join5(dir, LOG_FILE), "utf8").catch(() => void 0);
1311
+ if (packed === void 0 && prev === void 0 && current === void 0)
1312
+ return void 0;
1313
+ const old = packed === void 0 ? [] : parseLines(packed.toString("utf8"));
1314
+ const plain = [...parseLines(prev ?? ""), ...parseLines(current ?? "")];
1315
+ if (plain.length > 0 && old.length >= plain.length && sameLine(old[old.length - plain.length], plain[0]) && sameLine(old.at(-1), plain.at(-1)))
1316
+ return old;
1317
+ return [...old, ...plain];
1318
+ }
1319
+ async function runLogFile(dir) {
1320
+ return await exists(join5(dir, LOG_FILE)) || !await exists(join5(dir, PACKED_LOG_FILE)) ? join5(dir, LOG_FILE) : join5(dir, PACKED_LOG_FILE);
1321
+ }
1322
+ async function logBytes(dir) {
1323
+ let total = 0;
1324
+ for (const file of LOG_FILES)
1325
+ total += await stat3(join5(dir, file)).then((s) => s.size, () => 0);
1326
+ return total;
1327
+ }
1328
+ function parseLines(text) {
1329
+ return text.split("\n").filter((l) => l !== "").flatMap((l) => {
1330
+ try {
1331
+ return [JSON.parse(l)];
1332
+ } catch {
1333
+ return [];
1334
+ }
1335
+ });
1336
+ }
1337
+ function sameLine(a, b) {
1338
+ return a !== void 0 && b !== void 0 && a.at === b.at && a.source === b.source && a.text === b.text;
1339
+ }
1340
+ async function* concat(files) {
1341
+ for (const file of files)
1342
+ yield* createReadStream(file);
1343
+ }
1344
+ function exists(path) {
1345
+ return stat3(path).then(() => true, () => false);
1346
+ }
1347
+
1161
1348
  // packages/runner/lib/runs.js
1162
1349
  var KEEP_RUNS = 50;
1163
1350
  var KEEP_LINES = 2e3;
1164
- var KEEP_DAYS = 30;
1165
1351
  var Runner = class {
1166
1352
  locks = new ResourceLocks();
1167
1353
  /** The local config copies runs use. */
@@ -1177,6 +1363,8 @@ var Runner = class {
1177
1363
  #successorAborts = /* @__PURE__ */ new Map();
1178
1364
  /** Runs someone is still deciding about (the monitor handling an incident) → how many, and who waits. */
1179
1365
  #holds = /* @__PURE__ */ new Map();
1366
+ /** The retention pass going on (tidy). */
1367
+ #tidying = Promise.resolve();
1180
1368
  #now;
1181
1369
  constructor(options) {
1182
1370
  this.#options = options;
@@ -1230,7 +1418,7 @@ var Runner = class {
1230
1418
  if (text === void 0)
1231
1419
  throw new Error(`\u672C\u5730\u914D\u7F6E\u91CC\u8FD8\u6CA1\u6709 ${spec.file}\uFF1A\u5148\u300C\u6253\u5F00\u811A\u672C\u4FEE\u6539\u8BBE\u7F6E\u300D\uFF0C\u5728\u811A\u672C\u91CC\u5EFA\u4E00\u4E2A\uFF0C\u4E4B\u540E\u5C31\u53EF\u4EE5\u5728\u8FD9\u91CC\u590D\u5236`);
1232
1420
  const { list, value } = listWithNew(spec, text, name.trim());
1233
- const historyDir = join5(this.#options.dataDir, "config-history", scriptId, new Date(this.#now()).toISOString().replace(/[:.]/g, "-"));
1421
+ const historyDir = join6(this.#options.dataDir, "config-history", scriptId, new Date(this.#now()).toISOString().replace(/[:.]/g, "-"));
1234
1422
  await this.profiles.write(scriptId, script.dir, pack.manifest, spec.file, spec.list, list, historyDir, profile);
1235
1423
  return value;
1236
1424
  }
@@ -1286,6 +1474,20 @@ var Runner = class {
1286
1474
  const name = exe.toLowerCase().endsWith(".exe") ? exe : `${exe}.exe`;
1287
1475
  return { exe: name, candidates: await locateGame({ exe: name, keywords: gameKeywords(game ?? {}), ...signal === void 0 ? {} : { signal } }) };
1288
1476
  }
1477
+ /**
1478
+ * Where a PC game is, from what a pack says about it (its process and the
1479
+ * names to look for), installed or not: for the game's icon, before any
1480
+ * script that plays it is set up. @returns the best candidate's path.
1481
+ */
1482
+ async findGameProgram(game, extraKeywords = [], signal) {
1483
+ const exe = game.pc?.process;
1484
+ if (exe === void 0)
1485
+ return void 0;
1486
+ const name = exe.toLowerCase().endsWith(".exe") ? exe : `${exe}.exe`;
1487
+ const keywords = [.../* @__PURE__ */ new Set([...gameKeywords(game), ...extraKeywords.filter((k) => k.length >= 2)])];
1488
+ const candidates = await locateGame({ exe: name, keywords, ...signal === void 0 ? {} : { signal } });
1489
+ return candidates[0]?.path;
1490
+ }
1289
1491
  /** Follow every run's state and lines. @returns a disposer. */
1290
1492
  watch(listener) {
1291
1493
  this.#listeners.add(listener);
@@ -1307,21 +1509,18 @@ var Runner = class {
1307
1509
  * memory), also for runs from before a restart, searched and paged.
1308
1510
  */
1309
1511
  async readLog(runId, query = {}) {
1310
- const file = join5(this.#options.dataDir, "runs", runId, "log.jsonl");
1311
- let all;
1312
- try {
1313
- all = (await readFile4(file, "utf8")).split("\n").filter((l) => l !== "").flatMap((l) => {
1314
- try {
1315
- return [JSON.parse(l)];
1316
- } catch {
1317
- return [];
1318
- }
1319
- });
1320
- } catch {
1321
- all = this.#runs.get(runId)?.lines ?? [];
1322
- if (all.length === 0 && !this.#runs.has(runId))
1512
+ const dir = join6(this.#options.dataDir, "runs", runId);
1513
+ let all = await readRunLog(dir);
1514
+ if (all === void 0) {
1515
+ const memory = this.#runs.get(runId);
1516
+ if (memory !== void 0 && (memory.archived !== true || memory.lines.length > 0))
1517
+ all = memory.lines;
1518
+ else if (await stat4(join6(dir, "run.json")).then(() => true, () => false))
1519
+ throw new Error(`${runId} \u7684\u65E5\u5FD7\u5DF2\u6309\u4FDD\u7559\u89C4\u5219\u6E05\u7406\uFF08\u6BCF\u4E2A\u811A\u672C\u53EA\u7559\u6700\u8FD1\u7EA6 ${SCRIPT_LOG_BUDGET / 1024 / 1024} MiB \u7684\u8FD0\u884C\u65E5\u5FD7\uFF09`);
1520
+ else
1323
1521
  throw new Error(`\u6CA1\u6709\u8FD0\u884C\u8BB0\u5F55 ${runId}`);
1324
1522
  }
1523
+ const file = await runLogFile(dir);
1325
1524
  const pattern = query.search === void 0 || query.search === "" ? void 0 : toPattern(query.search);
1326
1525
  const numbered = all.map((line, i) => ({ ...line, n: i + 1 })).filter((l) => (query.levels === void 0 || query.levels.length === 0 || l.level !== void 0 && query.levels.includes(l.level)) && (pattern === void 0 || pattern.test(l.text)));
1327
1526
  const limit = Math.max(1, Math.min(query.limit ?? 200, 2e3));
@@ -1333,24 +1532,24 @@ var Runner = class {
1333
1532
  * the restart is marked failed. Old run folders are removed.
1334
1533
  */
1335
1534
  async loadHistory() {
1336
- const root = join5(this.#options.dataDir, "runs");
1535
+ const root = join6(this.#options.dataDir, "runs");
1337
1536
  let names;
1338
1537
  try {
1339
- names = await readdir3(root);
1538
+ names = await readdir4(root);
1340
1539
  } catch {
1341
1540
  return;
1342
1541
  }
1343
1542
  const infos = [];
1344
1543
  for (const name of names) {
1345
1544
  try {
1346
- const info = JSON.parse(await readFile4(join5(root, name, "run.json"), "utf8"));
1545
+ const info = JSON.parse(await readFile5(join6(root, name, "run.json"), "utf8"));
1347
1546
  if (info.endedAt === void 0) {
1348
1547
  Object.assign(info, { state: "failed", outcome: "\u7A0B\u5E8F\u9000\u51FA\u65F6\u4E2D\u65AD", endedAt: info.startedAt });
1349
- await writeFile4(join5(root, name, "run.json"), JSON.stringify(info, null, 2)).catch(() => {
1548
+ await writeFile4(join6(root, name, "run.json"), JSON.stringify(info, null, 2)).catch(() => {
1350
1549
  });
1351
1550
  }
1352
1551
  if (this.#now() - info.endedAt > KEEP_DAYS * 864e5) {
1353
- await rm2(join5(root, name), { recursive: true, force: true }).catch(() => {
1552
+ await rm3(join6(root, name), { recursive: true, force: true }).catch(() => {
1354
1553
  });
1355
1554
  continue;
1356
1555
  }
@@ -1369,6 +1568,9 @@ var Runner = class {
1369
1568
  controller: new AbortController(),
1370
1569
  lines: [],
1371
1570
  pendingLines: [],
1571
+ logText: [],
1572
+ writing: Promise.resolve(),
1573
+ logBytes: 0,
1372
1574
  release: [],
1373
1575
  finished: Promise.resolve(info),
1374
1576
  resolveFinished: () => {
@@ -1377,6 +1579,28 @@ var Runner = class {
1377
1579
  });
1378
1580
  }
1379
1581
  }
1582
+ /**
1583
+ * Apply the retention rules (retention.ts) to the saved runs: logs gzipped,
1584
+ * each script's within its budget, old run folders deleted. Runs still going
1585
+ * or still being handled are left alone. One pass at a time.
1586
+ */
1587
+ tidy() {
1588
+ const pass = this.#tidying.catch(() => void 0).then(() => tidyRuns(join6(this.#options.dataDir, "runs"), {
1589
+ now: this.#now(),
1590
+ ...this.#options.logLimits?.perScript === void 0 ? {} : { budget: this.#options.logLimits.perScript },
1591
+ busy: (id) => {
1592
+ const run = this.#runs.get(id);
1593
+ return run !== void 0 && run.info.endedAt === void 0 || this.#holds.has(id);
1594
+ }
1595
+ }));
1596
+ this.#tidying = pass;
1597
+ return pass.then((result) => {
1598
+ if (result.expired + result.packed + result.trimmed > 0) {
1599
+ this.#options.log.info(`run logs tidied: ${result.packed} gzipped, ${result.trimmed} trimmed to the per-script budget, ${result.expired} old run folder(s) deleted; ${(result.freed / 1024 / 1024).toFixed(1)} MiB freed`);
1600
+ }
1601
+ return result;
1602
+ });
1603
+ }
1380
1604
  /** Settles when the run ends. */
1381
1605
  finished(runId) {
1382
1606
  return this.#run(runId).finished;
@@ -1571,6 +1795,9 @@ var Runner = class {
1571
1795
  controller: new AbortController(),
1572
1796
  lines: [],
1573
1797
  pendingLines: [],
1798
+ logText: [],
1799
+ writing: Promise.resolve(),
1800
+ logBytes: 0,
1574
1801
  release: [],
1575
1802
  finished,
1576
1803
  resolveFinished
@@ -1596,9 +1823,9 @@ var Runner = class {
1596
1823
  run.release.push(() => signal.removeEventListener("abort", callOff));
1597
1824
  }
1598
1825
  }
1599
- const runDir = join5(this.#options.dataDir, "runs", runId);
1826
+ const runDir = join6(this.#options.dataDir, "runs", runId);
1600
1827
  await mkdir4(runDir, { recursive: true });
1601
- await writeFile4(join5(runDir, "run.json"), JSON.stringify(run.info, null, 2)).catch(() => {
1828
+ await writeFile4(join6(runDir, "run.json"), JSON.stringify(run.info, null, 2)).catch(() => {
1602
1829
  });
1603
1830
  this.#publish(run);
1604
1831
  let launchedGame;
@@ -1676,7 +1903,7 @@ var Runner = class {
1676
1903
  run.info.state = "running";
1677
1904
  this.#line(run, "adg", `\u5DF2\u542F\u52A8\uFF1A${run.info.command.map(quote).join(" ")}`);
1678
1905
  this.#publish(run);
1679
- void writeFile4(join5(runDir, "run.json"), JSON.stringify(run.info, null, 2)).catch(() => {
1906
+ void writeFile4(join6(runDir, "run.json"), JSON.stringify(run.info, null, 2)).catch(() => {
1680
1907
  });
1681
1908
  return run.info;
1682
1909
  } catch (error) {
@@ -1918,6 +2145,8 @@ var Runner = class {
1918
2145
  async dispose() {
1919
2146
  await Promise.all([...this.#runs.values()].filter((r) => r.info.endedAt === void 0).map((r) => this.stop(r.info.id).catch(() => {
1920
2147
  })));
2148
+ await this.#tidying.catch(() => {
2149
+ });
1921
2150
  }
1922
2151
  #follow(run, manifest, dir) {
1923
2152
  const rules = manifest.logs.rules.map((rule) => ({ rule, pattern: new RegExp(rule.match) }));
@@ -1997,13 +2226,15 @@ var Runner = class {
1997
2226
  this.#line(run, "adg", `${state === "succeeded" ? "\u5B8C\u6210" : state === "cancelled" ? "\u5DF2\u505C\u6B62" : "\u5931\u8D25"}\uFF1A${reason}`);
1998
2227
  this.#flush(run);
1999
2228
  this.#publish(run);
2000
- const runDir = join5(this.#options.dataDir, "runs", run.info.id);
2229
+ const runDir = join6(this.#options.dataDir, "runs", run.info.id);
2001
2230
  await mkdir4(runDir, { recursive: true }).catch(() => {
2002
2231
  });
2003
- await writeFile4(join5(runDir, "run.json"), JSON.stringify(run.info, null, 2)).catch(() => {
2232
+ await writeFile4(join6(runDir, "run.json"), JSON.stringify(run.info, null, 2)).catch(() => {
2004
2233
  });
2234
+ await run.writing;
2005
2235
  this.#options.log.info(`run ${run.info.id} ${state}: ${reason}`);
2006
2236
  run.resolveFinished(run.info);
2237
+ void this.tidy().catch((error) => this.#options.log.warn(`tidying run logs failed: ${error instanceof Error ? error.message : String(error)}`));
2007
2238
  }
2008
2239
  #line(run, source, text) {
2009
2240
  this.#push(run, { at: this.#now(), source, text });
@@ -2013,29 +2244,41 @@ var Runner = class {
2013
2244
  if (run.lines.length > KEEP_LINES)
2014
2245
  run.lines.splice(0, run.lines.length - KEEP_LINES);
2015
2246
  run.pendingLines.push(line);
2247
+ run.logText.push(`${JSON.stringify(line)}
2248
+ `);
2016
2249
  for (const listener of this.#listeners) {
2017
2250
  try {
2018
2251
  listener.line?.(run.info, line);
2019
2252
  } catch {
2020
2253
  }
2021
2254
  }
2022
- const dir = join5(this.#options.dataDir, "runs", run.info.id);
2023
- void appendFile(join5(dir, "log.jsonl"), `${JSON.stringify(line)}
2024
- `).catch(() => {
2025
- });
2026
- void appendFile(join5(dir, "log.txt"), `${new Date(line.at).toISOString()} [${line.source}]${line.level === void 0 ? "" : ` [${line.level}]`} ${line.text}
2027
- `).catch(() => {
2028
- });
2029
2255
  if (run.flushTimer === void 0)
2030
2256
  run.flushTimer = setTimeout(() => this.#flush(run), 100);
2031
2257
  }
2032
2258
  #flush(run) {
2033
2259
  clearTimeout(run.flushTimer);
2034
2260
  run.flushTimer = void 0;
2261
+ if (run.logText.length > 0) {
2262
+ const text = run.logText.splice(0).join("");
2263
+ run.writing = run.writing.then(() => this.#writeLog(run, text)).catch((error) => {
2264
+ this.#options.log.warn(`run ${run.info.id}: writing its log failed: ${error instanceof Error ? error.message : String(error)}`);
2265
+ });
2266
+ }
2035
2267
  if (run.pendingLines.length === 0)
2036
2268
  return;
2037
2269
  this.#options.onLog(run.info.id, run.pendingLines.splice(0));
2038
2270
  }
2271
+ /** Append to the run's log; past LIVE_LOG_MAX it starts over, the part before kept as log.prev.jsonl (as MAA keeps asst.bak.log). */
2272
+ async #writeLog(run, text) {
2273
+ const dir = join6(this.#options.dataDir, "runs", run.info.id);
2274
+ await mkdir4(dir, { recursive: true });
2275
+ await appendFile(join6(dir, LOG_FILE), text);
2276
+ run.logBytes += Buffer.byteLength(text);
2277
+ if (run.logBytes < (this.#options.logLimits?.live ?? LIVE_LOG_MAX))
2278
+ return;
2279
+ await rename3(join6(dir, LOG_FILE), join6(dir, PREV_LOG_FILE));
2280
+ run.logBytes = 0;
2281
+ }
2039
2282
  #publish(run) {
2040
2283
  const snapshot = { ...run.info, resources: [...run.info.resources], tags: [...run.info.tags], warnings: [...run.info.warnings] };
2041
2284
  this.#options.onState(snapshot);
@@ -2118,7 +2361,7 @@ function quote(value) {
2118
2361
  }
2119
2362
 
2120
2363
  // packages/runner/lib/config.js
2121
- import { join as join6 } from "node:path";
2364
+ import { join as join7 } from "node:path";
2122
2365
  var MAX_READ = 6e4;
2123
2366
  function allowed(manifest, file) {
2124
2367
  const normalized = file.replace(/\\/g, "/");
@@ -2149,9 +2392,9 @@ async function writeConfig(library, profiles, dataDir, scriptId, file, path, val
2149
2392
  allowed(manifest, file);
2150
2393
  const profile = await profiles.resolve(scriptId, profileRef);
2151
2394
  const stamp = new Date(now).toISOString().replace(/[:.]/g, "-");
2152
- const historyDir = join6(dataDir, "config-history", scriptId, profile.id === DEFAULT_PROFILE ? stamp : `${stamp}-${profile.id}`);
2395
+ const historyDir = join7(dataDir, "config-history", scriptId, profile.id === DEFAULT_PROFILE ? stamp : `${stamp}-${profile.id}`);
2153
2396
  await profiles.write(scriptId, dir, manifest, file, path, value, historyDir, profile.id);
2154
- return { file, backup: join6(historyDir, file), copy: "local", profile: profile.name };
2397
+ return { file, backup: join7(historyDir, file), copy: "local", profile: profile.name };
2155
2398
  }
2156
2399
  async function configStatus(library, profiles, scriptId, profileRef) {
2157
2400
  const { manifest, dir } = packFor(library, scriptId);
@@ -2244,6 +2487,67 @@ var brief = (runner, runId, lines = 15) => {
2244
2487
  last_lines: runner.logs(runId, lines).map((l) => `[${l.source}] ${l.text}`)
2245
2488
  };
2246
2489
  };
2490
+ var MAX_WAIT_SECONDS = 3600;
2491
+ async function waitForRun(runner, runId, ms, signals = {}, now = Date.now) {
2492
+ const { signal, input } = signals;
2493
+ const started = now();
2494
+ const followed = [];
2495
+ let current = runId;
2496
+ const TIMED_OUT = Symbol("timed out");
2497
+ const NEW_INPUT = Symbol("new input");
2498
+ const within = async (promise) => {
2499
+ if (input?.aborted === true)
2500
+ return NEW_INPUT;
2501
+ const left = started + ms - now();
2502
+ if (left <= 0 || signal?.aborted === true)
2503
+ return TIMED_OUT;
2504
+ let timer;
2505
+ let onAbort;
2506
+ let onInput;
2507
+ const stop = new Promise((resolve2) => {
2508
+ timer = setTimeout(() => resolve2(TIMED_OUT), left);
2509
+ onAbort = () => resolve2(TIMED_OUT);
2510
+ onInput = () => resolve2(NEW_INPUT);
2511
+ signal?.addEventListener("abort", onAbort, { once: true });
2512
+ input?.addEventListener("abort", onInput, { once: true });
2513
+ });
2514
+ try {
2515
+ return await Promise.race([promise, stop]);
2516
+ } finally {
2517
+ clearTimeout(timer);
2518
+ if (onAbort !== void 0)
2519
+ signal?.removeEventListener("abort", onAbort);
2520
+ if (onInput !== void 0)
2521
+ input?.removeEventListener("abort", onInput);
2522
+ }
2523
+ };
2524
+ const result = (timedOut, paused = false, newInput = false) => ({ runId: current, followed, timedOut, paused, newInput, ms: now() - started });
2525
+ for (; ; ) {
2526
+ if (runner.get(current).endedAt === void 0) {
2527
+ if (runner.held(current))
2528
+ return result(false, true);
2529
+ const ended = await within(runner.finished(current));
2530
+ if (ended === NEW_INPUT)
2531
+ return result(false, false, true);
2532
+ if (ended === TIMED_OUT)
2533
+ return result(true);
2534
+ }
2535
+ const next = await within(runner.successor(current));
2536
+ if (next === NEW_INPUT)
2537
+ return result(false, false, true);
2538
+ if (next === TIMED_OUT)
2539
+ return result(true);
2540
+ if (next === void 0)
2541
+ return result(false);
2542
+ current = next.id;
2543
+ followed.push(current);
2544
+ }
2545
+ }
2546
+ function waitedView(asked, waited) {
2547
+ const seconds = Math.round(waited.ms / 1e3);
2548
+ const note = waited.newInput ? `\u7B49\u4E86 ${seconds} \u79D2\uFF0C\u6709\u65B0\u6D88\u606F\uFF08\u7528\u6237\u6216\u522B\u7684 agent \u53D1\u6765\u7684\uFF09\u5728\u7B49\u4F60\uFF0C\u5148\u505C\u4E0B\u6765\u770B\u5B83\u3002\u4E0B\u9762\u662F\u8FD9\u6B21\u8FD0\u884C\u73B0\u5728\u7684\u72B6\u6001\uFF1B\u770B\u5B8C\u8FD8\u8981\u7B49\u5B83\u5C31\u518D\u8C03\u7528\u4E00\u6B21\u3002` : waited.paused ? "\u8FD9\u6B21\u8FD0\u884C\u6682\u505C\u7740\uFF0C\u6B63\u5728\u5904\u7406\u5B83\u51FA\u7684\u95EE\u9898\uFF08\u5E72\u9884\uFF09\uFF1A\u5904\u7406\u5B8C\u4E4B\u524D\u5B83\u4E0D\u4F1A\u7ED3\u675F\uFF0C\u6240\u4EE5\u6CA1\u6709\u7B49\u3002" : waited.timedOut ? `\u7B49\u4E86 ${seconds} \u79D2\u8FD8\u6CA1\u7ED3\u675F${waited.runId === asked ? "" : "\uFF08\u8FD9\u662F\u91CD\u65B0\u8FD0\u884C\u7684\u90A3\u6B21\uFF09"}\uFF1B\u8FD8\u8981\u7B49\u5C31\u518D\u8C03\u7528\u4E00\u6B21\u3002` : waited.followed.length > 0 ? `\u8FD0\u884C\u88AB\u91CD\u65B0\u8FD0\u884C\u8FC7 ${waited.followed.length} \u6B21\uFF0C\u4E0B\u9762\u662F\u6700\u540E\u90A3\u6B21\u7684\u7ED3\u679C\u3002` : "\u8FD0\u884C\u5DF2\u7ED3\u675F\u3002";
2549
+ return { seconds, timed_out: waited.timedOut, paused: waited.paused, ...waited.newInput ? { new_input: true } : {}, ...waited.followed.length > 0 ? { restarted_as: waited.followed } : {}, note };
2550
+ }
2247
2551
  function runnerTools(runner, config) {
2248
2552
  const id = { type: "string", description: "\u811A\u672C\u5E93\u91CC\u7684\u811A\u672C id\uFF08script_list \u53EF\u67E5\uFF09\u3002" };
2249
2553
  const profile = { type: "string", description: "\u7528\u54EA\u4EFD\u914D\u7F6E\uFF08script_profiles \u53EF\u67E5\uFF0C\u5199\u540D\u5B57\u6216 id\uFF09\uFF1B\u4E0D\u586B\u5C31\u662F\u811A\u672C\u5F53\u524D\u4F7F\u7528\u7684\u90A3\u4EFD\u3002" };
@@ -2372,15 +2676,24 @@ function runnerTools(runner, config) {
2372
2676
  }),
2373
2677
  tool({
2374
2678
  name: TOOL_NAMES.tasks,
2375
- description: "\u5217\u51FA\u4E00\u4E2A\u811A\u672C\u80FD\u8FD0\u884C\u7684\u4EFB\u52A1\uFF1A\u4EFB\u52A1 id\u3001\u540D\u79F0\u3001\u7528\u6237\u53EF\u80FD\u7684\u8BF4\u6CD5\u3001\u53C2\u6570\uFF08\u7C7B\u578B\u3001\u9ED8\u8BA4\u503C\u3001\u53EF\u9009\u503C\uFF1Bchoices \u662F\u4ECE\u811A\u672C\u914D\u7F6E\u91CC\u8BFB\u51FA\u7684\u53EF\u9009\u9879\uFF0C\u4F8B\u5982 MaaEnd \u7684\u5B9E\u4F8B\u540D\uFF0CcanCreate \u8868\u793A\u53EF\u4EE5\u7528 script_choice_create \u65B0\u5EFA\uFF09\u3001\u5360\u7528\u7684\u8D44\u6E90\uFF08desktop \u62A2\u5360\u9F20\u6807\u952E\u76D8\u3001adb \u4F7F\u7528\u6A21\u62DF\u5668\uFF09\u3002\u8FD0\u884C\u524D\u5148\u8C03\u7528\u5B83\u628A\u7528\u6237\u7684\u8BDD\u5BF9\u5E94\u5230\u4EFB\u52A1\u548C\u53C2\u6570\u3002",
2376
- properties: { id, profile: { ...profile, description: "\u53EF\u9009\u9879\uFF08choices\uFF09\u4ECE\u54EA\u4EFD\u914D\u7F6E\u91CC\u8BFB\uFF1B\u4E0D\u586B\u662F\u5F53\u524D\u90A3\u4EFD\u3002" } },
2679
+ description: "\u5217\u51FA\u4E00\u4E2A\u811A\u672C\u80FD\u8FD0\u884C\u7684\u4EFB\u52A1\uFF1A\u4EFB\u52A1 id\u3001\u540D\u79F0\u3001\u7528\u6237\u53EF\u80FD\u7684\u8BF4\u6CD5\u3001\u53C2\u6570\uFF08\u7C7B\u578B\u3001\u9ED8\u8BA4\u503C\u3001\u53EF\u9009\u503C\uFF1Bchoices \u662F\u4ECE\u811A\u672C\u914D\u7F6E\u91CC\u8BFB\u51FA\u7684\u53EF\u9009\u9879\uFF0C\u4F8B\u5982 MaaEnd \u7684\u5B9E\u4F8B\u540D\uFF0CcanCreate \u8868\u793A\u53EF\u4EE5\u7528 script_choice_create \u65B0\u5EFA\uFF09\u3001\u5360\u7528\u7684\u8D44\u6E90\uFF08desktop \u62A2\u5360\u9F20\u6807\u952E\u76D8\u3001adb \u4F7F\u7528\u6A21\u62DF\u5668\uFF09\u3002\u8FD0\u884C\u524D\u5148\u8C03\u7528\u5B83\u628A\u7528\u6237\u7684\u8BDD\u5BF9\u5E94\u5230\u4EFB\u52A1\u548C\u53C2\u6570\u3002guide \u4E3A true \u65F6\u9644\u4E0A\u811A\u672C\u5305\u7684\u4F7F\u7528\u8BF4\u660E\uFF08\u811A\u672C\u9875\u4E0A\u7ED9\u7528\u6237\u770B\u7684\u540C\u4E00\u4EFD\uFF09\uFF1A\u529F\u80FD\u600E\u4E48\u5F00\u542F\u3001\u914D\u7F6E\u6587\u4EF6\u7684\u91CD\u8981\u952E\u548C\u8FD0\u884C\u65F6\u4E34\u65F6\u6539\u7684\u952E\u3001\u9996\u6B21\u8BBE\u7F6E\u3001\u8FD0\u884C\u524D\u68C0\u67E5\u3001\u5E38\u89C1\u95EE\u9898\uFF1B\u7528\u6237\u95EE\u300C\u600E\u4E48\u5F00\u542F\u67D0\u529F\u80FD\u300D\u300C\u8FD9\u4E2A\u8BBE\u7F6E\u662F\u4EC0\u4E48\u610F\u601D\u300D\u300C\u8FD9\u4E2A\u62A5\u9519\u600E\u4E48\u529E\u300D\u65F6\u7528\u3002",
2680
+ properties: {
2681
+ id,
2682
+ profile: { ...profile, description: "\u53EF\u9009\u9879\uFF08choices\uFF09\u4ECE\u54EA\u4EFD\u914D\u7F6E\u91CC\u8BFB\uFF1B\u4E0D\u586B\u662F\u5F53\u524D\u90A3\u4EFD\u3002" },
2683
+ guide: { type: "boolean", description: "\u9644\u4E0A\u4F7F\u7528\u8BF4\u660E\u3002" }
2684
+ },
2377
2685
  required: ["id"],
2378
2686
  readOnly: true,
2379
2687
  kind: "read",
2380
2688
  title: (a) => `\u67E5\u770B\u4EFB\u52A1\uFF1A${String(a["id"] ?? "")}`,
2381
2689
  execute: async (args) => {
2382
- const a = parse(external_exports.object({ id: ScriptId, profile: Profile }), args);
2383
- return { ...await runner.tasks(a.id, ref(a.profile)), profiles: await runner.profiles.list(a.id) };
2690
+ const a = parse(external_exports.object({ id: ScriptId, profile: Profile, guide: external_exports.boolean().nullish() }), args);
2691
+ const listed = { ...await runner.tasks(a.id, ref(a.profile)), profiles: await runner.profiles.list(a.id) };
2692
+ const manifest = a.guide === true ? config.library.packOf(a.id)?.manifest : void 0;
2693
+ if (manifest === void 0)
2694
+ return listed;
2695
+ const { tasks: _tasks, packId: _packId, builtin: _builtin, ...guide } = guideView(manifest, { builtin: false });
2696
+ return { ...listed, guide };
2384
2697
  }
2385
2698
  }),
2386
2699
  tool({
@@ -2446,21 +2759,34 @@ function runnerTools(runner, config) {
2446
2759
  }),
2447
2760
  tool({
2448
2761
  name: TOOL_NAMES.runs,
2449
- description: "\u67E5\u770B\u6700\u8FD1\u7684\u8FD0\u884C\u8BB0\u5F55\u548C\u5B83\u4EEC\u6700\u540E\u51E0\u884C\u65E5\u5FD7\uFF1B\u5E26 run_id \u65F6\u8FD4\u56DE\u8FD9\u4E00\u6B21\u8FD0\u884C\u7684\u8BE6\u60C5\u548C\u66F4\u591A\u65E5\u5FD7\u3002",
2450
- properties: { id: { ...id, description: "\u53EA\u770B\u8FD9\u4E2A\u811A\u672C\u7684\u8FD0\u884C\u3002" }, run_id: { type: "string", description: "\u67E5\u770B\u8FD9\u4E00\u6B21\u8FD0\u884C\u3002" } },
2762
+ description: "\u67E5\u770B\u6700\u8FD1\u7684\u8FD0\u884C\u8BB0\u5F55\u548C\u5B83\u4EEC\u6700\u540E\u51E0\u884C\u65E5\u5FD7\uFF1B\u5E26 run_id \u65F6\u8FD4\u56DE\u8FD9\u4E00\u6B21\u8FD0\u884C\u7684\u8BE6\u60C5\u548C\u66F4\u591A\u65E5\u5FD7\u3002\u8981\u7B49\u4E00\u6B21\u8FD0\u884C\uFF08\u76D1\u63A7\u3001\u6D41\u6C34\u7EBF\u3001\u91CD\u8BD5\u6216\u522B\u7684 agent \u5F00\u7684\u4E5F\u884C\uFF09\u7ED3\u675F\uFF0C\u5E26\u4E0A run_id \u548C wait_seconds\uFF1A\u5B83\u4F1A\u7B49\u5230\u7ED3\u675F\uFF08\u88AB\u91CD\u65B0\u8FD0\u884C\u7684\u8BDD\u4E00\u76F4\u8DDF\u5230\u6700\u540E\u90A3\u6B21\uFF09\u518D\u8FD4\u56DE\uFF0C\u4E0D\u8981\u4E00\u904D\u904D\u67E5\u3002",
2763
+ properties: {
2764
+ id: { ...id, description: "\u53EA\u770B\u8FD9\u4E2A\u811A\u672C\u7684\u8FD0\u884C\u3002" },
2765
+ run_id: { type: "string", description: "\u67E5\u770B\u8FD9\u4E00\u6B21\u8FD0\u884C\u3002" },
2766
+ wait_seconds: { type: "integer", description: `\u548C run_id \u4E00\u8D77\u7528\uFF1A\u6700\u591A\u7B49\u8FD9\u4E48\u591A\u79D2\uFF081\u2013${MAX_WAIT_SECONDS}\uFF09\uFF0C\u8FD0\u884C\u7ED3\u675F\u5C31\u7ACB\u523B\u8FD4\u56DE\u3002\u5728 run_code \u7A0B\u5E8F\u91CC\u8C03\u7528\u65F6\uFF0C\u4E0D\u8981\u8D85\u8FC7\u90A3\u4E2A\u7A0B\u5E8F\u81EA\u5DF1\u7684\u65F6\u9650\uFF08\u9ED8\u8BA4 2 \u5206\u949F\uFF0C\u6700\u957F 10 \u5206\u949F\uFF09\u3002` }
2767
+ },
2451
2768
  readOnly: true,
2769
+ // The longest wait, and a little for the answer.
2770
+ timeoutMs: (MAX_WAIT_SECONDS + 60) * 1e3,
2452
2771
  kind: "read",
2453
- title: () => "\u67E5\u770B\u8FD0\u884C\u8BB0\u5F55",
2454
- execute: async (args) => {
2455
- const a = parse(external_exports.object({ id: ScriptId.nullish(), run_id: external_exports.string().nullish() }), args);
2456
- if (a.run_id !== void 0 && a.run_id !== null)
2457
- return brief(runner, a.run_id, 80);
2772
+ title: (a) => a["wait_seconds"] === void 0 ? "\u67E5\u770B\u8FD0\u884C\u8BB0\u5F55" : `\u7B49\u8FD0\u884C\u7ED3\u675F\uFF1A${String(a["run_id"] ?? "")}`,
2773
+ execute: async (args, exec) => {
2774
+ const a = parse(external_exports.object({ id: ScriptId.nullish(), run_id: external_exports.string().nullish(), wait_seconds: external_exports.number().int().min(1).max(MAX_WAIT_SECONDS).nullish() }), args);
2775
+ if (a.run_id !== void 0 && a.run_id !== null) {
2776
+ if (a.wait_seconds === void 0 || a.wait_seconds === null)
2777
+ return brief(runner, a.run_id, 80);
2778
+ const watch = config.watchInput?.(exec);
2779
+ const waited = await waitForRun(runner, a.run_id, a.wait_seconds * 1e3, { signal: exec.signal, ...watch === void 0 ? {} : { input: watch.signal } }).finally(() => watch?.dispose());
2780
+ return { ...brief(runner, waited.runId, 30), waited: waitedView(a.run_id, waited) };
2781
+ }
2782
+ if (a.wait_seconds !== void 0 && a.wait_seconds !== null)
2783
+ throw new Error("wait_seconds \u8981\u548C run_id \u4E00\u8D77\u7528\uFF1A\u5148\u7528 script_runs \u627E\u5230\u8981\u7B49\u7684\u90A3\u6B21\u8FD0\u884C");
2458
2784
  return { runs: runner.list(a.id ?? void 0).slice(0, 10).map((r) => brief(runner, r.id, 5)) };
2459
2785
  }
2460
2786
  }),
2461
2787
  tool({
2462
2788
  name: TOOL_NAMES.runLog,
2463
- description: "\u8BFB\u4E00\u6B21\u8FD0\u884C\u4FDD\u5B58\u4E0B\u6765\u7684\u5B8C\u6574\u65E5\u5FD7\uFF08\u5305\u62EC\u7A0B\u5E8F\u91CD\u542F\u524D\u7684\u8FD0\u884C\uFF09\uFF0C\u7528\u6765\u6392\u67E5\u95EE\u9898\uFF1A\u53EF\u4EE5\u6309\u6587\u5B57\u6216 /\u6B63\u5219/ \u641C\u7D22\u3001\u53EA\u770B\u9519\u8BEF\u6216\u8B66\u544A\u3001\u4ECE\u67D0\u4E00\u884C\u5F00\u59CB\u5F80\u540E\u7FFB\u3002script_runs \u53EA\u7ED9\u6700\u540E\u51E0\u884C\uFF0C\u8FD9\u91CC\u80FD\u770B\u5168\u90E8\u3002",
2789
+ description: "\u8BFB\u4E00\u6B21\u8FD0\u884C\u4FDD\u5B58\u4E0B\u6765\u7684\u5B8C\u6574\u65E5\u5FD7\uFF08\u5305\u62EC\u7A0B\u5E8F\u91CD\u542F\u524D\u7684\u8FD0\u884C\uFF09\uFF0C\u7528\u6765\u6392\u67E5\u95EE\u9898\uFF1A\u53EF\u4EE5\u6309\u6587\u5B57\u6216 /\u6B63\u5219/ \u641C\u7D22\u3001\u53EA\u770B\u9519\u8BEF\u6216\u8B66\u544A\u3001\u4ECE\u67D0\u4E00\u884C\u5F00\u59CB\u5F80\u540E\u7FFB\u3002script_runs \u53EA\u7ED9\u6700\u540E\u51E0\u884C\uFF0C\u8FD9\u91CC\u80FD\u770B\u5168\u90E8\u3002\u65E5\u5FD7\u6309\u4FDD\u7559\u89C4\u5219\u6E05\u7406\uFF1A\u6BCF\u4E2A\u811A\u672C\u53EA\u7559\u6700\u8FD1\u7EA6 64 MiB\uFF08\u538B\u7F29\u540E\uFF09\u7684\u8FD0\u884C\u65E5\u5FD7\uFF0C\u4E00\u6B21\u8FD0\u884C\u7684\u65E5\u5FD7\u8D85\u8FC7 64 MiB \u65F6\u53EA\u7559\u540E\u9762\u7684\u90E8\u5206\uFF0C\u8FD0\u884C\u8BB0\u5F55 30 \u5929\u540E\u5220\u9664\u3002",
2464
2790
  properties: {
2465
2791
  run_id: { type: "string", description: "\u8FD0\u884C id\uFF08script_runs \u6216\u5F02\u5E38\u8BB0\u5F55\u91CC\u6709\uFF09\u3002" },
2466
2792
  search: { type: "string", description: "\u8981\u627E\u7684\u6587\u5B57\uFF0C\u6216 /\u6B63\u5219/\uFF08\u4E0D\u533A\u5206\u5927\u5C0F\u5199\uFF09\u3002" },
@@ -2539,6 +2865,7 @@ var ConfigSchema = external_exports.object({
2539
2865
  /** Run records, logs and config backups: `<dataDir>/runs/<id>/`. */
2540
2866
  dataDir: external_exports.string().min(1)
2541
2867
  });
2868
+ var TIDY_EVERY_MS = 24 * 60 * 6e4;
2542
2869
  var AdgRunner = class extends Service {
2543
2870
  static inject = ["adgScripts"];
2544
2871
  runner;
@@ -2564,7 +2891,13 @@ var AdgRunner = class extends Service {
2564
2891
  log: { info: (m) => log.info(m), warn: (m) => log.warn(m) }
2565
2892
  });
2566
2893
  const runner = this.runner;
2567
- void runner.loadHistory().catch((error) => log.warn(`loading run history failed: ${String(error)}`));
2894
+ const tidy = () => runner.tidy().catch((error) => log.warn(`tidying run logs failed: ${String(error)}`));
2895
+ void runner.loadHistory().catch((error) => log.warn(`loading run history failed: ${String(error)}`)).then(tidy);
2896
+ ctx.effect(() => {
2897
+ const every = setInterval(() => void tidy(), TIDY_EVERY_MS);
2898
+ every.unref();
2899
+ return () => clearInterval(every);
2900
+ }, "adg-runner run log retention");
2568
2901
  const library = { get: (id) => scripts.library.get(id), packOf: (id) => scripts.library.packOf(id) };
2569
2902
  const profilesChanged = async (scriptId) => {
2570
2903
  const list = await runner.profiles.list(scriptId);
@@ -2576,7 +2909,8 @@ var AdgRunner = class extends Service {
2576
2909
  }, "adg-runner runs");
2577
2910
  ctx.inject(["adgGateway"], (gateway) => gateway.adgGateway.agentPart("adg-runner tools", (agent) => {
2578
2911
  const registered = [];
2579
- for (const tool2 of runnerTools(runner, { library, dataDir: spec.dataDir, profilesChanged })) {
2912
+ const watchInput = (exec) => gateway.adgGateway.watchInput(exec);
2913
+ for (const tool2 of runnerTools(runner, { library, dataDir: spec.dataDir, profilesChanged, watchInput })) {
2580
2914
  registered.push(agent.tools.register({ ...tool2, execute: async (args, exec) => {
2581
2915
  await scripts.ready;
2582
2916
  await ctx.get("adgGateway")?.guardTool(exec);
@@ -2709,6 +3043,12 @@ export {
2709
3043
  ConfigProfiles,
2710
3044
  declaredFiles,
2711
3045
  LogTail,
3046
+ LIVE_LOG_MAX,
3047
+ SCRIPT_LOG_BUDGET,
3048
+ PACK_AFTER_MS,
3049
+ KEEP_DAYS,
3050
+ tidyRuns,
3051
+ readRunLog,
2712
3052
  Runner,
2713
3053
  parseDuration,
2714
3054
  killTree,