@qianhaoq/dsh-dota2ai 0.2.12 → 0.2.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -7448,7 +7448,8 @@ var TOOL_DOCS = {
7448
7448
  description: "dota2.ai's main review: the coach watches this game's replay (every death, ultimate, fight and item) and writes what one player could have changed, each point backed by replay evidence (times, numbers) that was checked, plus what they did well, what to do next game, and what the replay cannot show. Needs the hero the user played (pick_hero lists the game's heroes). A first review takes 2\u20134 minutes: while status is parsing or reviewing, call again with the same arguments after poll_after_sec. Starts are limited per caller (about five reviews per ten minutes). Replays exist for about two weeks after a game. lang: en | zh.",
7449
7449
  params: {
7450
7450
  hero: "The hero the user played: key (queen_of_pain), English or Chinese name, or hero id",
7451
- retry: "Start again after status failed (a new start, counted on the limit)"
7451
+ retry: "Start again after status failed (a new start, counted on the limit)",
7452
+ refresh: "Regenerate under the latest coach version when a cached review is from an older version (a new start)"
7452
7453
  },
7453
7454
  // In the DSH plugin the review runs on the user's own DSH model and is kept on their machine: no site limit,
7454
7455
  // and the public page would not show it.
@@ -9895,11 +9896,11 @@ function track(list, state, on, t6, value) {
9895
9896
  function linkHeroNames(trace) {
9896
9897
  if (!Array.isArray(trace?.heroes) || !Array.isArray(trace?.names)) return trace;
9897
9898
  const logged = new Set(trace.names);
9898
- const PREFIX2 = "npc_dota_hero_";
9899
+ const PREFIX3 = "npc_dota_hero_";
9899
9900
  for (const h of trace.heroes) {
9900
9901
  if (typeof h?.key !== "string" || logged.has(h.npc)) continue;
9901
9902
  const want = h.key.replace(/_/g, "");
9902
- const found = trace.names.filter((n) => typeof n === "string" && n.startsWith(PREFIX2) && n.slice(PREFIX2.length).replace(/_/g, "") === want);
9903
+ const found = trace.names.filter((n) => typeof n === "string" && n.startsWith(PREFIX3) && n.slice(PREFIX3.length).replace(/_/g, "") === want);
9903
9904
  if (found.length === 1) h.npc = found[0];
9904
9905
  }
9905
9906
  return trace;
@@ -12282,16 +12283,236 @@ function fightTimeline(trace, args = {}, ctx = {}) {
12282
12283
  };
12283
12284
  }
12284
12285
  var CONSUMABLE = /^item_(tango|clarity|flask|faerie_fire|branches|ward_|enchanted_mango|famango|great_famango|tpscroll|smoke_of_deceit|dust|blood_grenade|tome_of_knowledge|infused_raindrop|bottle|madstone|recipe_)/;
12285
- function itemTimeline(trace, args = {}) {
12286
+ var POWER_TREADS_STAT_ALTS = ["belt_of_strength", "boots_of_elves", "robe"];
12287
+ function teamCourierDeaths(trace, heroTeam) {
12288
+ if (!Array.isArray(trace.creep_kills)) return null;
12289
+ const out = [];
12290
+ for (const row of trace.creep_kills) {
12291
+ if (!Array.isArray(row) || row[2] !== "c" || !Number.isFinite(row[0])) continue;
12292
+ const ah = heroOfName(trace, row[1]);
12293
+ if (ah < 0 || trace.heroes[ah].team === heroTeam) continue;
12294
+ out.push({ t: row[0], clock: clock3(row[0]), killed_by: trace.heroes[ah].key });
12295
+ }
12296
+ out.sort((a, b) => a.t - b.t);
12297
+ return out;
12298
+ }
12299
+ function itemRecipeSpec(key, patchItems) {
12300
+ const def = patchItems?.[key];
12301
+ if (!def || typeof def !== "object") return null;
12302
+ const comps = Array.isArray(def.components) ? def.components.filter((c) => typeof c === "string" && c.length > 0) : [];
12303
+ const recipeKey = `recipe_${key}`;
12304
+ const hasRecipe = Number(patchItems?.[recipeKey]?.cost) > 0;
12305
+ if (!comps.length && !hasRecipe) {
12306
+ return def.created === true ? { composite: true, parts: null } : { composite: false, parts: [] };
12307
+ }
12308
+ return { composite: true, parts: [...comps, ...hasRecipe ? [recipeKey] : []] };
12309
+ }
12310
+ function recipeDepth(key, patchItems, seen = /* @__PURE__ */ new Set()) {
12311
+ if (seen.has(key)) return 0;
12312
+ const spec = itemRecipeSpec(key, patchItems);
12313
+ if (!spec?.composite || !spec.parts?.length) return 0;
12314
+ seen.add(key);
12315
+ let d = 1;
12316
+ for (const p of spec.parts) d = Math.max(d, 1 + recipeDepth(p, patchItems, seen));
12317
+ seen.delete(key);
12318
+ return d;
12319
+ }
12320
+ function buildPurchaseMatcher(trace, h, patchItems) {
12321
+ if (!Array.isArray(trace.purchases) || !patchItems) return () => null;
12322
+ const npc = nameId(trace, trace.heroes[h].npc);
12323
+ const rawPurchases = [];
12324
+ if (npc >= 0) {
12325
+ for (let i = 0; i < trace.purchases.length; i += 1) {
12326
+ const p = trace.purchases[i];
12327
+ if (!Array.isArray(p) || p[1] !== npc || !Number.isFinite(p[0])) continue;
12328
+ const raw = trace.names[p[2]];
12329
+ if (typeof raw !== "string" || !raw.startsWith("item_")) continue;
12330
+ rawPurchases.push({ t: p[0], item: raw.slice(5), row: p[3] ?? i, ord: i });
12331
+ }
12332
+ }
12333
+ rawPurchases.sort((a, b) => a.t - b.t || (a.row ?? 0) - (b.row ?? 0) || a.ord - b.ord);
12334
+ const pool = [];
12335
+ for (const p of rawPurchases) {
12336
+ const spec = itemRecipeSpec(p.item, patchItems);
12337
+ if (!spec?.composite) {
12338
+ pool.push({ item: p.item, createdT: p.t, minT: p.t, maxT: p.t, unknown: false, source: "direct", syntheticT0: false, consumedAt: null });
12339
+ }
12340
+ }
12341
+ const heldEntries = Object.entries(trace.items?.[h] ?? {}).filter(([, e]) => e?.held?.length).map(([rawK, e]) => ({ item: rawK.replace(/^item_/, ""), firstHeld: e.held[0][0] }));
12342
+ for (const he of heldEntries) {
12343
+ if (he.firstHeld > trace.t0 + 0.5) continue;
12344
+ const spec = itemRecipeSpec(he.item, patchItems);
12345
+ if (spec?.composite) continue;
12346
+ if (!pool.some((x) => x.item === he.item && x.createdT <= trace.t0 + 1)) {
12347
+ pool.push({ item: he.item, createdT: trace.t0, minT: trace.t0, maxT: trace.t0, unknown: false, source: "direct", syntheticT0: true, consumedAt: null });
12348
+ }
12349
+ }
12350
+ pool.sort((a, b) => a.createdT - b.createdT);
12351
+ const compositeEvents = [];
12352
+ const loggedCompositeAt = /* @__PURE__ */ new Map();
12353
+ for (const p of rawPurchases) {
12354
+ const spec = itemRecipeSpec(p.item, patchItems);
12355
+ if (spec?.composite) {
12356
+ compositeEvents.push({ item: p.item, combineT: p.t, limitT: p.t + 2, ord: p.ord });
12357
+ if (!loggedCompositeAt.has(p.item)) loggedCompositeAt.set(p.item, p.t);
12358
+ }
12359
+ }
12360
+ for (const he of heldEntries) {
12361
+ const spec = itemRecipeSpec(he.item, patchItems);
12362
+ if (!spec?.composite) continue;
12363
+ const firstLog = loggedCompositeAt.get(he.item);
12364
+ if (firstLog == null || firstLog > he.firstHeld + 2) {
12365
+ compositeEvents.push({ item: he.item, combineT: null, limitT: he.firstHeld + 2, ord: Infinity });
12366
+ }
12367
+ }
12368
+ compositeEvents.sort((a, b) => (a.combineT ?? a.limitT - 2) - (b.combineT ?? b.limitT - 2) || recipeDepth(a.item, patchItems) - recipeDepth(b.item, patchItems) || a.ord - b.ord);
12369
+ const expandParts = (itemKey, parts, limitT, depth = 0) => {
12370
+ if (depth > 6) return null;
12371
+ const groups = /* @__PURE__ */ new Map();
12372
+ const addReq = (alts) => {
12373
+ const gk = alts.join("|");
12374
+ const cur = groups.get(gk) ?? { alts, count: 0 };
12375
+ cur.count += 1;
12376
+ groups.set(gk, cur);
12377
+ };
12378
+ for (const part of parts) {
12379
+ if (itemKey === "power_treads" && part === "belt_of_strength") {
12380
+ addReq(POWER_TREADS_STAT_ALTS);
12381
+ continue;
12382
+ }
12383
+ const directAvail = pool.filter((x) => x.consumedAt == null && x.item === part && x.createdT <= limitT).length;
12384
+ const alreadyNeeded = groups.get(part)?.count ?? 0;
12385
+ if (directAvail > alreadyNeeded) {
12386
+ addReq([part]);
12387
+ continue;
12388
+ }
12389
+ const subSpec = itemRecipeSpec(part, patchItems);
12390
+ if (subSpec?.composite && subSpec.parts?.length) {
12391
+ const sub = expandParts(part, subSpec.parts, limitT, depth + 1);
12392
+ if (!sub) return null;
12393
+ for (const [gk, g] of sub) {
12394
+ const cur = groups.get(gk) ?? { alts: g.alts, count: 0 };
12395
+ cur.count += g.count;
12396
+ groups.set(gk, cur);
12397
+ }
12398
+ } else {
12399
+ addReq([part]);
12400
+ }
12401
+ }
12402
+ return groups;
12403
+ };
12404
+ const sortAvail = (a, b) => (a.unknown === b.unknown ? a.unknown ? 0 : (a.minT ?? 0) - (b.minT ?? 0) : a.unknown ? -1 : 1) || a.createdT - b.createdT;
12405
+ for (const ev of compositeEvents) {
12406
+ const consumedAt = ev.combineT ?? ev.limitT - 2;
12407
+ const spec = itemRecipeSpec(ev.item, patchItems);
12408
+ if (!spec?.parts?.length) {
12409
+ pool.push({ item: ev.item, createdT: consumedAt, minT: null, maxT: null, unknown: true, source: "components", syntheticT0: false, consumedAt: null });
12410
+ pool.sort((a, b) => a.createdT - b.createdT);
12411
+ continue;
12412
+ }
12413
+ const groups = expandParts(ev.item, spec.parts, ev.limitT);
12414
+ if (!groups) {
12415
+ pool.push({ item: ev.item, createdT: consumedAt, minT: null, maxT: null, unknown: true, source: "components", syntheticT0: false, consumedAt: null });
12416
+ pool.sort((a, b) => a.createdT - b.createdT);
12417
+ continue;
12418
+ }
12419
+ const matched = [];
12420
+ let ok = true;
12421
+ for (const g of groups.values()) {
12422
+ const avail = pool.filter((x) => x.consumedAt == null && g.alts.includes(x.item) && x.createdT <= ev.limitT).sort(sortAvail);
12423
+ if (avail.length < g.count) ok = false;
12424
+ const groupUnknown = avail.some((x) => x.unknown);
12425
+ const groupMinT = !groupUnknown && avail.length ? avail[0].minT : null;
12426
+ const earliestMax = !groupUnknown && avail.length >= g.count ? avail[g.count - 1].minT : null;
12427
+ const latestMax = !groupUnknown && avail.length ? Math.max(...avail.map((x) => x.maxT ?? 0)) : null;
12428
+ matched.push({ g, avail, groupUnknown, groupMinT, earliestMax, latestMax });
12429
+ }
12430
+ const taken = [];
12431
+ for (const m of matched) {
12432
+ const take = Math.min(m.g.count, m.avail.length);
12433
+ for (let i = 0; i < take; i += 1) {
12434
+ m.avail[i].consumedAt = consumedAt;
12435
+ taken.push(m.avail[i]);
12436
+ }
12437
+ if (m.avail.length > take) {
12438
+ for (let i = take; i < m.avail.length; i += 1) {
12439
+ if (m.groupUnknown) {
12440
+ m.avail[i].unknown = true;
12441
+ m.avail[i].minT = null;
12442
+ m.avail[i].maxT = null;
12443
+ } else if (m.groupMinT != null && m.latestMax != null && !m.avail[i].unknown) {
12444
+ m.avail[i].minT = Math.min(m.avail[i].minT ?? m.groupMinT, m.groupMinT);
12445
+ m.avail[i].maxT = Math.max(m.avail[i].maxT ?? m.latestMax, m.latestMax);
12446
+ }
12447
+ }
12448
+ }
12449
+ }
12450
+ const evUnknown = !ok || matched.some((m) => m.groupUnknown);
12451
+ if (evUnknown) {
12452
+ pool.push({ item: ev.item, createdT: consumedAt, minT: null, maxT: null, unknown: true, source: "components", syntheticT0: false, consumedAt: null });
12453
+ } else {
12454
+ const minT = Math.max(...matched.map((m) => m.earliestMax ?? -Infinity));
12455
+ const maxT = Math.max(...matched.map((m) => m.latestMax ?? -Infinity));
12456
+ const anyReal = taken.some((x) => !x.syntheticT0);
12457
+ pool.push({ item: ev.item, createdT: consumedAt, minT, maxT, unknown: false, source: "components", syntheticT0: !anyReal, consumedAt: null });
12458
+ }
12459
+ pool.sort((a, b) => a.createdT - b.createdT);
12460
+ }
12461
+ return (itemKey, firstHeld) => {
12462
+ const cands = pool.filter((x) => !x.syntheticT0 && x.item === itemKey && x.createdT <= firstHeld + 2 && (x.consumedAt == null || x.consumedAt >= firstHeld - 2));
12463
+ if (!cands.length || cands.some((x) => x.unknown)) return null;
12464
+ const earliest = Math.min(...cands.map((x) => x.minT ?? 0));
12465
+ const latest = Math.max(...cands.map((x) => x.maxT ?? 0));
12466
+ if (latest - earliest > 2) return null;
12467
+ return { t: earliest, clock: clock3(earliest), source: cands[0].source };
12468
+ };
12469
+ }
12470
+ function itemTimeline(trace, args = {}, ctx = {}) {
12286
12471
  const { h, err } = needHero(trace, args.hero);
12287
12472
  if (err) return err;
12473
+ const view = viewer(trace, ctx);
12474
+ const heroKey = trace.heroes[h].key;
12475
+ const heroTeam = trace.heroes[h].team;
12476
+ const isEnemyView = Boolean(view && heroTeam !== view.team);
12477
+ const courierListKey = isEnemyView ? "enemy_team_courier_deaths" : "my_team_courier_deaths";
12478
+ const courierDeliveryKey = isEnemyView ? "enemy_team_courier_deaths_during_delivery" : "my_team_courier_deaths_during_delivery";
12288
12479
  const end = trace.t0 + trace.n - 1;
12289
- const items = Object.entries(trace.items[h]).filter(([k3, e]) => !CONSUMABLE.test(k3) && e.held.length).map(([k3, e]) => {
12480
+ const hasPurchases = Array.isArray(trace.purchases);
12481
+ const patchItems = ctx?.patchItems && typeof ctx.patchItems === "object" ? ctx.patchItems : null;
12482
+ const matchPurchase = buildPurchaseMatcher(trace, h, patchItems);
12483
+ const courierDeaths = teamCourierDeaths(trace, heroTeam);
12484
+ const items = Object.entries(trace.items?.[h] ?? {}).filter(([k3, e]) => !CONSUMABLE.test(k3) && e.held.length).map(([k3, e]) => {
12485
+ const itemKey = k3.replace(/^item_/, "");
12290
12486
  const first = e.held[0][0];
12291
12487
  const last = e.held.at(-1)[1];
12292
- return { ref: `item:${trace.heroes[h].key}:${k3.replace(/^item_/, "")}`, item: k3.replace(/^item_/, ""), first_held: { t: first, clock: clock3(first) }, held_at_end: last >= end - 2, ...last >= end - 2 ? {} : { last_held: { t: last, clock: clock3(last) } } };
12488
+ const purchased = matchPurchase(itemKey, first);
12489
+ const preHornStart = purchased != null && first <= trace.t0 + 0.5 && purchased.t < trace.t0;
12490
+ const delaySec = purchased == null || preHornStart ? null : Math.max(0, Math.round(first - purchased.t));
12491
+ const courierDuring = purchased != null && delaySec != null && delaySec > 0 ? courierDeaths == null ? null : courierDeaths.filter((d) => d.t >= purchased.t && d.t <= first) : void 0;
12492
+ return {
12493
+ ref: `item:${heroKey}:${itemKey}`,
12494
+ item: itemKey,
12495
+ first_purchased: purchased,
12496
+ first_held: { t: first, clock: clock3(first) },
12497
+ delivery_delay_seconds: delaySec,
12498
+ ...delaySec != null && delaySec > 0 ? { [courierDeliveryKey]: courierDuring } : {},
12499
+ held_at_end: last >= end - 2,
12500
+ ...last >= end - 2 ? {} : { last_held: { t: last, clock: clock3(last) } }
12501
+ };
12293
12502
  }).sort((a, b) => a.first_held.t - b.first_held.t);
12294
- return { hero: trace.heroes[h].key, items, note: "first_held is when the item first sat in an inventory, TP or neutral slot; components appear until they are built into something else" };
12503
+ return {
12504
+ hero: heroKey,
12505
+ ...sideOf(view, trace, h),
12506
+ [courierListKey]: courierDeaths,
12507
+ items,
12508
+ note: "first_purchased is when the hero paid for the item (direct shop purchase, or the last required component/recipe purchase for a composite item; null when absent or ambiguous in the purchase log). first_held is when the item first sat in an inventory, TP or neutral slot (not stash, backpack, or on a courier); components appear until they are built into something else. delivery_delay_seconds is first_held minus first_purchased (0 when held immediately, null when purchase or pre-horn delivery time is unknown). Courier deaths are hero-killed couriers of this hero's team from the combat log; a death during [first_purchased, first_held] is a factual lead, not proof of which courier died or what it carried.",
12509
+ gaps: [
12510
+ ...!hasPurchases ? [{ topic: "item_purchases", reason: "no_purchases_in_trace" }] : [],
12511
+ ...hasPurchases && !patchItems ? [{ topic: "item_purchases", reason: "patch_item_recipes_not_provided: purchase_timing_requires_item_recipes" }] : [],
12512
+ ...courierDeaths == null ? [{ topic: "courier_deaths", reason: "no_creep_kills_in_trace" }] : [{ topic: "courier_ownership_and_cargo", reason: "trace_does_not_record_courier_owner_carried_items_or_non_hero_courier_kills" }],
12513
+ { topic: "stash_and_backpack_state", reason: "trace_does_not_separate_courier_transit_from_stash_backpack_or_lock_combining_time" }
12514
+ ]
12515
+ };
12295
12516
  }
12296
12517
  var SHARED_NAME = /_tower4$/;
12297
12518
  var PHASE_SECONDS = 600;
@@ -12552,7 +12773,7 @@ var TRACE_TOOLS = [
12552
12773
  },
12553
12774
  {
12554
12775
  name: "item_timeline",
12555
- description: "When a hero first held each item, in order, and whether they still had it at the end. Works for any hero of the match: use it for the player's build and for when an enemy finished a key item.",
12776
+ description: "When a hero purchased (`first_purchased`, direct shop buy or last required component/recipe) and first held (`first_held`, in a usable slot \u2014 not stash, backpack, or on a courier) each item, in order, with `delivery_delay_seconds`, whether they still had it at the end, team courier deaths (`my_team_courier_deaths` / `enemy_team_courier_deaths`), and any team courier deaths during `[first_purchased, first_held]` (`*_courier_deaths_during_delivery`). Works for any hero of the match: use it for the player's build (distinguishing paid-but-undelivered items from slow farming) and for when an enemy finished a key item.",
12556
12777
  input_schema: { type: "object", properties: { hero: HERO }, required: ["hero"], additionalProperties: false },
12557
12778
  run: itemTimeline
12558
12779
  },
@@ -12823,7 +13044,8 @@ var PARAMETERS = {
12823
13044
  match_id: MATCH,
12824
13045
  hero: idOrName(TOOL_DOCS.replay_review.params.hero),
12825
13046
  lang: LANG,
12826
- retry: { type: "boolean", description: TOOL_DOCS.replay_review.params.retry }
13047
+ retry: { type: "boolean", description: TOOL_DOCS.replay_review.params.retry },
13048
+ refresh: { type: "boolean", description: TOOL_DOCS.replay_review.params.refresh }
12827
13049
  },
12828
13050
  recent_matches: {
12829
13051
  account: { type: "string", required: true, description: "Steam friend code or a Steam/OpenDota/Dotabuff/STRATZ profile link" }
@@ -12919,7 +13141,7 @@ import { join as join5 } from "node:path";
12919
13141
 
12920
13142
  // lib/agent/review/schema.js
12921
13143
  var DEEP_REVIEW_SCHEMA = "dota2.ai/deep-review@1";
12922
- var DEEP_REVIEW_PROMPT_VERSION = 79;
13144
+ var DEEP_REVIEW_PROMPT_VERSION = 80;
12923
13145
  var MAX_REFS = 3;
12924
13146
  var MAX_FINDINGS = 3;
12925
13147
  var MAX_HIGHLIGHTS = 4;
@@ -17708,9 +17930,22 @@ function buildCheck(trace, args = {}, ctx = {}) {
17708
17930
  if (key === "aghanims_shard" && myAghs?.shard?.length) return { for_this_hero: myAghs.shard };
17709
17931
  return {};
17710
17932
  };
17711
- const timeline = itemTimeline(trace, { hero: slug2 }).items ?? [];
17933
+ const timelineRes = itemTimeline(trace, { hero: slug2 }, { ...ctx, perspective: slug2, patchItems: pd.items });
17934
+ const timeline = timelineRes.items ?? [];
17712
17935
  const firstHeld = new Map(timeline.map((i) => [i.item, i.first_held]));
17713
- const mine = timeline.filter((i) => big(i.item)).sort((a, b) => a.first_held.t - b.first_held.t).map((i) => ({ item: i.item, name: itemName2(i.item, lang), first_held: i.first_held.clock, ...itemFacts(i.item, pd.items), ...heroAghsNote(i.item), built_for: purposesOf(i.item, pd.items) }));
17936
+ const mine = timeline.filter((i) => big(i.item)).sort((a, b) => a.first_held.t - b.first_held.t).map((i) => ({
17937
+ item: i.item,
17938
+ name: itemName2(i.item, lang),
17939
+ first_held: i.first_held.clock,
17940
+ first_purchased: i.first_purchased?.clock ?? null,
17941
+ ...i.delivery_delay_seconds != null && i.delivery_delay_seconds > 0 ? { delivery_delay_seconds: i.delivery_delay_seconds } : {},
17942
+ ...i.delivery_delay_seconds != null && i.delivery_delay_seconds > 0 ? {
17943
+ my_team_courier_deaths_during_delivery: i.my_team_courier_deaths_during_delivery == null ? null : i.my_team_courier_deaths_during_delivery.map(({ clock: clock10, killed_by }) => ({ clock: clock10, killed_by }))
17944
+ } : {},
17945
+ ...itemFacts(i.item, pd.items),
17946
+ ...heroAghsNote(i.item),
17947
+ built_for: purposesOf(i.item, pd.items)
17948
+ }));
17714
17949
  const onTop = goldOnTop(mine.map((i) => i.item), pd.items);
17715
17950
  mine.forEach((i, n) => {
17716
17951
  if (onTop[n] != null) i.gold_on_top_of_items_already_held = onTop[n];
@@ -17816,6 +18051,7 @@ function buildCheck(trace, args = {}, ctx = {}) {
17816
18051
  killed_by: kills,
17817
18052
  damage_in_my_deaths: { share_from_enemy_attacks: fromAttacks, share_from_enemy_abilities_and_items: fromSpells, by_enemy: byEnemy },
17818
18053
  my_big_items_in_order: mine,
18054
+ my_team_courier_deaths: timelineRes.my_team_courier_deaths ?? null,
17819
18055
  gold_in_big_items_by_purpose: Object.fromEntries(Object.entries(goldBy).map(([p, v]) => [p, { gold: v.gold, items: v.items, first_at: v.first_at }])),
17820
18056
  player_already_held_for_this_purpose: {
17821
18057
  attack_damage_or_armor: heldFor("answer_to_attack_damage", "armor"),
@@ -17828,7 +18064,7 @@ function buildCheck(trace, args = {}, ctx = {}) {
17828
18064
  most_built_in_this_bracket: bracketCore,
17829
18065
  most_built_by_pros_on_this_hero: core.length ? { pro_games: row.games, played_on_releases: row.releases, ...fromBefore ? { from_the_patch_before_this_game: true } : sample.few_games ? { few_games: true } : {}, window: "finished between 10:00 and 24:59", items: core } : null,
17830
18066
  gap_closers: { mine: myGap ? { item: myGap.item, name: itemName2(myGap.item, lang), first_held: myGap.first_held.clock } : null, enemies: theirGaps },
17831
- note: `answers_to_top_killers is per enemy who killed the player most: Valve's text of that hero's abilities (valve_text is the current release's wording; the flags are this game's release), the shop's big items whose Valve data acts on the kind of damage that enemy did in the deaths (items_acting_on_their_damage: against_their attacks or abilities, cheapest first, \`how\` each acts on it, read off this patch's item data, whatever the role \u2014 a list to weigh, not a pick), the items pros on this hero build clearly more often against it (association, not proof); known_for is the site's curated threat tags of that hero. built_for is what the site's curated lists and Valve's item stats say an item is for; an empty list means "not classified", not "offensive". estimated_minutes_of_my_farm = item cost / my_economy.gold_per_min when that is known; "gives" and "does" are Valve's data. player_already_held_for_this_purpose groups big items the player already finished by the threats they cover. Shares of damage are over the 12 seconds before each death, of all damage taken in them (the two sums count enemy heroes only). An item built from a big item already held counts only the gold on top of it (gold_on_top_of_items_already_held). Pro shares are professional games, not this bracket; most_built_in_this_bracket (when present) is public games of this bracket and role (STRATZ).`,
18067
+ note: `answers_to_top_killers is per enemy who killed the player most: Valve's text of that hero's abilities (valve_text is the current release's wording; the flags are this game's release), the shop's big items whose Valve data acts on the kind of damage that enemy did in the deaths (items_acting_on_their_damage: against_their attacks or abilities, cheapest first, \`how\` each acts on it, read off this patch's item data, whatever the role \u2014 a list to weigh, not a pick), the items pros on this hero build clearly more often against it (association, not proof); known_for is the site's curated threat tags of that hero. built_for is what the site's curated lists and Valve's item stats say an item is for; an empty list means "not classified", not "offensive". On my_big_items_in_order, first_purchased is when the player finished buying the item (direct buy or last required component/recipe, null if absent/ambiguous), first_held is when it first sat in a usable inventory slot (not stash, backpack, or courier), delivery_delay_seconds is first_held minus first_purchased when positive, and my_team_courier_deaths_during_delivery lists hero-killed team couriers in [first_purchased, first_held] (a factual lead, not proof of courier owner or cargo). estimated_minutes_of_my_farm = item cost / my_economy.gold_per_min when that is known; "gives" and "does" are Valve's data. player_already_held_for_this_purpose groups big items the player already finished by the threats they cover. Shares of damage are over the 12 seconds before each death, of all damage taken in them (the two sums count enemy heroes only). An item built from a big item already held counts only the gold on top of it (gold_on_top_of_items_already_held). Pro shares are professional games, not this bracket; most_built_in_this_bracket (when present) is public games of this bracket and role (STRATZ).`,
17832
18068
  gaps: [
17833
18069
  ...role.kind ? [] : [{ topic: "role", reason: ctx.match ? role.gaps[0] ?? "role_not_established" : "no_match_data_for_this_game" }],
17834
18070
  ...economy ? [
@@ -17843,7 +18079,8 @@ function buildCheck(trace, args = {}, ctx = {}) {
17843
18079
  ...answersToTopKillers.some((k3) => k3.pro_items_against_this_killer) ? [{ topic: "pro_items_against_killers", reason: `professional_matches_since_${ITEM_VS_SOURCE.since}_all_releases_together` }] : [],
17844
18080
  ...answersToTopKillers.length && !pd.exact ? [{ topic: "killer_ability_data_of_this_game_patch", reason: `${pd.reason}; ${pd.name} data used` }] : [],
17845
18081
  { topic: "damage_type_of_abilities", reason: "spell_damage_is_not_split_into_magical_and_physical_here" },
17846
- { topic: "gold_spent_on_small_items", reason: "only_big_items_are_counted" }
18082
+ { topic: "gold_spent_on_small_items", reason: "only_big_items_are_counted" },
18083
+ ...timelineRes.gaps ?? []
17847
18084
  ]
17848
18085
  };
17849
18086
  }
@@ -17943,7 +18180,7 @@ var HERO2 = { type: "string", description: `Hero key as in match_overview, e.g.
17943
18180
  var SITUATION_TOOLS = [
17944
18181
  {
17945
18182
  name: "build_check",
17946
- description: "The player's build against what killed them. Gives their role and 1\u20135 position (from parsed match lanes or inferred from the replay), their economy (`my_economy`: GPM, net worth / 20:00 gold when known), where the damage in their deaths came from (which enemy, attacks or abilities), each big item they bought in order with its cost, what Valve lists for it and what it is for (built_for: an answer to attack damage, to spell damage, to disables, a gap closer, magic resistance, armor \u2014 empty means not classified), the gold put into each purpose, which big items the player already held for each purpose (player_already_held_for_this_purpose), for each of the (up to two) enemies who killed them most what that hero's abilities do in Valve's words, the shop's big items whose Valve data acts on that enemy's kind of damage (disarm, push, physical immunity, damage block or return, lowered attack speed, armor; or spell immunity, magic barrier, magic resistance) with their cost, and the items pros on this hero build clearly more often against that hero (answers_to_top_killers), each with what it does, `estimated_minutes_of_my_farm` (item cost divided by the player's GPM) and whether the player held it, what players of this bracket and role build on the hero in public games (most_built_in_this_bracket, when known), the hero's most-built professional items with when the player had them, and when each side got its first gap closer (Blink Dagger and the like). Use it before saying anything about what an item is, what the player's build answered, or what to buy.",
18183
+ description: "The player's build against what killed them. Gives their role and 1\u20135 position (from parsed match lanes or inferred from the replay), their economy (`my_economy`: GPM, net worth / 20:00 gold when known), where the damage in their deaths came from (which enemy, attacks or abilities), each big item they bought in order with its purchase vs delivery timing (`first_purchased`, `first_held`, positive `delivery_delay_seconds`, and any `my_team_courier_deaths_during_delivery`, alongside match-wide `my_team_courier_deaths`), its cost, what Valve lists for it and what it is for (built_for: an answer to attack damage, to spell damage, to disables, a gap closer, magic resistance, armor \u2014 empty means not classified), the gold put into each purpose, which big items the player already held for each purpose (player_already_held_for_this_purpose), for each of the (up to two) enemies who killed them most what that hero's abilities do in Valve's words, the shop's big items whose Valve data acts on that enemy's kind of damage (disarm, push, physical immunity, damage block or return, lowered attack speed, armor; or spell immunity, magic barrier, magic resistance) with their cost, and the items pros on this hero build clearly more often against that hero (answers_to_top_killers), each with what it does, `estimated_minutes_of_my_farm` (item cost divided by the player's GPM) and whether the player held it, what players of this bracket and role build on the hero in public games (most_built_in_this_bracket, when known), the hero's most-built professional items with when the player had them, and when each side got its first gap closer (Blink Dagger and the like). Use it before saying anything about what an item is, what the player's build answered, or what to buy.",
17947
18184
  input_schema: { type: "object", properties: { hero: HERO2 }, required: ["hero"], additionalProperties: false },
17948
18185
  run: buildCheck
17949
18186
  },
@@ -21306,7 +21543,8 @@ function namesIn(value, lang) {
21306
21543
  }
21307
21544
  function resolveRef(trace, ref, { hero, lang = "en", match = null, bracketData }) {
21308
21545
  if (typeof ref !== "string" || !REF.test(ref)) return null;
21309
- const ctx = { match, perspective: hero, lang, ultimateOf: ultimateOf2, ultimatesOf, ...bracketData ? { bracketData } : {} };
21546
+ const pd = patchForGame(trace?.match_id, match);
21547
+ const ctx = { match, perspective: hero, lang, ultimateOf: ultimateOf2, ultimatesOf, patchItems: pd.items, ...bracketData ? { bracketData } : {} };
21310
21548
  const [kind, a, b, c] = ref.split(":");
21311
21549
  const run = (name2, args) => {
21312
21550
  const r = runTraceTool(trace, name2, args, ctx);
@@ -22179,9 +22417,9 @@ function reviewToolkit({ trace, hero, lang, match = null, webSearch = webSearchF
22179
22417
  const seat = trace.heroes.find((h) => h.key === String(hero).trim().toLowerCase().replace(/^npc_dota_hero_/, "").replace(/[\s-]+/g, "_"));
22180
22418
  if (!seat) return null;
22181
22419
  const lookups = [...TRACE_TOOLS, ...KNOWLEDGE_TOOLS, WEB_SEARCH_TOOL];
22182
- const ctx = { match, perspective: seat.key, lang: language, ultimateOf: ultimateOf2, ultimatesOf };
22183
- const knowledge = new Map(KNOWLEDGE_TOOLS.map((t6) => [t6.name, t6]));
22184
22420
  const pd = patchForGame(trace.match_id, match);
22421
+ const ctx = { match, perspective: seat.key, lang: language, ultimateOf: ultimateOf2, ultimatesOf, patchItems: pd.items };
22422
+ const knowledge = new Map(KNOWLEDGE_TOOLS.map((t6) => [t6.name, t6]));
22185
22423
  const gamePatch2 = pd.exact || /hotfix/.test(pd.reason ?? "") ? { name: pd.name, released: RELEASES.find((r) => r.name === pd.name)?.rollout_by ?? null } : { name: null, released: null, reason: pd.reason ?? "patch_not_established" };
22186
22424
  const names2 = heroNames(trace, language);
22187
22425
  return {
@@ -22191,7 +22429,7 @@ function reviewToolkit({ trace, hero, lang, match = null, webSearch = webSearchF
22191
22429
  /** Count n web searches already made (a resumed review's): the limit is per review, not per restart. */
22192
22430
  spendSearches: (n) => webSearch?.spend?.(n),
22193
22431
  runTool: (name2, args) => name2 === WEB_SEARCH_TOOL.name ? webSearch(args ?? {}, { patch: gamePatch2 }) : withHeroNames(roshanGapPointsToTool(knowledge.has(name2) ? { tool: name2, ...knowledge.get(name2).run(trace, args, ctx) } : runTraceTool(trace, name2, args, ctx), trace), names2, language),
22194
- patch: (({ name: name2, hotfix, exact, how, reason }) => ({ name: name2, ...hotfix ? { hotfix } : {}, exact, ...how ? { known_from: how } : {}, ...exact ? {} : { reason } }))(patchForGame(trace.match_id, match)),
22432
+ patch: (({ name: name2, hotfix, exact, how, reason }) => ({ name: name2, ...hotfix ? { hotfix } : {}, exact, ...how ? { known_from: how } : {}, ...exact ? {} : { reason } }))(pd),
22195
22433
  context: { match_id: trace.match_id, player_hero: seat.key, hero_names: names2, place_names: placeNames(language), ...scoreboard(match, seat.key) ? { scoreboard: scoreboard(match, seat.key) } : {} }
22196
22434
  };
22197
22435
  }
@@ -24294,14 +24532,15 @@ function momentFrames(trace, { hero, t: t6, to: endT = null, before = MOMENT_BEF
24294
24532
 
24295
24533
  // lib/agent/stores.js
24296
24534
  import { createHash } from "node:crypto";
24297
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
24535
+ import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
24298
24536
  import { join as join2 } from "node:path";
24299
24537
  import { gunzipSync } from "node:zlib";
24300
24538
  var KEY2 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,180}$/;
24539
+ var PREFIX2 = /^[A-Za-z0-9._-]{0,180}$/;
24301
24540
  var MATCH_ID = /^[1-9]\d{0,14}$/;
24302
24541
  var MAX_TRACE_JSON_BYTES = 32 * 1024 * 1024;
24303
24542
  var contentGen = (buf) => createHash("sha256").update(buf).digest("hex").slice(0, 16);
24304
- function createFileStore(dir, fs = { mkdir, readFile, rename, rm, writeFile }) {
24543
+ function createFileStore(dir, fs = { mkdir, readdir, readFile, rename, rm, writeFile }) {
24305
24544
  let n = 0;
24306
24545
  const locks = /* @__PURE__ */ new Map();
24307
24546
  const serialize = (key, fn) => {
@@ -24391,7 +24630,18 @@ function createFileStore(dir, fs = { mkdir, readFile, rename, rm, writeFile }) {
24391
24630
  async delete(key) {
24392
24631
  if (!dir || !KEY2.test(key)) return;
24393
24632
  await fs.rm(join2(dir, key), { force: true });
24394
- }
24633
+ },
24634
+ ...typeof fs?.readdir === "function" ? {
24635
+ async list(prefix = "") {
24636
+ if (!dir || typeof prefix !== "string" || !PREFIX2.test(prefix) || prefix.includes("..")) return [];
24637
+ try {
24638
+ const entries = await fs.readdir(dir);
24639
+ return entries.filter((name2) => typeof name2 === "string" && KEY2.test(name2) && name2.startsWith(prefix)).sort();
24640
+ } catch {
24641
+ return [];
24642
+ }
24643
+ }
24644
+ } : {}
24395
24645
  };
24396
24646
  }
24397
24647
  function createTraceStore(blobs, { keep = 4 } = {}) {
@@ -24470,6 +24720,9 @@ function createJsonStore(blobs) {
24470
24720
  async delete(key) {
24471
24721
  if (blobs?.delete) await blobs.delete(key);
24472
24722
  },
24723
+ ...typeof blobs?.list === "function" ? { async list(prefix = "") {
24724
+ return blobs.list(prefix);
24725
+ } } : {},
24473
24726
  ...cas ? {
24474
24727
  async getWithMeta(key) {
24475
24728
  const res = await blobs.getWithMeta(key);
@@ -25101,6 +25354,7 @@ function createTracePipeline(deps) {
25101
25354
 
25102
25355
  // lib/agent/service.js
25103
25356
  var HERO_BY_SLUG2 = HEROES_BY_KEY;
25357
+ var FALLBACK_PROBE_WINDOW = 10;
25104
25358
  var MAX_KEPT_JOBS = 200;
25105
25359
  var BEAT_MS = 15e3;
25106
25360
  var STALE_MS = 9e4;
@@ -25161,12 +25415,12 @@ function createAgentService(deps) {
25161
25415
  const runner = `${now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
25162
25416
  const jobs = /* @__PURE__ */ new Map();
25163
25417
  const parses = /* @__PURE__ */ new Map();
25164
- const suffixOf = (plan = null, model = null) => {
25418
+ const suffixOf = (plan = null, model = null, version = DEEP_REVIEW_PROMPT_VERSION) => {
25165
25419
  const id = idOf(model);
25166
- return `p${DEEP_REVIEW_PROMPT_VERSION}${plan ? `.plan-${plan}` : ""}${id && id !== DEFAULT_AGENT_MODEL ? `.m-${id}` : ""}`;
25420
+ return `p${version}${plan ? `.plan-${plan}` : ""}${id && id !== DEFAULT_AGENT_MODEL ? `.m-${id}` : ""}`;
25167
25421
  };
25168
- const keyOf = (matchId, hero, plan = null, model = null) => `${matchId}.${hero}.${suffixOf(plan, model)}`;
25169
- const legacyKeyOf = (matchId, hero, lang, plan = null, model = null) => `${matchId}.${hero}.${lang}.${suffixOf(plan, model)}`;
25422
+ const keyOf = (matchId, hero, plan = null, model = null, version = DEEP_REVIEW_PROMPT_VERSION) => `${matchId}.${hero}.${suffixOf(plan, model, version)}`;
25423
+ const legacyKeyOf = (matchId, hero, lang, plan = null, model = null, version = DEEP_REVIEW_PROMPT_VERSION) => `${matchId}.${hero}.${lang}.${suffixOf(plan, model, version)}`;
25170
25424
  const jobKeyOf = (matchId, hero, lang, plan = null, model = null) => legacyKeyOf(matchId, hero, normalizeUiLang(lang), plan, model);
25171
25425
  const read = async (key) => {
25172
25426
  try {
@@ -25175,6 +25429,13 @@ function createAgentService(deps) {
25175
25429
  return null;
25176
25430
  }
25177
25431
  };
25432
+ const listKeys = async (prefix) => {
25433
+ try {
25434
+ return typeof docs?.list === "function" ? await docs.list(prefix) : null;
25435
+ } catch {
25436
+ return null;
25437
+ }
25438
+ };
25178
25439
  const write = async (key, value) => {
25179
25440
  try {
25180
25441
  if (docs) await docs.put(key, value);
@@ -25238,23 +25499,91 @@ function createAgentService(deps) {
25238
25499
  const k3 = heroKeyOf(hero);
25239
25500
  return { trace, key: trace.heroes.some((h) => h.key === k3) ? k3 : null };
25240
25501
  }
25241
- const cleanReviewsMap = (map) => Object.fromEntries(
25242
- Object.entries(map ?? {}).filter(([, r]) => r?.schema).map(([l, r]) => [l, withoutHandles(r)])
25502
+ const isCompatibleReview = (r, { lang = null, hero = null, matchId = null, plan = null } = {}) => {
25503
+ if (!r || typeof r !== "object" || Array.isArray(r)) return false;
25504
+ if (r.schema !== DEEP_REVIEW_SCHEMA) return false;
25505
+ if (typeof r.verdict !== "string" || !r.verdict.trim()) return false;
25506
+ if (!Array.isArray(r.findings)) return false;
25507
+ if (lang != null && r.lang != null && normalizeUiLang(r.lang) !== lang) return false;
25508
+ if (hero != null && r.hero != null && heroKeyOf(r.hero) !== hero) return false;
25509
+ if (matchId != null && r.match_id != null && String(r.match_id) !== String(matchId)) return false;
25510
+ if (plan == null) {
25511
+ if (r.plan != null && r.plan !== "") return false;
25512
+ } else if (r.plan != null && planKey(r.plan) !== plan) {
25513
+ return false;
25514
+ }
25515
+ return true;
25516
+ };
25517
+ const cleanReviewsMap = (map, check = {}) => Object.fromEntries(
25518
+ Object.entries(map ?? {}).filter(([l, r]) => isCompatibleReview(r, { ...check, lang: normalizeUiLang(l) })).map(([l, r]) => [l, withoutHandles(r)])
25243
25519
  );
25244
- const stored = async (matchId, hero, lang, plan = null, model = null) => {
25520
+ const extractBundleRecord = (bundle, L3, check, version) => {
25521
+ if (!bundle?.reviews || typeof bundle.reviews !== "object") return null;
25522
+ const reviews = cleanReviewsMap(bundle.reviews, check);
25523
+ if (!reviews[L3]) return null;
25524
+ return { ...bundle, review: reviews[L3], reviews, prompt_version: version };
25525
+ };
25526
+ const extractLegacyRecord = (legacy, L3, check, version) => {
25527
+ if (!isCompatibleReview(legacy?.review, { ...check, lang: L3 })) return null;
25528
+ const review = withoutHandles(legacy.review);
25529
+ return { ...legacy, review, reviews: { [L3]: review }, prompt_version: version };
25530
+ };
25531
+ const storedAtVersion = async (matchId, hero, lang, plan = null, model = null, version = DEEP_REVIEW_PROMPT_VERSION) => {
25532
+ const L3 = normalizeUiLang(lang);
25533
+ const check = { hero, matchId, plan };
25534
+ const bundle = await read(`${keyOf(matchId, hero, plan, model, version)}.review.json`);
25535
+ const fromBundle = extractBundleRecord(bundle, L3, check, version);
25536
+ if (fromBundle) return fromBundle;
25537
+ const legacy = await read(`${legacyKeyOf(matchId, hero, L3, plan, model, version)}.review.json`);
25538
+ return extractLegacyRecord(legacy, L3, check, version);
25539
+ };
25540
+ const storedExact = (matchId, hero, lang, plan = null, model = null) => storedAtVersion(matchId, hero, lang, plan, model, DEEP_REVIEW_PROMPT_VERSION);
25541
+ const storedFallback = async (matchId, hero, lang, plan = null, model = null) => {
25542
+ if (!docs || DEEP_REVIEW_PROMPT_VERSION <= 1) return null;
25245
25543
  const L3 = normalizeUiLang(lang);
25246
- const bundle = await read(`${keyOf(matchId, hero, plan, model)}.review.json`);
25247
- if (bundle?.reviews && typeof bundle.reviews === "object") {
25248
- const reviews = cleanReviewsMap(bundle.reviews);
25249
- if (reviews[L3]) return { ...bundle, review: reviews[L3], reviews };
25544
+ const check = { hero, matchId, plan };
25545
+ if (typeof docs.list === "function") {
25546
+ const prefix = `${matchId}.${hero}.`;
25547
+ const keys = await listKeys(prefix);
25548
+ if (!Array.isArray(keys)) return null;
25549
+ const modelId = idOf(model);
25550
+ const tail = `${plan ? `.plan-${plan}` : ""}${modelId && modelId !== DEFAULT_AGENT_MODEL ? `.m-${modelId}` : ""}.review.json`;
25551
+ const byVersion = /* @__PURE__ */ new Map();
25552
+ for (const k3 of keys) {
25553
+ if (!k3.startsWith(prefix) || !k3.endsWith(tail) || k3.length <= prefix.length + tail.length) continue;
25554
+ const mid = k3.slice(prefix.length, k3.length - tail.length);
25555
+ const match = /^(?:([a-z]{2})\.)?p([1-9]\d*)$/.exec(mid);
25556
+ if (!match) continue;
25557
+ if (match[1] && match[1] !== L3) continue;
25558
+ const v = Number(match[2]);
25559
+ if (!Number.isSafeInteger(v) || v < 1 || v >= DEEP_REVIEW_PROMPT_VERSION) continue;
25560
+ const slot = byVersion.get(v) ?? {};
25561
+ if (match[1]) slot.perLang = k3;
25562
+ else slot.bundle = k3;
25563
+ byVersion.set(v, slot);
25564
+ }
25565
+ const versions = [...byVersion.keys()].sort((a, b) => b - a);
25566
+ for (const v of versions) {
25567
+ const slot = byVersion.get(v);
25568
+ if (slot.bundle) {
25569
+ const hit = extractBundleRecord(await read(slot.bundle), L3, check, v);
25570
+ if (hit) return hit;
25571
+ }
25572
+ if (slot.perLang) {
25573
+ const hit = extractLegacyRecord(await read(slot.perLang), L3, check, v);
25574
+ if (hit) return hit;
25575
+ }
25576
+ }
25577
+ return null;
25250
25578
  }
25251
- const legacy = await read(`${legacyKeyOf(matchId, hero, L3, plan, model)}.review.json`);
25252
- if (legacy?.review?.schema) {
25253
- const review = withoutHandles(legacy.review);
25254
- return { ...legacy, review, reviews: { [L3]: review } };
25579
+ const floor = Math.max(1, DEEP_REVIEW_PROMPT_VERSION - FALLBACK_PROBE_WINDOW);
25580
+ for (let v = DEEP_REVIEW_PROMPT_VERSION - 1; v >= floor; v -= 1) {
25581
+ const hit = await storedAtVersion(matchId, hero, L3, plan, model, v);
25582
+ if (hit) return hit;
25255
25583
  }
25256
25584
  return null;
25257
25585
  };
25586
+ const stored = async (matchId, hero, lang, plan = null, model = null) => await storedExact(matchId, hero, lang, plan, model) ?? await storedFallback(matchId, hero, lang, plan, model);
25258
25587
  async function parseState(matchId) {
25259
25588
  const id = String(matchId);
25260
25589
  const local = parses.get(id);
@@ -25538,20 +25867,25 @@ function createAgentService(deps) {
25538
25867
  });
25539
25868
  return { job, done: settled };
25540
25869
  }
25541
- const readyPayload = (record, rev) => ({
25542
- status: "ready",
25543
- model: record.model,
25544
- tool_calls: record.tool_calls,
25545
- ...Number.isInteger(record.steps) ? { steps: record.steps } : {},
25546
- ...Number.isInteger(record.repair_rounds) ? { repair_rounds: record.repair_rounds } : {},
25547
- ...Number.isInteger(record.truncation_retries) ? { truncation_retries: record.truncation_retries } : {},
25548
- ...record.usage ? { usage: record.usage } : {},
25549
- ..."usage_source" in record ? { usage_source: record.usage_source } : record.usage && "source" in record.usage ? { usage_source: record.usage.source } : {},
25550
- ...record.verification ? { verification: record.verification } : {},
25551
- prompt_version: DEEP_REVIEW_PROMPT_VERSION,
25552
- review: rev,
25553
- ...Object.keys(record.reviews ?? {}).length > 1 ? { reviews: record.reviews } : {}
25554
- });
25870
+ const readyPayload = (record, rev, promptVersion = DEEP_REVIEW_PROMPT_VERSION) => {
25871
+ const version = Number.isInteger(promptVersion) ? promptVersion : DEEP_REVIEW_PROMPT_VERSION;
25872
+ const stale = version !== DEEP_REVIEW_PROMPT_VERSION;
25873
+ return {
25874
+ status: "ready",
25875
+ model: record.model,
25876
+ tool_calls: record.tool_calls,
25877
+ ...Number.isInteger(record.steps) ? { steps: record.steps } : {},
25878
+ ...Number.isInteger(record.repair_rounds) ? { repair_rounds: record.repair_rounds } : {},
25879
+ ...Number.isInteger(record.truncation_retries) ? { truncation_retries: record.truncation_retries } : {},
25880
+ ...record.usage ? { usage: record.usage } : {},
25881
+ ..."usage_source" in record ? { usage_source: record.usage_source } : record.usage && "source" in record.usage ? { usage_source: record.usage.source } : {},
25882
+ ...record.verification ? { verification: record.verification } : {},
25883
+ prompt_version: version,
25884
+ ...stale ? { latest_prompt_version: DEEP_REVIEW_PROMPT_VERSION, stale_version: true, cached: true } : {},
25885
+ review: rev,
25886
+ ...Object.keys(record.reviews ?? {}).length > 1 ? { reviews: record.reviews } : {}
25887
+ };
25888
+ };
25555
25889
  async function status(matchId, hero, lang, plan = null, model = null) {
25556
25890
  const { trace, key } = await seatOf(matchId, hero);
25557
25891
  if (!trace) return { status: "no_trace" };
@@ -25565,18 +25899,24 @@ function createAgentService(deps) {
25565
25899
  if (job?.state === "running") return { status: "running", steps: job.steps };
25566
25900
  if (job?.state === "ready") {
25567
25901
  const rev = job.result.reviews?.[L3] ?? (job.result.review?.lang === L3 ? job.result.review : null);
25568
- if (rev) return readyPayload(job.result, rev);
25902
+ if (rev) return readyPayload(job.result, rev, DEEP_REVIEW_PROMPT_VERSION);
25569
25903
  }
25570
- const disk = await stored(matchId, key, L3, p, m);
25904
+ const disk = await storedExact(matchId, key, L3, p, m);
25571
25905
  if (disk) {
25572
25906
  const merged = job?.state === "ready" ? { ...disk, reviews: { ...job.result.reviews, ...disk.reviews } } : disk;
25573
25907
  jobs.set(id, { state: "ready", result: merged });
25574
- return readyPayload(merged, disk.review);
25908
+ return readyPayload(merged, disk.review, DEEP_REVIEW_PROMPT_VERSION);
25575
25909
  }
25576
25910
  const marker = await read(`${id}.job.json`);
25577
25911
  if (marker?.state === "running" && now() - (marker.at ?? 0) < REVIEW_STALE_MS && (job?.state !== "failed" || (marker.at ?? 0) >= (job.at ?? 0))) return { status: "running", steps: marker.steps ?? [] };
25578
- if (job?.state === "failed") return { status: "failed", reason: job.reason };
25579
- if (marker?.state === "failed" && now() - (marker.at ?? 0) < 6e4) return { status: "failed", reason: marker.reason };
25912
+ const hasFailed = job?.state === "failed" || marker?.state === "failed" && now() - (marker.at ?? 0) < 6e4;
25913
+ const failedReason = job?.state === "failed" ? job.reason : marker?.reason;
25914
+ const fallback = await storedFallback(matchId, key, L3, p, m);
25915
+ if (fallback) {
25916
+ const payload = readyPayload(fallback, fallback.review, fallback.prompt_version);
25917
+ return hasFailed ? { ...payload, refresh_failed: { reason: failedReason ?? null } } : payload;
25918
+ }
25919
+ if (hasFailed) return { status: "failed", reason: failedReason };
25580
25920
  return { status: "none" };
25581
25921
  }
25582
25922
  async function lastFailure(matchId, hero, lang, plan = null, model = null) {
@@ -25598,7 +25938,7 @@ function createAgentService(deps) {
25598
25938
  const m = modelOf(model);
25599
25939
  if (m === false || !/^\d{1,20}$/.test(String(matchId)) || !/^[a-z][a-z0-9_]{1,39}$/.test(k3) || !SUPPORTED_LANGS.includes(lang)) return null;
25600
25940
  try {
25601
- return (await stored(matchId, k3, lang, planKey(plan), m))?.review ?? null;
25941
+ return (await storedExact(matchId, k3, lang, planKey(plan), m))?.review ?? null;
25602
25942
  } catch {
25603
25943
  return null;
25604
25944
  }
@@ -25628,27 +25968,44 @@ function createAgentService(deps) {
25628
25968
  reparseClaims.set(id, p);
25629
25969
  return p;
25630
25970
  }
25631
- function start(matchId, hero, lang, { admit, admitParse, plan = null, model = null } = {}) {
25971
+ function start(matchId, hero, lang, { admit, admitParse, plan = null, model = null, refresh = false } = {}) {
25632
25972
  const m = modelOf(model);
25633
25973
  if (m === false) return Promise.resolve({ status: "unavailable", reason: "model_not_offered" });
25634
25974
  const L3 = normalizeUiLang(lang);
25635
25975
  const pPlan = planKey(plan);
25636
- const claim = `${matchId}|${String(hero ?? "").trim().toLowerCase().replace(/^npc_dota_hero_/, "").replace(/[\s-]+/g, "_")}|${L3}|${pPlan ?? ""}|${m ?? ""}`;
25637
- let pending = starting.get(claim);
25638
- if (!pending) {
25639
- pending = begin(matchId, hero, L3, admit, pPlan, m, admitParse).finally(() => starting.delete(claim));
25640
- starting.set(claim, pending);
25641
- }
25642
- return pending.then((res) => {
25643
- if (res?.status !== "ready") return res;
25644
- const rev = res.reviews?.[L3] ?? (res.review?.lang === L3 ? res.review : null);
25645
- if (rev) return { ...res, review: rev };
25646
- return begin(matchId, hero, L3, admit, pPlan, m, admitParse);
25647
- });
25976
+ const forceRefresh = refresh === true;
25977
+ const claim = `${matchId}|${heroKeyOf(hero)}|${L3}|${pPlan ?? ""}|${m ?? ""}`;
25978
+ const runAttempt = (retried = 0) => {
25979
+ let entry = starting.get(claim);
25980
+ if (!entry) {
25981
+ const currentEntry = { promise: null, refresh: forceRefresh };
25982
+ currentEntry.promise = begin(matchId, hero, L3, admit, pPlan, m, admitParse, forceRefresh).finally(() => {
25983
+ if (starting.get(claim) === currentEntry) starting.delete(claim);
25984
+ });
25985
+ entry = currentEntry;
25986
+ starting.set(claim, entry);
25987
+ }
25988
+ return entry.promise.then(async (res) => {
25989
+ if (forceRefresh && !entry.refresh && res?.status === "ready" && res.stale_version === true && retried < 4) {
25990
+ return runAttempt(retried + 1);
25991
+ }
25992
+ if (!forceRefresh && entry.refresh && (res?.status === "refused" || res?.status === "unavailable")) {
25993
+ const cached = await status(matchId, hero, L3, pPlan, m);
25994
+ if (cached.status === "ready") return cached;
25995
+ return res;
25996
+ }
25997
+ if (res?.status !== "ready") return res;
25998
+ const rev = res.reviews?.[L3] ?? (res.review?.lang === L3 ? res.review : null);
25999
+ if (rev) return { ...res, review: rev };
26000
+ return begin(matchId, hero, L3, admit, pPlan, m, admitParse, forceRefresh);
26001
+ });
26002
+ };
26003
+ return runAttempt();
25648
26004
  }
25649
- async function begin(matchId, hero, lang, admit, plan, model, admitParse) {
26005
+ async function begin(matchId, hero, lang, admit, plan, model, admitParse, refresh = false) {
25650
26006
  const current2 = await status(matchId, hero, lang, plan, model);
25651
- if (current2.status !== "none" && current2.status !== "failed") return current2;
26007
+ const canUpgradeStale = refresh === true && current2.status === "ready" && current2.stale_version === true;
26008
+ if (current2.status !== "none" && current2.status !== "failed" && !canUpgradeStale) return current2;
25652
26009
  if (!engineOf(model)) return { status: "unavailable", reason: "model_not_configured" };
25653
26010
  const modelKey = idOf(model) ?? "";
25654
26011
  const monitorDown = deps.balanceMonitor?.down?.(modelKey) ?? null;
@@ -25882,7 +26239,7 @@ function createAgentService(deps) {
25882
26239
  if (!trace || !key) return { status: "gone" };
25883
26240
  if (!engineOf(model)) return { status: "unavailable" };
25884
26241
  const id = jobKeyOf(matchId, key, lang, plan, model);
25885
- if (await stored(matchId, key, lang, plan, model)) return { status: "ready" };
26242
+ if (await storedExact(matchId, key, lang, plan, model)) return { status: "ready" };
25886
26243
  const marker = await read(`${id}.job.json`);
25887
26244
  if (marker?.state === "running" && marker.runner && marker.runner !== runner && now() - (marker.at ?? 0) < REVIEW_BUSY_MS) return { status: "busy" };
25888
26245
  if (jobs.get(id)?.state === "running") return { status: "busy" };
@@ -25935,7 +26292,7 @@ function createAgentService(deps) {
25935
26292
  const fbKeyPrefix = legacyKeyOf(matchId, key, L3, p, m);
25936
26293
  const job = jobs.get(id);
25937
26294
  const memReview = job?.state === "ready" ? job.result.reviews?.[L3] ?? (job.result.review?.lang === L3 ? job.result.review : null) : null;
25938
- const rev = memReview ?? (await stored(matchId, key, L3, p, m))?.review ?? null;
26295
+ const rev = memReview ?? (await storedExact(matchId, key, L3, p, m))?.review ?? null;
25939
26296
  if (!rev) return { status: "no_review" };
25940
26297
  const record = feedbackRecord({ matchId, hero: key, lang: L3, plan: p, model: idOf(m), promptVersion: DEEP_REVIEW_PROMPT_VERSION, review: rev, value, at: now() });
25941
26298
  if (record.error) return { status: record.error };
@@ -26028,7 +26385,14 @@ function shapeReview(matchId, hero, lang, state) {
26028
26385
  ...state?.usage && typeof state.usage === "object" ? { usage: state.usage } : {},
26029
26386
  ..."usage_source" in (state ?? {}) ? { usage_source: state.usage_source } : state?.usage && "source" in state.usage ? { usage_source: state.usage.source } : {},
26030
26387
  checked: { against: "replay records", removed_for_lack_of_evidence: state.verification?.dropped ?? 0 },
26031
- note: "Times and numbers were checked against the replay. Present in a warm, constructive coach tone (verdict + opening_note, concrete highlights, key chapters/findings, encouragement) with zero mechanical next-game KPI quotas. Quote times and numbers as given, say what the review cannot see (blind_spots), and link the url: it has every piece of evidence and a coach to ask."
26388
+ ...state?.stale_version ? {
26389
+ cached: true,
26390
+ stale_version: true,
26391
+ ...Number.isInteger(state.prompt_version) ? { prompt_version: state.prompt_version } : {},
26392
+ ...Number.isInteger(state.latest_prompt_version) ? { latest_prompt_version: state.latest_prompt_version } : {},
26393
+ ...state.refresh_failed && typeof state.refresh_failed === "object" ? { refresh_failed: { reason: state.refresh_failed.reason ?? null } } : {}
26394
+ } : {},
26395
+ note: state?.stale_version && state.refresh_failed && typeof state.refresh_failed === "object" ? `Times and numbers were checked against the replay. Present in a warm, constructive coach tone (verdict + opening_note, concrete highlights, key chapters/findings, encouragement) with zero mechanical next-game KPI quotas. Quote times and numbers as given, say what the review cannot see (blind_spots), and link the url: it has every piece of evidence and a coach to ask. Updating this cached${Number.isInteger(state.prompt_version) ? ` v${state.prompt_version}` : ""} review${Number.isInteger(state.latest_prompt_version) ? ` to v${state.latest_prompt_version}` : ""} failed${state.refresh_failed.reason ? ` (${state.refresh_failed.reason})` : ""}; returning the saved review instead. Call replay_review with refresh: true and retry: true only if the user explicitly wants to retry regenerating it (this counts as a new start).` : state?.stale_version && Number.isInteger(state.prompt_version) ? `Times and numbers were checked against the replay. Present in a warm, constructive coach tone (verdict + opening_note, concrete highlights, key chapters/findings, encouragement) with zero mechanical next-game KPI quotas. Quote times and numbers as given, say what the review cannot see (blind_spots), and link the url: it has every piece of evidence and a coach to ask. This cached review was written under coach v${state.prompt_version}${Number.isInteger(state.latest_prompt_version) ? ` (latest is v${state.latest_prompt_version})` : ""}; call replay_review with refresh: true only if the user explicitly wants to regenerate it.` : "Times and numbers were checked against the replay. Present in a warm, constructive coach tone (verdict + opening_note, concrete highlights, key chapters/findings, encouragement) with zero mechanical next-game KPI quotas. Quote times and numbers as given, say what the review cannot see (blind_spots), and link the url: it has every piece of evidence and a coach to ask."
26032
26396
  };
26033
26397
  }
26034
26398
  var OWN_MODEL = "To review now on your own model instead, install the dota2.ai plugin for DeepSeek Harness (DSH): https://dota2.ai/#ways-dsh";
@@ -26087,21 +26451,38 @@ async function replayReview(api, args) {
26087
26451
  message: "The coach could not finish a review it could back with the replay. It often works on a second try: call replay_review again with retry: true (this counts as a new start)."
26088
26452
  };
26089
26453
  }
26090
- if (state.status === "none" || state.status === "failed") {
26091
- if (!avail.model_configured) return { status: "unavailable", reason: "model_not_configured", message: "The coach is not available on this server right now." };
26092
- const r = await api.start(matchId, hero.hero, lang);
26454
+ let refreshFailure = state.status === "ready" && state.stale_version === true ? state.refresh_failed ?? null : null;
26455
+ if (!refreshFailure && args?.refresh === true && state.status === "ready" && state.stale_version === true && args?.retry !== true && api.lastFailure) {
26456
+ const f = await api.lastFailure(matchId, hero.hero, lang);
26457
+ if (f) refreshFailure = { reason: f.reason ?? null };
26458
+ }
26459
+ const wantsRefresh = args?.refresh === true && state.status === "ready" && state.stale_version === true && (!refreshFailure || args?.retry === true);
26460
+ if (state.status === "none" || state.status === "failed" || wantsRefresh) {
26461
+ if (!avail.model_configured) {
26462
+ if (wantsRefresh) return shapeReview(matchId, hero.hero, lang, { ...state, refresh_failed: { reason: "model_not_configured" } });
26463
+ return { status: "unavailable", reason: "model_not_configured", message: "The coach is not available on this server right now." };
26464
+ }
26465
+ const prevReady = wantsRefresh ? state : null;
26466
+ const r = wantsRefresh ? await api.start(matchId, hero.hero, lang, { refresh: true }) : await api.start(matchId, hero.hero, lang);
26093
26467
  if (r.status === 429 || r.status === 503 && r.body?.retryAfterSec) throw refusal2(r);
26094
- if (r.status === 503) return { status: "unavailable", reason: "model_not_configured", message: "The coach is not available on this server right now." };
26468
+ if (r.status === 503) {
26469
+ if (prevReady) return shapeReview(matchId, hero.hero, lang, { ...prevReady, refresh_failed: { reason: r.body?.reason ?? "model_not_configured" } });
26470
+ return { status: "unavailable", reason: r.body?.reason ?? "model_not_configured", message: "The coach is not available on this server right now." };
26471
+ }
26472
+ if (prevReady && (r.body?.status === "failed" || r.body?.status === "unavailable")) {
26473
+ return shapeReview(matchId, hero.hero, lang, { ...prevReady, refresh_failed: { reason: r.body.reason ?? null } });
26474
+ }
26095
26475
  state = r.body;
26476
+ refreshFailure = null;
26096
26477
  }
26097
- if (state.status === "ready") return shapeReview(matchId, hero.hero, lang, state);
26478
+ if (state.status === "ready") return shapeReview(matchId, hero.hero, lang, refreshFailure ? { ...state, refresh_failed: refreshFailure } : state);
26098
26479
  return {
26099
26480
  status: "reviewing",
26100
26481
  match_id: matchId,
26101
26482
  hero: hero.hero,
26102
26483
  lang,
26103
26484
  steps: Array.isArray(state.steps) ? state.steps.length : 0,
26104
- message: "The coach is going through the replay (two to three minutes in all). Call replay_review again with the same arguments.",
26485
+ message: args?.retry === true ? "The coach is going through the replay (two to three minutes in all). Call replay_review again without retry: true to check progress." : "The coach is going through the replay (two to three minutes in all). Call replay_review again with the same arguments.",
26105
26486
  poll_after_sec: POLL_AFTER_SEC
26106
26487
  };
26107
26488
  }
@@ -27810,10 +28191,12 @@ function createDshService({
27810
28191
  const localReview = (out) => {
27811
28192
  if (out?.status !== "ready") return out;
27812
28193
  const { url: _public, ...rest } = out;
28194
+ const staleHint = out.stale_version && out.refresh_failed && typeof out.refresh_failed === "object" ? ` Updating this cached${Number.isInteger(out.prompt_version) ? ` v${out.prompt_version}` : ""} review${Number.isInteger(out.latest_prompt_version) ? ` to v${out.latest_prompt_version}` : ""} failed${out.refresh_failed.reason ? ` (${out.refresh_failed.reason})` : ""}; returning the saved review instead. Call dota2ai_replay_review with refresh: true and retry: true only if the user explicitly wants to retry regenerating it (this counts as a new start).` : out.stale_version && Number.isInteger(out.prompt_version) ? ` This cached review was written under coach v${out.prompt_version}${Number.isInteger(out.latest_prompt_version) ? ` (latest is v${out.latest_prompt_version})` : ""}; call dota2ai_replay_review with refresh: true only if the user explicitly wants to regenerate it.` : "";
27813
28195
  return {
27814
28196
  ...rest,
28197
+ cache_scope: "dsh_local",
27815
28198
  panel_route: `/r/${out.match_id}?hero=${encodeURIComponent(out.hero)}&lang=${out.lang}`,
27816
- note: "Times and numbers were checked against the replay. Quote them as given and say what the review cannot see (blind_spots). It was written on the user's own DSH model and is kept on this machine: point them to the dota2.ai panel in the DSH sidebar (the tool card's button opens it at panel_route), which has every piece of evidence and a coach to ask. The public dota2.ai link would not show this review."
28199
+ note: `Times and numbers were checked against the replay. Quote them as given and say what the review cannot see (blind_spots). It was written on the user's own DSH model and is kept on this machine (local private DSH cache, separate from the public dota2.ai web cache; replay traces can be reused, while local reviews are never auto-published): point them to the dota2.ai panel in the DSH sidebar (the tool card's button opens it at panel_route), which has every piece of evidence and a coach to ask. The public dota2.ai link would not show this review.${staleHint}`
27817
28200
  };
27818
28201
  };
27819
28202
  const replay = {
@@ -27829,8 +28212,8 @@ function createDshService({
27829
28212
  const out = await agent.prepare(String(id));
27830
28213
  return { status: out.status === "running" ? 202 : out.status === "unavailable" ? 503 : 200, body: out };
27831
28214
  },
27832
- start: async (id, hero, lang) => {
27833
- const out = await agent.start(String(id), hero, normalizeUiLang(lang));
28215
+ start: async (id, hero, lang, opts) => {
28216
+ const out = await agent.start(String(id), hero, normalizeUiLang(lang), opts?.refresh ? { refresh: true } : void 0);
27834
28217
  return { status: out.status === "running" ? 202 : out.status === "unavailable" ? 503 : 200, body: out };
27835
28218
  }
27836
28219
  }, args));
@@ -27889,7 +28272,8 @@ function createDshService({
27889
28272
  if (plan === false) return { status: 400, body: { code: "invalid_plan", error: "Unknown plan" } };
27890
28273
  const model = b.model == null || b.model === "" ? null : agent.modelOf(b.model);
27891
28274
  if (model === false) return { status: 400, body: { code: "invalid_model", error: "Unknown model" } };
27892
- const out = await agent.start(id, hero, normalizeUiLang(b.lang), { plan, model });
28275
+ const refresh = b.refresh === true || b.force === true;
28276
+ const out = await agent.start(id, hero, normalizeUiLang(b.lang), { plan, model, ...refresh ? { refresh: true } : {} });
27893
28277
  return { status: out.status === "running" ? 202 : out.status === "unavailable" ? 503 : 200, body: out };
27894
28278
  }
27895
28279
  }