@qianhaoq/dsh-dota2ai 0.2.9 → 0.2.10

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 (3) hide show
  1. package/lib/client.js +236 -7
  2. package/lib/index.js +352 -63
  3. package/package.json +1 -1
package/lib/index.js CHANGED
@@ -22027,6 +22027,134 @@ function nameHeroes(review, names2, places = {}) {
22027
22027
  };
22028
22028
  }
22029
22029
 
22030
+ // lib/agent/usage.js
22031
+ var nonNegNum = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : null;
22032
+ function emptyUsage() {
22033
+ return {
22034
+ input: 0,
22035
+ output: 0,
22036
+ input_uncached: null,
22037
+ cache_read: null,
22038
+ cache_write: null,
22039
+ source: null
22040
+ };
22041
+ }
22042
+ function parseDshUsage(u) {
22043
+ if (!u || typeof u !== "object") return emptyUsage();
22044
+ const rawInput = nonNegNum(u.inputTokens);
22045
+ const cacheRead = nonNegNum(u.cacheReadTokens);
22046
+ const cacheWrite = nonNegNum(u.cacheWriteTokens);
22047
+ const rawOutput = nonNegNum(u.outputTokens);
22048
+ const reported = rawInput != null || cacheRead != null || cacheWrite != null || rawOutput != null;
22049
+ if (!reported) return emptyUsage();
22050
+ const hasCacheSplit = cacheRead != null || cacheWrite != null;
22051
+ return {
22052
+ input: (rawInput ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0),
22053
+ output: rawOutput ?? 0,
22054
+ input_uncached: hasCacheSplit ? rawInput : null,
22055
+ cache_read: cacheRead,
22056
+ cache_write: cacheWrite,
22057
+ source: "provider_usage"
22058
+ };
22059
+ }
22060
+ function normalizeStepUsage(u) {
22061
+ if (!u || typeof u !== "object") return emptyUsage();
22062
+ const input = nonNegNum(u.input);
22063
+ const output = nonNegNum(u.output);
22064
+ const inputUncached = nonNegNum(u.input_uncached);
22065
+ const cacheRead = nonNegNum(u.cache_read);
22066
+ const cacheWrite = nonNegNum(u.cache_write);
22067
+ const explicitSource = u.source === "provider_usage" ? (
22068
+ /** @type {'provider_usage'} */
22069
+ "provider_usage"
22070
+ ) : u.source === null ? null : void 0;
22071
+ const hasCounts = input != null || output != null || inputUncached != null || cacheRead != null || cacheWrite != null;
22072
+ const source = explicitSource !== void 0 ? explicitSource : hasCounts ? "provider_usage" : null;
22073
+ return {
22074
+ input: input ?? 0,
22075
+ output: output ?? 0,
22076
+ input_uncached: inputUncached,
22077
+ cache_read: cacheRead,
22078
+ cache_write: cacheWrite,
22079
+ source
22080
+ };
22081
+ }
22082
+ function createUsageAccumulator(initial = null, initialSteps = 0) {
22083
+ let calls = 0;
22084
+ let input = 0;
22085
+ let output = 0;
22086
+ let inputUncached = 0;
22087
+ let cacheRead = 0;
22088
+ let cacheWrite = 0;
22089
+ let inputUncachedKnown = true;
22090
+ let cacheReadKnown = true;
22091
+ let cacheWriteKnown = true;
22092
+ let sourceKnown = true;
22093
+ if (initial && typeof initial === "object" && initialSteps > 0) {
22094
+ calls = initialSteps;
22095
+ input = nonNegNum(initial.input) ?? 0;
22096
+ output = nonNegNum(initial.output) ?? 0;
22097
+ const iu = nonNegNum(initial.input_uncached);
22098
+ const cr = nonNegNum(initial.cache_read);
22099
+ const cw = nonNegNum(initial.cache_write);
22100
+ if (iu != null) inputUncached = iu;
22101
+ else inputUncachedKnown = false;
22102
+ if (cr != null) cacheRead = cr;
22103
+ else cacheReadKnown = false;
22104
+ if (cw != null) cacheWrite = cw;
22105
+ else cacheWriteKnown = false;
22106
+ if (initial.source === "provider_usage") sourceKnown = true;
22107
+ else if (initial.source === null) sourceKnown = false;
22108
+ else sourceKnown = nonNegNum(initial.input) != null && nonNegNum(initial.output) != null && (input > 0 || output > 0);
22109
+ }
22110
+ return {
22111
+ add(stepUsage) {
22112
+ const u = normalizeStepUsage(stepUsage);
22113
+ calls += 1;
22114
+ input += u.input;
22115
+ output += u.output;
22116
+ if (inputUncachedKnown && u.input_uncached != null) inputUncached += u.input_uncached;
22117
+ else inputUncachedKnown = false;
22118
+ if (cacheReadKnown && u.cache_read != null) cacheRead += u.cache_read;
22119
+ else cacheReadKnown = false;
22120
+ if (cacheWriteKnown && u.cache_write != null) cacheWrite += u.cache_write;
22121
+ else cacheWriteKnown = false;
22122
+ if (u.source !== "provider_usage") sourceKnown = false;
22123
+ },
22124
+ snapshot() {
22125
+ if (calls === 0) return emptyUsage();
22126
+ return {
22127
+ input,
22128
+ output,
22129
+ input_uncached: inputUncachedKnown ? inputUncached : null,
22130
+ cache_read: cacheReadKnown ? cacheRead : null,
22131
+ cache_write: cacheWriteKnown ? cacheWrite : null,
22132
+ source: sourceKnown ? "provider_usage" : null
22133
+ };
22134
+ }
22135
+ };
22136
+ }
22137
+ function mergeUsages(list) {
22138
+ const acc = createUsageAccumulator();
22139
+ for (const item of list ?? []) {
22140
+ if (!item || typeof item !== "object") continue;
22141
+ acc.add(item);
22142
+ }
22143
+ return acc.snapshot();
22144
+ }
22145
+ function formatUsageLog(u) {
22146
+ if (!u || typeof u !== "object") return "in=0 out=0";
22147
+ const parts = [`in=${u.input ?? 0}`];
22148
+ if (typeof u.input_uncached === "number") parts.push(`uncached=${u.input_uncached}`);
22149
+ if (typeof u.cache_read === "number") {
22150
+ const pct6 = typeof u.input === "number" && u.input > 0 ? Math.round(u.cache_read / u.input * 100) : null;
22151
+ parts.push(`cache_read=${u.cache_read}${pct6 != null ? `(${pct6}%)` : ""}`);
22152
+ }
22153
+ if (typeof u.cache_write === "number") parts.push(`cache_write=${u.cache_write}`);
22154
+ parts.push(`out=${u.output ?? 0}`);
22155
+ return parts.join(" ");
22156
+ }
22157
+
22030
22158
  // lib/agent/loop.js
