dsh-multigameassistant 2.0.5 → 2.1.1

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 (37) hide show
  1. package/cordis.patch.yml +178 -4
  2. package/lib/analyzer.js +6 -4
  3. package/lib/browser.js +279 -0
  4. package/lib/{chunk-KHO3SRUJ.js → chunk-5PDYWE24.js} +4 -2
  5. package/lib/{chunk-YG4B5G7F.js → chunk-B4UT4NYH.js} +1 -0
  6. package/lib/{chunk-IOBYH4RN.js → chunk-FBDVN6Q2.js} +76 -1
  7. package/lib/{chunk-TD4YFQWE.js → chunk-MQG5FLOG.js} +629 -167
  8. package/lib/chunk-NM6H6WCQ.js +3753 -0
  9. package/lib/chunk-RESS7WVY.js +157 -0
  10. package/lib/{chunk-BTT2GBTQ.js → chunk-SHTX4AGU.js} +1 -3670
  11. package/lib/{chunk-4Q4EH73S.js → chunk-UQLHGLMP.js} +13 -9
  12. package/lib/{chunk-PAJOD6LV.js → chunk-VOTN4IHB.js} +384 -54
  13. package/lib/emulator.js +6 -4
  14. package/lib/feishu.js +8 -6
  15. package/lib/game-intel.js +90 -9
  16. package/lib/gateway.js +11 -6
  17. package/lib/guard.js +5 -3
  18. package/lib/intervene.js +62 -18
  19. package/lib/low-context.js +13 -2
  20. package/lib/monitor.js +90 -10
  21. package/lib/notify.js +6 -5
  22. package/lib/orchestrator.js +14 -10
  23. package/lib/qqbot.js +8 -6
  24. package/lib/runner.js +18 -5
  25. package/lib/scheduler.js +4 -2
  26. package/lib/script-registry.js +345 -216
  27. package/package.json +5 -4
  28. package/skills/pipeline-planning.md +1 -1
  29. package/skills/web-reading.md +2 -0
  30. package/web/assets/index-CL3SeTW9.css +1 -0
  31. package/web/assets/index-GYwpGP3f.js +244 -0
  32. package/web/assets/index-GYwpGP3f.js.map +1 -0
  33. package/web/index.html +2 -2
  34. package/lib/chunk-CCAB6XXZ.js +0 -34
  35. package/web/assets/index-BuStplKb.js +0 -242
  36. package/web/assets/index-BuStplKb.js.map +0 -1
  37. package/web/assets/index-CSB3B28L.css +0 -1
@@ -4,12 +4,14 @@ import {
4
4
  guideView,
5
5
  renderTask,
6
6
  require_dist
7
- } from "./chunk-KHO3SRUJ.js";
7
+ } from "./chunk-5PDYWE24.js";
8
8
  import {
9
9
  RUNS_CAPABILITY,
10
- ScriptId,
10
+ ScriptId
11
+ } from "./chunk-NM6H6WCQ.js";
12
+ import {
11
13
  external_exports
12
- } from "./chunk-BTT2GBTQ.js";
14
+ } from "./chunk-SHTX4AGU.js";
13
15
  import {
14
16
  __toESM
15
17
  } from "./chunk-2UFLGPDY.js";
@@ -19,8 +21,8 @@ import { Service } from "@deepseek-ai/cordis";
19
21
 
20
22
  // packages/runner/lib/runs.js
21
23
  import { spawn as spawn2, execFile as execFile4 } from "node:child_process";