22031
22159
  var AGENT_DEFAULTS = { maxSteps: 28, maxToolCalls: 60, maxToolChars: 4e4 };
22032
22160
  var TRUNCATION_RETRY_INSTRUCTION = "Your previous response hit the output token limit before finishing its tool call. Keep your reasoning brief and call the tool directly now.";
@@ -22034,6 +22162,41 @@ function toolContent(result2, max) {
22034
22162
  const text = typeof result2 === "string" ? result2 : JSON.stringify(result2);
22035
22163
  return text.length <= max ? text : `${text.slice(0, max)}\u2026[truncated: ${text.length - max} more characters; ask for a narrower slice]`;
22036
22164
  }
22165
+ function canonicalJson(value) {
22166
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
22167
+ if (Array.isArray(value)) return `[${value.map((v) => v === void 0 ? "null" : canonicalJson(v)).join(",")}]`;
22168
+ const keys = Object.keys(value).filter((k3) => value[k3] !== void 0).sort();
22169
+ return `{${keys.map((k3) => `${JSON.stringify(k3)}:${canonicalJson(value[k3])}`).join(",")}}`;
22170
+ }
22171
+ function toolCallKey(name2, args) {
22172
+ return `${name2}\0${canonicalJson(args ?? {})}`;
22173
+ }
22174
+ function seedPriorToolCalls(messages) {
22175
+ const callById = /* @__PURE__ */ new Map();
22176
+ const prior = /* @__PURE__ */ new Map();
22177
+ for (const m of messages) {
22178
+ if (m?.role === "assistant" && Array.isArray(m.tool_calls)) {
22179
+ for (const tc of m.tool_calls) {
22180
+ if (!tc?.id || !tc?.function?.name) continue;
22181
+ let args = {};
22182
+ try {
22183
+ args = tc.function.arguments ? JSON.parse(tc.function.arguments) : {};
22184
+ } catch {
22185
+ continue;
22186
+ }
22187
+ if (args == null || typeof args !== "object" || Array.isArray(args)) continue;
22188
+ callById.set(tc.id, toolCallKey(tc.function.name, args));
22189
+ }
22190
+ } else if (m?.role === "tool" && m.tool_call_id) {
22191
+ const key = callById.get(m.tool_call_id);
22192
+ const content = String(m.content ?? "");
22193
+ if (key && !prior.has(key) && !content.startsWith('{"error":') && !content.startsWith('{"duplicate_of":')) {
22194
+ prior.set(key, { id: m.tool_call_id, chars: content.length });
22195
+ }
22196
+ }
22197
+ }
22198
+ return prior;
22199
+ }
22037
22200
  async function runAgent(o) {
22038
22201
  const { complete, system, tools, runTool, isFinal = () => false, signal, onEvent = () => {
22039
22202
  } } = o;
@@ -22043,12 +22206,14 @@ async function runAgent(o) {
22043
22206
  const maxTruncationRetries = o.maxTruncationRetries ?? 1;
22044
22207
  const messages = [...o.messages];
22045
22208
  const transcript = [...o.resume?.transcript ?? []];
22046
- const usage = { input: o.resume?.usage?.input ?? 0, output: o.resume?.usage?.output ?? 0 };
22209
+ const usageAcc = createUsageAccumulator(o.resume?.usage, o.resume?.steps ?? 0);
22210
+ const priorToolCalls = seedPriorToolCalls(messages);
22047
22211
  const known = new Set(tools.map((t6) => t6.name));
22048
22212
  const finalTools = new Set(o.finalTools ?? []);
22049
22213
  let steps = o.resume?.steps ?? 0;
22050
22214
  let calls = o.resume?.calls ?? 0;
22051
- let truncationRetries = 0;
22215
+ let truncationRetries = o.resume?.truncation_retries ?? 0;
22216
+ let duplicateToolCalls = o.resume?.duplicate_tool_calls ?? 0;
22052
22217
  let retryNudge = null;
22053
22218
  while (steps < maxSteps) {
22054
22219
  signal?.throwIfAborted();
@@ -22057,8 +22222,7 @@ async function runAgent(o) {
22057
22222
  retryNudge = null;
22058
22223
  const reply = await complete({ system, messages: callMessages, tools: spent ? tools.filter((t6) => finalTools.has(t6.name)) : tools, signal });
22059
22224
  steps += 1;
22060
- usage.input += reply.usage?.input ?? 0;
22061
- usage.output += reply.usage?.output ?? 0;
22225
+ usageAcc.add(reply.usage);
22062
22226
  const toolCalls = (reply.toolCalls ?? []).filter((c) => !spent || finalTools.has(c.name));
22063
22227
  const truncatedIncomplete = Boolean(reply.truncated) && (!toolCalls.length || toolCalls.some((c) => c.argsError));
22064
22228
  if (truncatedIncomplete) {
@@ -22069,11 +22233,11 @@ async function runAgent(o) {
22069
22233
  continue;
22070
22234
  }
22071
22235
  messages.push({ role: "assistant", content: reply.text ?? "" });
22072
- return { status: "truncated", text: reply.text ?? "", final: null, messages, transcript, steps, usage };
22236
+ return { status: "truncated", text: reply.text ?? "", final: null, messages, transcript, steps, truncation_retries: truncationRetries, duplicate_tool_calls: duplicateToolCalls, usage: usageAcc.snapshot() };
22073
22237
  }
22074
22238
  if (!toolCalls.length) {
22075
22239
  messages.push({ role: "assistant", content: reply.text ?? "" });
22076
- return { status: "answered", text: reply.text ?? "", final: null, messages, transcript, steps, usage };
22240
+ return { status: "answered", text: reply.text ?? "", final: null, messages, transcript, steps, truncation_retries: truncationRetries, duplicate_tool_calls: duplicateToolCalls, usage: usageAcc.snapshot() };
22077
22241
  }
22078
22242
  messages.push({
22079
22243
  role: "assistant",
@@ -22083,29 +22247,46 @@ async function runAgent(o) {
22083
22247
  tool_calls: toolCalls.map((c) => ({ id: c.id, type: "function", function: { name: c.name, arguments: JSON.stringify(c.args ?? {}) } }))
22084
22248
  });
22085
22249
  const done = toolCalls.find((c) => !c.argsError && known.has(c.name) && isFinal(c));
22086
- if (done) return { status: "final", text: reply.text ?? "", final: done.args, messages, transcript, steps, usage };
22250
+ if (done) return { status: "final", text: reply.text ?? "", final: done.args, messages, transcript, steps, truncation_retries: truncationRetries, duplicate_tool_calls: duplicateToolCalls, usage: usageAcc.snapshot() };
22087
22251
  for (const call of toolCalls) {
22088
22252
  signal?.throwIfAborted();
22089
- let result2;
22090
- if (calls >= maxToolCalls) result2 = { error: "tool_budget_spent" };
22091
- else if (call.argsError) result2 = { error: "invalid_arguments", detail: "arguments were not valid JSON" };
22092
- else if (!known.has(call.name)) result2 = { error: "unknown_tool", tools: [...known] };
22253
+ let content;
22254
+ if (calls >= maxToolCalls) content = toolContent({ error: "tool_budget_spent" }, maxToolChars);
22255
+ else if (call.argsError) content = toolContent({ error: "invalid_arguments", detail: "arguments were not valid JSON" }, maxToolChars);
22256
+ else if (!known.has(call.name)) content = toolContent({ error: "unknown_tool", tools: [...known] }, maxToolChars);
22093
22257
  else {
22094
- calls += 1;
22095
- onEvent({ type: "tool_start", name: call.name, args: call.args });
22096
- try {
22097
- result2 = await runTool(call.name, call.args ?? {});
22098
- } catch {
22099
- result2 = { error: "tool_failed" };
22258
+ const args = call.args ?? {};
22259
+ const key = toolCallKey(call.name, args);
22260
+ const prior = priorToolCalls.get(key);
22261
+ const dupPointer = prior ? JSON.stringify({ duplicate_of: prior.id, tool: call.name, note: "Identical tool result already returned earlier in this conversation; reuse that result." }) : null;
22262
+ if (prior && dupPointer && prior.chars > dupPointer.length) {
22263
+ calls += 1;
22264
+ duplicateToolCalls += 1;
22265
+ onEvent({ type: "tool_start", name: call.name, args, duplicate: true });
22266
+ onEvent({ type: "tool_end", name: call.name, ok: true, duplicate: true });
22267
+ content = dupPointer;
22268
+ } else {
22269
+ calls += 1;
22270
+ onEvent({ type: "tool_start", name: call.name, args });
22271
+ let result2;
22272
+ try {
22273
+ result2 = await runTool(call.name, args);
22274
+ } catch {
22275
+ result2 = { error: "tool_failed" };
22276
+ }
22277
+ onEvent({ type: "tool_end", name: call.name, ok: !result2?.error });
22278
+ transcript.push({ name: call.name, args, result: result2 });
22279
+ content = toolContent(result2, maxToolChars);
22280
+ if (!result2?.error && !priorToolCalls.has(key)) {
22281
+ priorToolCalls.set(key, { id: call.id, chars: content.length });
22282
+ }
22100
22283
  }
22101
- onEvent({ type: "tool_end", name: call.name, ok: !result2?.error });
22102
- transcript.push({ name: call.name, args: call.args ?? {}, result: result2 });
22103
22284
  }
22104
- messages.push({ role: "tool", tool_call_id: call.id, content: toolContent(result2, maxToolChars) });
22285
+ messages.push({ role: "tool", tool_call_id: call.id, content });
22105
22286
  }
22106
- o.onCheckpoint?.({ messages: [...messages], steps, calls, usage: { ...usage }, transcript: [...transcript] });
22287
+ o.onCheckpoint?.({ messages: [...messages], steps, calls, truncation_retries: truncationRetries, duplicate_tool_calls: duplicateToolCalls, usage: usageAcc.snapshot(), transcript: [...transcript] });
22107
22288
  }
22108
- return { status: "budget", text: "", final: null, messages, transcript, steps, usage };
22289
+ return { status: "budget", text: "", final: null, messages, transcript, steps, truncation_retries: truncationRetries, duplicate_tool_calls: duplicateToolCalls, usage: usageAcc.snapshot() };
22109
22290
  }
22110
22291
 
22111
22292
  // node_modules/jsonrepair/lib/esm/utils/JSONRepairError.js
@@ -23212,9 +23393,10 @@ var TRANSLATE_SYSTEM = [
23212
23393
  async function translateReview({ complete, review, sourceLang, targetLangs, trace = null, sources = null, signal, onEvent }) {
23213
23394
  const src = normalizeUiLang(sourceLang);
23214
23395
  const targets = [...new Set((targetLangs ?? SUPPORTED_LANGS.filter((l) => l !== src)).map(normalizeUiLang).filter((l) => l !== src))];
23215
- const usage = { input: 0, output: 0 };
23396
+ const usageAcc = createUsageAccumulator();
23397
+ let steps = 0;
23216
23398
  const reviews = {};
23217
- if (!complete || !review || !targets.length) return { reviews, usage };
23399
+ if (!complete || !review || !targets.length) return { reviews, steps, usage: usageAcc.snapshot() };
23218
23400
  const payload = extractTranslatable(review);
23219
23401
  const namesByLang = Object.fromEntries(targets.map((l) => [l, {
23220
23402
  heroes: trace ? heroNames(trace, l) : {},
@@ -23235,8 +23417,8 @@ async function translateReview({ complete, review, sourceLang, targetLangs, trac
23235
23417
  tools: [],
23236
23418
  signal
23237
23419
  });
23238
- usage.input += Number(res?.usage?.input ?? 0);
23239
- usage.output += Number(res?.usage?.output ?? 0);
23420
+ steps += 1;
23421
+ usageAcc.add(res?.usage);
23240
23422
  const raw = typeof res?.text === "string" ? res.text : "";
23241
23423
  const parsed = parseTranslationJson(raw);
23242
23424
  if (parsed) {
@@ -23256,7 +23438,7 @@ async function translateReview({ complete, review, sourceLang, targetLangs, trac
23256
23438
  }
23257
23439
  } catch {
23258
23440
  }
23259
- return { reviews, usage };
23441
+ return { reviews, steps, usage: usageAcc.snapshot() };
23260
23442
  }
23261
23443
 
23262
23444
  // lib/agent/review/run.js
@@ -23315,7 +23497,7 @@ function lookupAnswers(messages) {
23315
23497
  if (m?.role === "assistant") {
23316
23498
  for (const c of m.tool_calls ?? []) if (c?.function?.name === SUBMIT_REVIEW.name) submitted.add(c.id);
23317
23499
  }
23318
- if (m?.role === "tool" && !submitted.has(m.tool_call_id) && !/^\{"error":"(tool_budget_spent|invalid_arguments|unknown_tool|not_run|unsupported_facts)"/.test(String(m.content))) out.push(String(m.content));
23500
+ if (m?.role === "tool" && !submitted.has(m.tool_call_id) && !/^\{"error":"(tool_budget_spent|invalid_arguments|unknown_tool|not_run|unsupported_facts)"/.test(String(m.content)) && !/^\{"duplicate_of":[^,]+,"tool":/.test(String(m.content))) out.push(String(m.content));
23319
23501
  }
23320
23502
  return out;
23321
23503
  }
@@ -23337,13 +23519,10 @@ async function runDeepReview({ complete, trace, hero, lang, plan = null, match =
23337
23519
  isFinal: (call) => call.name === SUBMIT_REVIEW.name,
23338
23520
  finalTools: [SUBMIT_REVIEW.name]
23339
23521
  };
23340
- const usage = { input: 0, output: 0 };
23341
23522
  let steps = 0;
23342
- const add = (r) => {
23343
- usage.input += r.usage.input;
23344
- usage.output += r.usage.output;
23345
- steps += r.steps;
23346
- };
23523
+ const stageUsages = [];
23524
+ const stages = {};
23525
+ const stageEntry = (u, s, tc, tr2) => ({ ...u, steps: s, tool_calls: tc, truncation_retries: tr2 });
23347
23526
  const stated = planByKey(planKey(plan));
23348
23527
  const opening = `Review this game for the player on ${seat.key}.${stated ? `
23349
23528
  The player says their plan this game was to ${stated.for_the_model} (in their words: "${stated.said.en}"). Read the game against it in game_plan.against_your_plan.` : ""}
@@ -23366,7 +23545,14 @@ ${JSON.stringify(context)}`;
23366
23545
  }
23367
23546
  return out;
23368
23547
  };
23369
- const pack = (s) => ({ messages: s.messages, calls: s.transcript.map((t6) => ({ name: t6.name, args: t6.args })), steps: s.steps, usage: s.usage });
23548
+ const pack = (s) => ({
23549
+ messages: s.messages,
23550
+ calls: s.transcript.map((t6) => ({ name: t6.name, args: t6.args })),
23551
+ steps: s.steps,
23552
+ truncation_retries: s.truncation_retries ?? 0,
23553
+ duplicate_tool_calls: s.duplicate_tool_calls ?? 0,
23554
+ usage: s.usage
23555
+ });
23370
23556
  const save = (first2, run) => onCheckpoint?.({ v: REVIEW_CHECKPOINT_VERSION, hero: seat.key, lang: language, opening, first: first2, run });
23371
23557
  let firstAgain = null;
23372
23558
  let runAgain = null;
@@ -23378,11 +23564,27 @@ ${JSON.stringify(context)}`;
23378
23564
  if (from.first && !same(firstAgain, firstAnswers) || from.run && !same(runAgain, lookupAnswers(from.run.messages).slice(firstAnswers.length))) from = null;
23379
23565
  }
23380
23566
  if (from) kit.spendSearches([...from.first?.calls ?? [], ...from.run?.calls ?? []].filter((c) => c.name === WEB_SEARCH_TOOL.name).length);
23381
- const resumed = (s) => ({ steps: s.steps, calls: s.tool_count, usage: s.usage, transcript: runAgain });
23567
+ const resumed = (s) => ({
23568
+ steps: s.steps,
23569
+ calls: s.tool_count,
23570
+ truncation_retries: s.truncation_retries ?? 0,
23571
+ duplicate_tool_calls: s.duplicate_tool_calls ?? 0,
23572
+ usage: s.usage,
23573
+ transcript: runAgain
23574
+ });
23382
23575
  if (from) onEvent?.({ type: "resumed", tools: [...from.first?.calls ?? [], ...from.run?.calls ?? []] });
23383
23576
  let first;
23384
23577
  if (from?.first) {
23385
- first = { status: "final", final: submittedIn(from.first.messages.at(-1)), messages: from.first.messages, transcript: firstAgain, steps: from.first.steps, usage: from.first.usage };
23578
+ first = {
23579
+ status: "final",
23580
+ final: submittedIn(from.first.messages.at(-1)),
23581
+ messages: from.first.messages,
23582
+ transcript: firstAgain,
23583
+ steps: from.first.steps,
23584
+ truncation_retries: from.first.truncation_retries ?? 0,
23585
+ duplicate_tool_calls: from.first.duplicate_tool_calls ?? 0,
23586
+ usage: normalizeStepUsage(from.first.usage)
23587
+ };
23386
23588
  } else {
23387
23589
  first = await runAgent({
23388
23590
  ...base,
@@ -23391,11 +23593,25 @@ ${JSON.stringify(context)}`;
23391
23593
  onCheckpoint: (s) => save(null, { ...pack(s), tool_count: s.calls })
23392
23594
  });
23393
23595
  }
23394
- add(first);
23596
+ const firstUsage = normalizeStepUsage(first.usage);
23597
+ steps += first.steps;
23598
+ stageUsages.push(firstUsage);
23599
+ stages.first = stageEntry(firstUsage, first.steps, first.transcript.length, first.truncation_retries ?? 0);
23395
23600
  if (first.status !== "final") {
23396
23601
  const status = first.status === "budget" ? "budget" : first.status === "truncated" ? "output_cap" : "no_review";
23397
23602
  const detail = typeof first.text === "string" && first.text.trim() ? first.text.trim().slice(0, 400) : null;
23398
- return { status, steps, usage, transcript: first.transcript, ...detail ? { detail } : {} };
23603
+ const total2 = mergeUsages(stageUsages);
23604
+ return {
23605
+ status,
23606
+ steps,
23607
+ repair_rounds: 0,
23608
+ truncation_retries: first.truncation_retries ?? 0,
23609
+ duplicate_tool_calls: first.duplicate_tool_calls ?? 0,
23610
+ usage_source: total2.source,
23611
+ usage: { ...total2, stages },
23612
+ transcript: first.transcript,
23613
+ ...detail ? { detail } : {}
23614
+ };
23399
23615
  }
23400
23616
  const asReviewObj = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
23401
23617
  let review = asReviewObj(first.final);
@@ -23404,6 +23620,7 @@ ${JSON.stringify(context)}`;
23404
23620
  let check = verifyReview(review, sources());
23405
23621
  const firstProblems = check.problems;
23406
23622
  let repaired = false;
23623
+ let second = null;
23407
23624
  if (!check.ok) {
23408
23625
  repaired = true;
23409
23626
  const lastCall = first.messages.at(-1).tool_calls.find((c) => c.function.name === SUBMIT_REVIEW.name);
@@ -23421,7 +23638,7 @@ ${JSON.stringify(context)}`;
23421
23638
  ...suggested.length ? { suggested_refs: suggested } : {}
23422
23639
  };
23423
23640
  };
23424
- const second = await runAgent({
23641
+ second = await runAgent({
23425
23642
  ...base,
23426
23643
  ...midRepair ? { resume: resumed(midRepair) } : {},
23427
23644
  // The repair round's own counts start at zero; what it had used when cut off comes back with `resume`.
@@ -23432,7 +23649,10 @@ ${JSON.stringify(context)}`;
23432
23649
  content: c === lastCall ? JSON.stringify({ error: "unsupported_facts", detail: "Look each one up with a tool, or rewrite the sentence without it, then call submit_review again with the whole review.", problems: check.problems.map(formatProblem) }) : JSON.stringify({ error: "not_run" })
23433
23650
  }))]
23434
23651
  });
23435
- add(second);
23652
+ const secondUsage = normalizeStepUsage(second.usage);
23653
+ steps += second.steps;
23654
+ stageUsages.push(secondUsage);
23655
+ stages.repair = stageEntry(secondUsage, second.steps, second.transcript.length, second.truncation_retries ?? 0);
23436
23656
  if (second.status === "final") {
23437
23657
  review = asReviewObj(second.final);
23438
23658
  transcript = [...transcript, ...second.transcript];
@@ -23491,9 +23711,13 @@ ${JSON.stringify(context)}`;
23491
23711
  if (translate && ok && !signal?.aborted) {
23492
23712
  const tr2 = await translateReview({ complete, review: primary, sourceLang: language, trace, sources: sources(), signal, onEvent });
23493
23713
  Object.assign(reviews, tr2.reviews);
23494
- usage.input += tr2.usage.input;
23495
- usage.output += tr2.usage.output;
23714
+ if ((tr2.steps ?? 0) > 0) {
23715
+ const trUsage = normalizeStepUsage(tr2.usage);
23716
+ stageUsages.push(trUsage);
23717
+ stages.translate = stageEntry(trUsage, tr2.steps, 0, 0);
23718
+ }
23496
23719
  }
23720
+ const total = mergeUsages(stageUsages);
23497
23721
  return {
23498
23722
  status: ok ? "ok" : "unverified",
23499
23723
  review: primary,
@@ -23504,7 +23728,11 @@ ${JSON.stringify(context)}`;
23504
23728
  dropped_findings: rawFindings.filter((_, i) => bad("finding").has(i)),
23505
23729
  tool_calls: transcript.map((t6) => ({ name: t6.name, args: t6.args })),
23506
23730
  steps,
23507
- usage
23731
+ repair_rounds: repaired ? 1 : 0,
23732
+ truncation_retries: (first.truncation_retries ?? 0) + (second?.truncation_retries ?? 0),
23733
+ duplicate_tool_calls: (first.duplicate_tool_calls ?? 0) + (second?.duplicate_tool_calls ?? 0),
23734
+ usage_source: total.source,
23735
+ usage: { ...total, stages }
23508
23736
  };
23509
23737
  }
23510
23738
 
@@ -23648,32 +23876,41 @@ Review of this game: ${review ? JSON.stringify(review) : "none yet"}`;
23648
23876
  for (const h of history) messages.push({ role: "user", content: h.q }, { role: "assistant", content: h.a });
23649
23877
  messages.push({ role: "user", content: question });
23650
23878
  const base = { complete, system: chatSystem(kit.language), tools: kit.tools, runTool: kit.runTool, signal, onEvent, ...CHAT_BUDGET };
23651
- const usage = { input: 0, output: 0 };
23652
23879
  let run = await runAgent({ ...base, messages });
23653
- usage.input += run.usage.input;
23654
- usage.output += run.usage.output;
23655
- if (run.status !== "answered" || !run.text.trim()) return { status: "no_answer", usage };
23880
+ const stageUsages = [run.usage];
23881
+ let truncationRetries = run.truncation_retries ?? 0;
23882
+ let repairRounds = 0;
23883
+ if (run.status !== "answered" || !run.text.trim()) {
23884
+ const usage2 = mergeUsages(stageUsages);
23885
+ return { status: "no_answer", usage: usage2, usage_source: usage2.source, repair_rounds: repairRounds, truncation_retries: truncationRetries };
23886
+ }
23656
23887
  let transcript = run.transcript;
23888
+ const firstUsedCalls = transcript.length + (run.duplicate_tool_calls ?? 0);
23657
23889
  const checked = checkedPart(review);
23658
23890
  const sources = () => [kit.context, checked, history.filter((h) => h.clean).map((h) => h.a), ...transcript.map((t6) => t6.result).filter((r) => !isWebSearchResult(r))];
23659
23891
  const accepted = [...checked ? [JSON.stringify(checked)] : [], ...history.filter((h) => h.clean).map((h) => h.a)];
23660
23892
  let check = verifyText(run.text, sources(), accepted);
23661
23893
  if (!check.ok) {
23662
- const left = { maxToolCalls: Math.max(0, CHAT_BUDGET.maxToolCalls - transcript.length), maxSteps: Math.max(1, CHAT_BUDGET.maxSteps - run.steps) };
23894
+ repairRounds = 1;
23895
+ const left = { maxToolCalls: Math.max(0, CHAT_BUDGET.maxToolCalls - firstUsedCalls), maxSteps: Math.max(1, CHAT_BUDGET.maxSteps - run.steps) };
23663
23896
  const again = await runAgent({ ...base, ...left, messages: [...run.messages, { role: "user", content: `These are not in any tool result or in the review: ${check.problems.map((p) => p.text).join(", ")}. Look them up with a tool or rewrite the answer without them.${check.problems.some((p) => p.kind === "sight") ? " The replay data has no vision: never say who could see whom; give the distance or position a tool returned instead." : ""} Reply with the full corrected answer only.` }] });
23664
- usage.input += again.usage.input;
23665
- usage.output += again.usage.output;
23897
+ stageUsages.push(again.usage);
23898
+ truncationRetries += again.truncation_retries ?? 0;
23666
23899
  if (again.status === "answered" && again.text.trim()) {
23667
23900
  run = again;
23668
23901
  transcript = [...transcript, ...again.transcript];
23669
23902
  check = verifyText(run.text, sources(), accepted);
23670
23903
  }
23671
23904
  }
23905
+ const usage = mergeUsages(stageUsages);
23672
23906
  return {
23673
23907
  status: "ok",
23674
23908
  text: nameHeroes({ verdict: run.text }, kit.context.hero_names, kit.context.place_names).verdict,
23675
23909
  unverified: check.problems,
23676
23910
  tool_calls: transcript.map((t6) => ({ name: t6.name, args: t6.args })),
23911
+ repair_rounds: repairRounds,
23912
+ truncation_retries: truncationRetries,
23913
+ usage_source: usage.source,
23677
23914
  usage
23678
23915
  };
23679
23916
  }
@@ -25053,6 +25290,11 @@ function createAgentService(deps) {
25053
25290
  status: "ready",
25054
25291
  model: record.model,
25055
25292
  tool_calls: record.tool_calls,
25293
+ ...Number.isInteger(record.steps) ? { steps: record.steps } : {},
25294
+ ...Number.isInteger(record.repair_rounds) ? { repair_rounds: record.repair_rounds } : {},
25295
+ ...Number.isInteger(record.truncation_retries) ? { truncation_retries: record.truncation_retries } : {},
25296
+ ...record.usage ? { usage: record.usage } : {},
25297
+ ..."usage_source" in record ? { usage_source: record.usage_source } : record.usage && "source" in record.usage ? { usage_source: record.usage.source } : {},
25056
25298
  ...record.verification ? { verification: record.verification } : {},
25057
25299
  prompt_version: DEEP_REVIEW_PROMPT_VERSION,
25058
25300
  review: rev,
@@ -25256,13 +25498,25 @@ function createAgentService(deps) {
25256
25498
  reason,
25257
25499
  at,
25258
25500
  steps: meta.steps ?? job.steps.length,
25501
+ ...Number.isInteger(meta.repair_rounds) ? { repair_rounds: meta.repair_rounds } : {},
25502
+ ...Number.isInteger(meta.truncation_retries) ? { truncation_retries: meta.truncation_retries } : {},
25259
25503
  ...meta.usage ? { usage: meta.usage } : {},
25504
+ ..."usage_source" in meta ? { usage_source: meta.usage_source } : {},
25260
25505
  ...meta.detail ? { detail: meta.detail } : {}
25261
25506
  });
25262
25507
  if (!job.stopped) {
25263
25508
  const snap = lastCheckpoint ?? await read(cpKey);
25264
25509
  if (snap && snap.v) {
25265
- await write(failedCpKey, { ...snap, failed_at: at, reason, ...meta.usage ? { usage: meta.usage } : {}, ...meta.detail ? { detail: meta.detail } : {} });
25510
+ await write(failedCpKey, {
25511
+ ...snap,
25512
+ failed_at: at,
25513
+ reason,
25514
+ ...Number.isInteger(meta.repair_rounds) ? { repair_rounds: meta.repair_rounds } : {},
25515
+ ...Number.isInteger(meta.truncation_retries) ? { truncation_retries: meta.truncation_retries } : {},
25516
+ ...meta.usage ? { usage: meta.usage } : {},
25517
+ ..."usage_source" in meta ? { usage_source: meta.usage_source } : {},
25518
+ ...meta.detail ? { detail: meta.detail } : {}
25519
+ });
25266
25520
  }
25267
25521
  await endCheckpoint();
25268
25522
  }
@@ -25301,12 +25555,33 @@ function createAgentService(deps) {
25301
25555
  });
25302
25556
  if (out.verification?.problems?.length) await write(`${id}.unverified.json`, { at: now(), status: out.status, problems: out.verification.problems, dropped_findings: out.dropped_findings ?? [] });
25303
25557
  if (out.status !== "ok") {
25304
- await failed(out.status, { steps: out.steps, usage: out.usage, detail: out.detail ?? null });
25305
- log(`deep-review failed match=${matchId} hero=${key} plan=${plan ?? "none"}${tag} reason=${out.status} steps=${out.steps ?? 0} in=${out.usage?.input ?? 0} out=${out.usage?.output ?? 0}`);
25558
+ await failed(out.status, {
25559
+ steps: out.steps,
25560
+ repair_rounds: out.repair_rounds ?? 0,
25561
+ truncation_retries: out.truncation_retries ?? 0,
25562
+ usage: out.usage,
25563
+ usage_source: out.usage_source ?? out.usage?.source ?? null,
25564
+ detail: out.detail ?? null
25565
+ });
25566
+ log(`deep-review failed match=${matchId} hero=${key} plan=${plan ?? "none"}${tag} reason=${out.status} steps=${out.steps ?? 0} repairs=${out.repair_rounds ?? 0}${out.truncation_retries ? ` trunc_retries=${out.truncation_retries}` : ""} ${formatUsageLog(out.usage)}`);
25306
25567
  return;
25307
25568
  }
25308
25569
  const L3 = normalizeUiLang(lang);
25309
- const result2 = { schema: "dota2.ai/deep-review-bundle@1", primary_lang: L3, review: out.review, reviews: { [L3]: out.review }, verification: { repaired: out.verification.repaired, dropped: out.verification.dropped }, model: engine.name ?? null, tool_calls: out.tool_calls.length };
25570
+ const result2 = {
25571
+ schema: "dota2.ai/deep-review-bundle@1",
25572
+ primary_lang: L3,
25573
+ review: out.review,
25574
+ reviews: { [L3]: out.review },
25575
+ verification: { repaired: out.verification.repaired, dropped: out.verification.dropped },
25576
+ model: engine.name ?? null,
25577
+ steps: out.steps,
25578
+ tool_calls: out.tool_calls.length,
25579
+ repair_rounds: out.repair_rounds ?? 0,
25580
+ truncation_retries: out.truncation_retries ?? 0,
25581
+ ...out.duplicate_tool_calls ? { duplicate_tool_calls: out.duplicate_tool_calls } : {},
25582
+ usage: out.usage,
25583
+ usage_source: out.usage_source ?? out.usage?.source ?? null
25584
+ };
25310
25585
  await write(`${id}.review.json`, result2);
25311
25586
  await endCheckpoint();
25312
25587
  await drop(failedCpKey);
@@ -25314,7 +25589,7 @@ function createAgentService(deps) {
25314
25589
  job.state = "ready";
25315
25590
  await mark({ state: "done", at: now() });
25316
25591
  settle({ status: "ready" });
25317
- log(`deep-review ready match=${matchId} hero=${key} plan=${plan ?? "none"}${tag} steps=${out.steps} in=${out.usage.input} out=${out.usage.output} dropped=${out.verification.dropped} unverified=${out.verification.problems.map((p) => `${p.where}${p.index + 1}:${p.kind}`).join(",") || "none"} lang=${L3}`);
25592
+ log(`deep-review ready match=${matchId} hero=${key} plan=${plan ?? "none"}${tag} steps=${out.steps} tools=${out.tool_calls.length} repairs=${out.repair_rounds ?? 0}${out.truncation_retries ? ` trunc_retries=${out.truncation_retries}` : ""}${out.duplicate_tool_calls ? ` deduped=${out.duplicate_tool_calls}` : ""} ${formatUsageLog(out.usage)} dropped=${out.verification.dropped} unverified=${out.verification.problems.map((p) => `${p.where}${p.index + 1}:${p.kind}`).join(",") || "none"} lang=${L3}`);
25318
25593
  } catch (error) {
25319
25594
  const why = reviewFailure(error);
25320
25595
  const failedAt = now();
@@ -25493,6 +25768,13 @@ function shapeReview(matchId, hero, lang, state) {
25493
25768
  next_game: list(r.next_game),
25494
25769
  ...typeof r.encouragement === "string" && r.encouragement.trim() ? { encouragement: r.encouragement } : {},
25495
25770
  blind_spots: list(r.blind_spots),
25771
+ ...typeof state?.model === "string" && state.model ? { model: state.model } : {},
25772
+ ...Number.isInteger(state?.steps) ? { steps: state.steps } : {},
25773
+ ...Number.isInteger(state?.tool_calls) ? { tool_calls: state.tool_calls } : {},
25774
+ ...Number.isInteger(state?.repair_rounds) ? { repair_rounds: state.repair_rounds } : {},
25775
+ ...Number.isInteger(state?.truncation_retries) ? { truncation_retries: state.truncation_retries } : {},
25776
+ ...state?.usage && typeof state.usage === "object" ? { usage: state.usage } : {},
25777
+ ..."usage_source" in (state ?? {}) ? { usage_source: state.usage_source } : state?.usage && "source" in state.usage ? { usage_source: state.usage.source } : {},
25496
25778
  checked: { against: "replay records", removed_for_lack_of_evidence: state.verification?.dropped ?? 0 },
25497
25779
  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."
25498
25780
  };
@@ -26762,16 +27044,14 @@ function createDshComplete({ ctx, route, primitives = fallbackPrimitives, maxTok
26762
27044
  });
26763
27045
  }
26764
27046
  }
26765
- const u = assembler.usage;
26766
- const inputTokens = (u?.inputTokens ?? 0) + (u?.cacheReadTokens ?? 0) + (u?.cacheWriteTokens ?? 0);
26767
- const outputTokens = u?.outputTokens ?? 0;
27047
+ const usage = parseDshUsage(assembler.usage);
26768
27048
  return {
26769
27049
  text,
26770
27050
  ...reasoning ? { reasoning } : {},
26771
27051
  ...assembler.replayState !== void 0 ? { providerState: assembler.replayState } : {},
26772
27052
  ...finish?.kind === "max-tokens" ? { truncated: true } : {},
26773
27053
  toolCalls,
26774
- usage: { input: inputTokens, output: outputTokens }
27054
+ usage
26775
27055
  };
26776
27056
  };
26777
27057
  }
@@ -27207,7 +27487,7 @@ function createDshService({
27207
27487
  const reply = await complete({ system, messages: rest, tools: [], signal });
27208
27488
  const text = String(reply?.text ?? "").trim();
27209
27489
  if (!text) return { text: fallbackAnswer({ report, slot, lang, question }), fallback: true, notice: FALLBACK_NOTICE[lang] };
27210
- return { text, fallback: false };
27490
+ return { text, fallback: false, ...reply?.usage ? { usage: reply.usage } : {} };
27211
27491
  } catch {
27212
27492
  return { text: fallbackAnswer({ report, slot, lang, question }), fallback: true, notice: FALLBACK_NOTICE[lang] };
27213
27493
  }
@@ -27229,13 +27509,22 @@ function createDshService({
27229
27509
  if (avail.trace && resolvedHero && models.isConfigured()) {
27230
27510
  const out = await agent.chat({ matchId: String(args.match_id), hero: resolvedHero.hero, lang, question, history: [], signal });
27231
27511
  if (out.status === "ok") {
27232
- return { match_id: Number(args.match_id), hero: resolvedHero.hero, lang, answer: out.text, source: "replay", unverified: out.unverified };
27512
+ return {
27513
+ match_id: Number(args.match_id),
27514
+ hero: resolvedHero.hero,
27515
+ lang,
27516
+ answer: out.text,
27517
+ source: "replay",
27518
+ unverified: out.unverified,
27519
+ ...out.usage ? { usage: out.usage } : {},
27520
+ ..."usage_source" in out ? { usage_source: out.usage_source } : {}
27521
+ };
27233
27522
  }
27234
27523
  }
27235
27524
  const report = await fetchCoachReportRemote(args?.match_id, "", signal);
27236
27525
  const seat = findSeat(report, args?.hero);
27237
27526
  const res = await askReportWithHostModel({ report, slot: seat, lang, question, signal });
27238
- return { match_id: report.match.id, seat, lang, answer: res.text, ...res.fallback ? { fallback: true } : {} };
27527
+ return { match_id: report.match.id, seat, lang, answer: res.text, ...res.usage ? { usage: res.usage } : {}, ...res.fallback ? { fallback: true } : {} };
27239
27528
  },
27240
27529
  goal_check: async (args) => {
27241
27530
  let goal = args?.goal;