22
- import { appendFile, mkdir as mkdir4, readdir as readdir3, readFile as readFile4, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
23
- 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";
24
26
 
25
27
  // packages/runner/lib/choices.js
26
28
  var import_yaml = __toESM(require_dist(), 1);
@@ -1063,7 +1065,13 @@ async function locateGame(options) {
1063
1065
  for (const path of probe.running)
1064
1066
  if (basename2(path).toLowerCase() === want)
1065
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);
1066
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" });
1067
1075
  for (const entry of probe.entries) {
1068
1076
  if (!matches2(entry.name))
1069
1077
  continue;
@@ -1079,8 +1087,12 @@ async function locateGame(options) {
1079
1087
  continue;
1080
1088
  if (basename2(link.target).toLowerCase() === want)
1081
1089
  add(link.target, `\u5FEB\u6377\u65B9\u5F0F\u300C${link.name}\u300D`);
1082
- else
1090
+ else {
1083
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
+ }
1084
1096
  }
1085
1097
  const budget = { folders: options.maxFolders ?? 4e4, until: Date.now() + (options.maxMs ?? 2e4) };
1086
1098
  const walk = async (dir, depth, matched, source) => {
@@ -1127,14 +1139,44 @@ function drives() {
1127
1139
  var PROBE = `
1128
1140
  $ErrorActionPreference = 'SilentlyContinue'
1129
1141
  [Console]::OutputEncoding = [Text.Encoding]::UTF8
1130
- $stem = [IO.Path]::GetFileNameWithoutExtension($env:ADG_GAME_EXE)
1142
+ $exe = $env:ADG_GAME_EXE
1143
+ $stem = [IO.Path]::GetFileNameWithoutExtension($exe)
1131
1144
  $running = @(Get-Process -Name $stem | ForEach-Object { $_.Path } | Where-Object { $_ })
1132
1145
  $keys = 'HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*', 'HKLM:\\Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*', 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'
1133
1146
  $entries = @(Get-ItemProperty $keys | Where-Object { $_.DisplayName } | ForEach-Object { @{ name = [string]$_.DisplayName; location = [string]$_.InstallLocation; icon = [string]$_.DisplayIcon } })
1134
1147
  $shell = New-Object -ComObject WScript.Shell
1135
1148
  $dirs = @([Environment]::GetFolderPath('CommonStartMenu'), [Environment]::GetFolderPath('StartMenu'), [Environment]::GetFolderPath('Desktop'), [Environment]::GetFolderPath('CommonDesktopDirectory'))
1136
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 } } } })
1137
- @{ 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
1138
1180
  `;
1139
1181
  function windowsProbe(exe) {
1140
1182
  if (process.platform !== "win32")
@@ -1151,7 +1193,7 @@ function windowsProbe(exe) {
1151
1193
  try {
1152
1194
  const raw = JSON.parse(String(stdout).trim());
1153
1195
  const list = (v) => Array.isArray(v) ? v : v === null || v === void 0 ? [] : [v];
1154
- 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) });
1155
1197
  } catch (e) {
1156
1198
  reject(e);
1157
1199
  }
@@ -1159,10 +1201,153 @@ function windowsProbe(exe) {
1159
1201
  });
1160
1202
  }
1161
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
+
1162
1348
  // packages/runner/lib/runs.js
1163
1349
  var KEEP_RUNS = 50;
1164
1350
  var KEEP_LINES = 2e3;
1165
- var KEEP_DAYS = 30;
1166
1351
  var Runner = class {
1167
1352
  locks = new ResourceLocks();
1168
1353
  /** The local config copies runs use. */
@@ -1178,6 +1363,8 @@ var Runner = class {
1178
1363
  #successorAborts = /* @__PURE__ */ new Map();
1179
1364
  /** Runs someone is still deciding about (the monitor handling an incident) → how many, and who waits. */
1180
1365
  #holds = /* @__PURE__ */ new Map();
1366
+ /** The retention pass going on (tidy). */
1367
+ #tidying = Promise.resolve();
1181
1368
  #now;
1182
1369
  constructor(options) {
1183
1370
  this.#options = options;
@@ -1231,7 +1418,7 @@ var Runner = class {
1231
1418
  if (text === void 0)
1232
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`);
1233
1420
  const { list, value } = listWithNew(spec, text, name.trim());
1234
- 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, "-"));
1235
1422
  await this.profiles.write(scriptId, script.dir, pack.manifest, spec.file, spec.list, list, historyDir, profile);
1236
1423
  return value;
1237
1424
  }
@@ -1287,6 +1474,20 @@ var Runner = class {
1287
1474
  const name = exe.toLowerCase().endsWith(".exe") ? exe : `${exe}.exe`;
1288
1475
  return { exe: name, candidates: await locateGame({ exe: name, keywords: gameKeywords(game ?? {}), ...signal === void 0 ? {} : { signal } }) };
1289
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
+ }
1290
1491
  /** Follow every run's state and lines. @returns a disposer. */
1291
1492
  watch(listener) {
1292
1493
  this.#listeners.add(listener);
@@ -1308,21 +1509,18 @@ var Runner = class {
1308
1509
  * memory), also for runs from before a restart, searched and paged.
1309
1510
  */
1310
1511
  async readLog(runId, query = {}) {
1311
- const file = join5(this.#options.dataDir, "runs", runId, "log.jsonl");
1312
- let all;
1313
- try {
1314
- all = (await readFile4(file, "utf8")).split("\n").filter((l) => l !== "").flatMap((l) => {
1315
- try {
1316
- return [JSON.parse(l)];
1317
- } catch {
1318
- return [];
1319
- }
1320
- });
1321
- } catch {
1322
- all = this.#runs.get(runId)?.lines ?? [];
1323
- 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
1324
1521
  throw new Error(`\u6CA1\u6709\u8FD0\u884C\u8BB0\u5F55 ${runId}`);
1325
1522
  }
1523
+ const file = await runLogFile(dir);
1326
1524
  const pattern = query.search === void 0 || query.search === "" ? void 0 : toPattern(query.search);
1327
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)));
1328
1526
  const limit = Math.max(1, Math.min(query.limit ?? 200, 2e3));
@@ -1334,24 +1532,24 @@ var Runner = class {
1334
1532
  * the restart is marked failed. Old run folders are removed.
1335
1533
  */
1336
1534
  async loadHistory() {
1337
- const root = join5(this.#options.dataDir, "runs");
1535
+ const root = join6(this.#options.dataDir, "runs");
1338
1536
  let names;
1339
1537
  try {
1340
- names = await readdir3(root);
1538
+ names = await readdir4(root);
1341
1539
  } catch {
1342
1540
  return;
1343
1541
  }
1344
1542
  const infos = [];
1345
1543
  for (const name of names) {
1346
1544
  try {
1347
- 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"));
1348
1546
  if (info.endedAt === void 0) {
1349
1547
  Object.assign(info, { state: "failed", outcome: "\u7A0B\u5E8F\u9000\u51FA\u65F6\u4E2D\u65AD", endedAt: info.startedAt });
1350
- 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(() => {
1351
1549
  });
1352
1550
  }
1353
1551
  if (this.#now() - info.endedAt > KEEP_DAYS * 864e5) {
1354
- await rm2(join5(root, name), { recursive: true, force: true }).catch(() => {
1552
+ await rm3(join6(root, name), { recursive: true, force: true }).catch(() => {
1355
1553
  });
1356
1554
  continue;
1357
1555
  }
@@ -1370,6 +1568,9 @@ var Runner = class {
1370
1568
  controller: new AbortController(),
1371
1569
  lines: [],
1372
1570
  pendingLines: [],
1571
+ logText: [],
1572
+ writing: Promise.resolve(),
1573
+ logBytes: 0,
1373
1574
  release: [],
1374
1575
  finished: Promise.resolve(info),
1375
1576
  resolveFinished: () => {
@@ -1378,6 +1579,28 @@ var Runner = class {
1378
1579
  });
1379
1580
  }
1380
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
+ }
1381
1604
  /** Settles when the run ends. */
1382
1605
  finished(runId) {
1383
1606
  return this.#run(runId).finished;
@@ -1572,6 +1795,9 @@ var Runner = class {
1572
1795
  controller: new AbortController(),
1573
1796
  lines: [],
1574
1797
  pendingLines: [],
1798
+ logText: [],
1799
+ writing: Promise.resolve(),
1800
+ logBytes: 0,
1575
1801
  release: [],
1576
1802
  finished,
1577
1803
  resolveFinished
@@ -1597,9 +1823,9 @@ var Runner = class {
1597
1823
  run.release.push(() => signal.removeEventListener("abort", callOff));
1598
1824
  }
1599
1825
  }
1600
- const runDir = join5(this.#options.dataDir, "runs", runId);
1826
+ const runDir = join6(this.#options.dataDir, "runs", runId);
1601
1827
  await mkdir4(runDir, { recursive: true });
1602
- 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(() => {
1603
1829
  });
1604
1830
  this.#publish(run);
1605
1831
  let launchedGame;
@@ -1677,7 +1903,7 @@ var Runner = class {
1677
1903
  run.info.state = "running";
1678
1904
  this.#line(run, "adg", `\u5DF2\u542F\u52A8\uFF1A${run.info.command.map(quote).join(" ")}`);
1679
1905
  this.#publish(run);
1680
- 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(() => {
1681
1907
  });
1682
1908
  return run.info;
1683
1909
  } catch (error) {
@@ -1919,6 +2145,8 @@ var Runner = class {
1919
2145
  async dispose() {
1920
2146
  await Promise.all([...this.#runs.values()].filter((r) => r.info.endedAt === void 0).map((r) => this.stop(r.info.id).catch(() => {
1921
2147
  })));
2148
+ await this.#tidying.catch(() => {
2149
+ });
1922
2150
  }
1923
2151
  #follow(run, manifest, dir) {
1924
2152
  const rules = manifest.logs.rules.map((rule) => ({ rule, pattern: new RegExp(rule.match) }));
@@ -1998,13 +2226,15 @@ var Runner = class {
1998
2226
  this.#line(run, "adg", `${state === "succeeded" ? "\u5B8C\u6210" : state === "cancelled" ? "\u5DF2\u505C\u6B62" : "\u5931\u8D25"}\uFF1A${reason}`);
1999
2227
  this.#flush(run);
2000
2228
  this.#publish(run);
2001
- const runDir = join5(this.#options.dataDir, "runs", run.info.id);
2229
+ const runDir = join6(this.#options.dataDir, "runs", run.info.id);
2002
2230
  await mkdir4(runDir, { recursive: true }).catch(() => {
2003
2231
  });
2004
- 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(() => {
2005
2233
  });
2234
+ await run.writing;
2006
2235
  this.#options.log.info(`run ${run.info.id} ${state}: ${reason}`);
2007
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)}`));
2008
2238
  }
2009
2239
  #line(run, source, text) {
2010
2240
  this.#push(run, { at: this.#now(), source, text });
@@ -2014,29 +2244,41 @@ var Runner = class {
2014
2244
  if (run.lines.length > KEEP_LINES)
2015
2245
  run.lines.splice(0, run.lines.length - KEEP_LINES);
2016
2246
  run.pendingLines.push(line);
2247
+ run.logText.push(`${JSON.stringify(line)}
2248
+ `);
2017
2249
  for (const listener of this.#listeners) {
2018
2250
  try {
2019
2251
  listener.line?.(run.info, line);
2020
2252
  } catch {
2021
2253
  }
2022
2254
  }
2023
- const dir = join5(this.#options.dataDir, "runs", run.info.id);
2024
- void appendFile(join5(dir, "log.jsonl"), `${JSON.stringify(line)}
2025
- `).catch(() => {
2026
- });
2027
- void appendFile(join5(dir, "log.txt"), `${new Date(line.at).toISOString()} [${line.source}]${line.level === void 0 ? "" : ` [${line.level}]`} ${line.text}
2028
- `).catch(() => {
2029
- });
2030
2255
  if (run.flushTimer === void 0)
2031
2256
  run.flushTimer = setTimeout(() => this.#flush(run), 100);
2032
2257
  }
2033
2258
  #flush(run) {
2034
2259
  clearTimeout(run.flushTimer);
2035
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
+ }
2036
2267
  if (run.pendingLines.length === 0)
2037
2268
  return;
2038
2269
  this.#options.onLog(run.info.id, run.pendingLines.splice(0));
2039
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
+ }
2040
2282
  #publish(run) {
2041
2283
  const snapshot = { ...run.info, resources: [...run.info.resources], tags: [...run.info.tags], warnings: [...run.info.warnings] };
2042
2284
  this.#options.onState(snapshot);
@@ -2119,7 +2361,7 @@ function quote(value) {
2119
2361
  }
2120
2362
 
2121
2363
  // packages/runner/lib/config.js
2122
- import { join as join6 } from "node:path";
2364
+ import { join as join7 } from "node:path";
2123
2365
  var MAX_READ = 6e4;
2124
2366
  function allowed(manifest, file) {
2125
2367
  const normalized = file.replace(/\\/g, "/");
@@ -2150,9 +2392,9 @@ async function writeConfig(library, profiles, dataDir, scriptId, file, path, val
2150
2392
  allowed(manifest, file);
2151
2393
  const profile = await profiles.resolve(scriptId, profileRef);
2152
2394
  const stamp = new Date(now).toISOString().replace(/[:.]/g, "-");
2153
- 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}`);
2154
2396
  await profiles.write(scriptId, dir, manifest, file, path, value, historyDir, profile.id);
2155
- return { file, backup: join6(historyDir, file), copy: "local", profile: profile.name };
2397
+ return { file, backup: join7(historyDir, file), copy: "local", profile: profile.name };
2156
2398
  }
2157
2399
  async function configStatus(library, profiles, scriptId, profileRef) {
2158
2400
  const { manifest, dir } = packFor(library, scriptId);
@@ -2245,6 +2487,67 @@ var brief = (runner, runId, lines = 15) => {
2245
2487
  last_lines: runner.logs(runId, lines).map((l) => `[${l.source}] ${l.text}`)
2246
2488
  };
2247
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
+ }
2248
2551
  function runnerTools(runner, config) {
2249
2552
  const id = { type: "string", description: "\u811A\u672C\u5E93\u91CC\u7684\u811A\u672C id\uFF08script_list \u53EF\u67E5\uFF09\u3002" };
2250
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" };
@@ -2456,21 +2759,34 @@ function runnerTools(runner, config) {
2456
2759
  }),
2457
2760
  tool({
2458
2761
  name: TOOL_NAMES.runs,
2459
- 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",
2460
- 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
+ },
2461
2768
  readOnly: true,
2769
+ // The longest wait, and a little for the answer.
2770
+ timeoutMs: (MAX_WAIT_SECONDS + 60) * 1e3,
2462
2771
  kind: "read",
2463
- title: () => "\u67E5\u770B\u8FD0\u884C\u8BB0\u5F55",
2464
- execute: async (args) => {
2465
- const a = parse(external_exports.object({ id: ScriptId.nullish(), run_id: external_exports.string().nullish() }), args);
2466
- if (a.run_id !== void 0 && a.run_id !== null)
2467
- 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");
2468
2784
  return { runs: runner.list(a.id ?? void 0).slice(0, 10).map((r) => brief(runner, r.id, 5)) };
2469
2785
  }
2470
2786
  }),
2471
2787
  tool({
2472
2788
  name: TOOL_NAMES.runLog,
2473
- 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",
2474
2790
  properties: {
2475
2791
  run_id: { type: "string", description: "\u8FD0\u884C id\uFF08script_runs \u6216\u5F02\u5E38\u8BB0\u5F55\u91CC\u6709\uFF09\u3002" },
2476
2792
  search: { type: "string", description: "\u8981\u627E\u7684\u6587\u5B57\uFF0C\u6216 /\u6B63\u5219/\uFF08\u4E0D\u533A\u5206\u5927\u5C0F\u5199\uFF09\u3002" },
@@ -2549,6 +2865,7 @@ var ConfigSchema = external_exports.object({
2549
2865
  /** Run records, logs and config backups: `<dataDir>/runs/<id>/`. */
2550
2866
  dataDir: external_exports.string().min(1)
2551
2867
  });
2868
+ var TIDY_EVERY_MS = 24 * 60 * 6e4;
2552
2869
  var AdgRunner = class extends Service {
2553
2870
  static inject = ["adgScripts"];
2554
2871
  runner;
@@ -2574,7 +2891,13 @@ var AdgRunner = class extends Service {
2574
2891
  log: { info: (m) => log.info(m), warn: (m) => log.warn(m) }
2575
2892
  });
2576
2893
  const runner = this.runner;
2577
- 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");
2578
2901
  const library = { get: (id) => scripts.library.get(id), packOf: (id) => scripts.library.packOf(id) };
2579
2902
  const profilesChanged = async (scriptId) => {
2580
2903
  const list = await runner.profiles.list(scriptId);
@@ -2586,7 +2909,8 @@ var AdgRunner = class extends Service {
2586
2909
  }, "adg-runner runs");
2587
2910
  ctx.inject(["adgGateway"], (gateway) => gateway.adgGateway.agentPart("adg-runner tools", (agent) => {
2588
2911
  const registered = [];
2589
- 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 })) {
2590
2914
  registered.push(agent.tools.register({ ...tool2, execute: async (args, exec) => {
2591
2915
  await scripts.ready;
2592
2916
  await ctx.get("adgGateway")?.guardTool(exec);
@@ -2719,6 +3043,12 @@ export {
2719
3043
  ConfigProfiles,
2720
3044
  declaredFiles,
2721
3045
  LogTail,
3046
+ LIVE_LOG_MAX,
3047
+ SCRIPT_LOG_BUDGET,
3048
+ PACK_AFTER_MS,
3049
+ KEEP_DAYS,
3050
+ tidyRuns,
3051
+ readRunLog,
2722
3052
  Runner,
2723
3053
  parseDuration,
2724
3054
  killTree,