@omniralph/agent 2.4.0 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -7234,6 +7234,10 @@ function mergeModelUsage(a, b) {
7234
7234
  }
7235
7235
  return [...merged.values()];
7236
7236
  }
7237
+ var CACHE_READ_BUDGET_WEIGHT = 0.1;
7238
+ function budgetTokens(usage) {
7239
+ return usage.inputTokens + usage.cacheCreationInputTokens + usage.outputTokens + Math.ceil(usage.cacheReadInputTokens * CACHE_READ_BUDGET_WEIGHT);
7240
+ }
7237
7241
  function addTokenUsage(a, b) {
7238
7242
  const byModel = a.byModel || b.byModel ? mergeModelUsage(a.byModel ?? [], b.byModel ?? []) : void 0;
7239
7243
  return {
@@ -10064,7 +10068,7 @@ function complexityScore(files, signals) {
10064
10068
  if (fileCount > 20) score += 3;
10065
10069
  else if (fileCount > 10) score += 2;
10066
10070
  else if (fileCount > 5) score += 1;
10067
- const totalChanges = files.reduce((sum2, f) => sum2 + f.additions + f.deletions, 0);
10071
+ const totalChanges = files.reduce((sum, f) => sum + f.additions + f.deletions, 0);
10068
10072
  if (totalChanges > 500) score += 3;
10069
10073
  else if (totalChanges > 200) score += 2;
10070
10074
  else if (totalChanges > 50) score += 1;
@@ -10164,12 +10168,12 @@ function selectFiles(files, profile, options) {
10164
10168
  dropped.set(candidate, "max_files");
10165
10169
  }
10166
10170
  const limit = profile.maxTokensPerReview * BUDGET_FILL_RATIO;
10167
- let total2 = candidates.filter((c) => !dropped.has(c)).reduce((sum2, c) => sum2 + c.tokens, 0);
10171
+ let total = candidates.filter((c) => !dropped.has(c)).reduce((sum, c) => sum + c.tokens, 0);
10168
10172
  for (const candidate of byDropOrder) {
10169
- if (total2 <= limit) break;
10173
+ if (total <= limit) break;
10170
10174
  if (dropped.has(candidate)) continue;
10171
10175
  dropped.set(candidate, "budget");
10172
- total2 -= candidate.tokens;
10176
+ total -= candidate.tokens;
10173
10177
  }
10174
10178
  for (const candidate of byDropOrder) {
10175
10179
  const reason2 = dropped.get(candidate);
@@ -10178,7 +10182,7 @@ function selectFiles(files, profile, options) {
10178
10182
  return {
10179
10183
  included: candidates.filter((c) => !dropped.has(c)),
10180
10184
  skipped,
10181
- estimatedInputTokens: total2,
10185
+ estimatedInputTokens: total,
10182
10186
  complexityScore: scan.complexityScore
10183
10187
  };
10184
10188
  }
@@ -10259,12 +10263,12 @@ function groupFilesByDirectory(files, max = MAX_FILES_PER_CHECK_GROUP) {
10259
10263
  if (current.length > 0) groups.push(current);
10260
10264
  return groups;
10261
10265
  }
10262
- function splitBudget(total2, weights) {
10266
+ function splitBudget(total, weights) {
10263
10267
  if (weights.length === 0) return [];
10264
- const whole = Math.max(0, Math.floor(total2));
10268
+ const whole = Math.max(0, Math.floor(total));
10265
10269
  const positive = weights.map((w) => Math.max(0, w));
10266
- const sum2 = positive.reduce((acc, w) => acc + w, 0);
10267
- const exact = positive.map((w) => sum2 > 0 ? whole * w / sum2 : whole / weights.length);
10270
+ const sum = positive.reduce((acc, w) => acc + w, 0);
10271
+ const exact = positive.map((w) => sum > 0 ? whole * w / sum : whole / weights.length);
10268
10272
  const shares = exact.map((value) => Math.floor(value));
10269
10273
  let rest = whole - shares.reduce((acc, s) => acc + s, 0);
10270
10274
  const byFraction = exact.map((value, index) => ({ index, fraction: value - Math.floor(value) })).sort((a, b) => b.fraction - a.fraction || a.index - b.index);
@@ -10303,7 +10307,7 @@ function planChecks(files, profile, options = {}) {
10303
10307
  const budget = typeBudgets[typeIndex];
10304
10308
  const groupBudgets = splitBudget(
10305
10309
  budget,
10306
- groups.map((group) => group.files.reduce((sum2, file) => sum2 + (tokensOf.get(file) ?? 0), 0))
10310
+ groups.map((group) => group.files.reduce((sum, file) => sum + (tokensOf.get(file) ?? 0), 0))
10307
10311
  );
10308
10312
  return {
10309
10313
  type,
@@ -10349,7 +10353,7 @@ function planCheckPass(files, profile, pass, options = {}) {
10349
10353
  const estimate = options.estimateFileTokens ?? ((file) => estimateTokens(file.patch));
10350
10354
  const budgets = splitBudget(
10351
10355
  profile.maxTokensPerReview,
10352
- groups.map((group) => group.files.reduce((sum2, file) => sum2 + estimate(file), 0))
10356
+ groups.map((group) => group.files.reduce((sum, file) => sum + estimate(file), 0))
10353
10357
  );
10354
10358
  return {
10355
10359
  checks,
@@ -10793,31 +10797,50 @@ function readOnlyPermissions(scope) {
10793
10797
  var UsageTracker = class {
10794
10798
  perMessage = /* @__PURE__ */ new Map();
10795
10799
  floor = { inputTokens: 0, outputTokens: 0 };
10800
+ spentFloor = 0;
10796
10801
  anonymous = 0;
10797
10802
  models = new UsageByModelTracker();
10798
10803
  /** Records a message's usage and returns it (input incl. cache reads/writes). */
10799
10804
  record(id, usage) {
10800
- if (!usage) return { input: 0, output: 0 };
10805
+ if (!usage) return { input: 0, output: 0, budget: 0 };
10801
10806
  const num = (key3) => typeof usage[key3] === "number" ? usage[key3] : 0;
10807
+ const counts = {
10808
+ inputTokens: num("input_tokens"),
10809
+ cacheCreationInputTokens: num("cache_creation_input_tokens"),
10810
+ cacheReadInputTokens: num("cache_read_input_tokens"),
10811
+ outputTokens: num("output_tokens")
10812
+ };
10802
10813
  const next = {
10803
- input: num("input_tokens") + num("cache_creation_input_tokens") + num("cache_read_input_tokens"),
10804
- output: num("output_tokens")
10814
+ input: counts.inputTokens + counts.cacheCreationInputTokens + counts.cacheReadInputTokens,
10815
+ output: counts.outputTokens,
10816
+ budget: budgetTokens(counts)
10805
10817
  };
10806
10818
  const key2 = id ?? `anonymous-${this.anonymous++}`;
10807
10819
  const prev = this.perMessage.get(key2);
10808
10820
  const merged = {
10809
10821
  input: Math.max(prev?.input ?? 0, next.input),
10810
- output: Math.max(prev?.output ?? 0, next.output)
10822
+ output: Math.max(prev?.output ?? 0, next.output),
10823
+ budget: Math.max(prev?.budget ?? 0, next.budget)
10811
10824
  };
10812
10825
  this.perMessage.set(key2, merged);
10813
10826
  return merged;
10814
10827
  }
10815
- /** Result messages carry run totals (`modelUsage`); never report less than those. */
10816
- recordRunTotal(base, total2) {
10828
+ /**
10829
+ * Result messages carry run totals (`modelUsage`, and `spent` of them against the budget,
10830
+ * after `baseSpent` of the earlier runs); never report less than those.
10831
+ */
10832
+ recordRunTotal(base, total, baseSpent, spent) {
10817
10833
  this.floor = {
10818
- inputTokens: Math.max(this.floor.inputTokens, base.inputTokens + total2.inputTokens),
10819
- outputTokens: Math.max(this.floor.outputTokens, base.outputTokens + total2.outputTokens)
10834
+ inputTokens: Math.max(this.floor.inputTokens, base.inputTokens + total.inputTokens),
10835
+ outputTokens: Math.max(this.floor.outputTokens, base.outputTokens + total.outputTokens)
10820
10836
  };
10837
+ this.spentFloor = Math.max(this.spentFloor, baseSpent + spent);
10838
+ }
10839
+ /** What the runs so far spent of the token budget (`budgetTokens`). */
10840
+ get spent() {
10841
+ let spent = 0;
10842
+ for (const usage of this.perMessage.values()) spent += usage.budget;
10843
+ return Math.max(spent, this.spentFloor);
10821
10844
  }
10822
10845
  get total() {
10823
10846
  let input = 0;
@@ -10834,9 +10857,6 @@ var UsageTracker = class {
10834
10857
  };
10835
10858
  }
10836
10859
  };
10837
- function sum(usage) {
10838
- return usage.inputTokens + usage.outputTokens;
10839
- }
10840
10860
  function realpathOrResolve(path27) {
10841
10861
  try {
10842
10862
  return realpathSync(path27);
@@ -10964,7 +10984,7 @@ var ClaudeAgentProvider = class {
10964
10984
  { taskId: request.task.id, error: parsed.error },
10965
10985
  "Invalid review output; asking for a repair"
10966
10986
  );
10967
- if (sum(usage.total) >= budget) {
10987
+ if (usage.spent >= budget) {
10968
10988
  return finish(
10969
10989
  "budget_exhausted",
10970
10990
  this.dropInvalid(request, first.text, parsed.items, discarded)
@@ -11165,6 +11185,7 @@ var ClaudeAgentProvider = class {
11165
11185
  request.systemPrompt
11166
11186
  );
11167
11187
  const base = usage.total;
11188
+ const baseSpent = usage.spent;
11168
11189
  usage.models.startQuery();
11169
11190
  let streamed = "";
11170
11191
  let rateLimitRejected = false;
@@ -11194,11 +11215,17 @@ var ClaudeAgentProvider = class {
11194
11215
  retryAfterMs
11195
11216
  };
11196
11217
  }
11197
- const nextTurn = turn.input + turn.output;
11198
- if (message.parent_tool_use_id === null && msg.content?.some((block) => block.type === "tool_use") && sum(usage.total) + nextTurn > budget) {
11218
+ const nextTurn = turn.budget;
11219
+ if (message.parent_tool_use_id === null && msg.content?.some((block) => block.type === "tool_use") && usage.spent + nextTurn > budget) {
11199
11220
  controller.abort();
11200
11221
  this.logger.warn(
11201
- { taskId: request.taskId, budget, usage: usage.total, nextTurn },
11222
+ {
11223
+ taskId: request.taskId,
11224
+ budget,
11225
+ spent: usage.spent,
11226
+ usage: usage.total,
11227
+ nextTurn
11228
+ },
11202
11229
  "Review token budget exhausted: the next turn would exceed it; aborting"
11203
11230
  );
11204
11231
  return { stop: "budget_exhausted", text: streamed };
@@ -11225,7 +11252,11 @@ var ClaudeAgentProvider = class {
11225
11252
  }),
11226
11253
  { inputTokens: 0, outputTokens: 0 }
11227
11254
  );
11228
- usage.recordRunTotal(base, totals);
11255
+ const spent = Object.values(message.modelUsage ?? {}).reduce(
11256
+ (acc, m) => acc + budgetTokens(m),
11257
+ 0
11258
+ );
11259
+ usage.recordRunTotal(base, totals, baseSpent, spent);
11229
11260
  usage.models.recordResult(message);
11230
11261
  if (message.subtype === "success" && !message.is_error) {
11231
11262
  return { stop: "completed", text: message.result };
@@ -11241,10 +11272,10 @@ var ClaudeAgentProvider = class {
11241
11272
  default:
11242
11273
  break;
11243
11274
  }
11244
- if (sum(usage.total) >= budget) {
11275
+ if (usage.spent >= budget) {
11245
11276
  controller.abort();
11246
11277
  this.logger.warn(
11247
- { taskId: request.taskId, budget, usage: usage.total },
11278
+ { taskId: request.taskId, budget, spent: usage.spent, usage: usage.total },
11248
11279
  "Review token budget exhausted; aborting"
11249
11280
  );
11250
11281
  return { stop: "budget_exhausted", text: streamed };
@@ -11938,6 +11969,11 @@ var BACKGROUND_WAIT_TIMEOUT_MS = 60 * 6e4;
11938
11969
  var WAIT_NUDGE_DELAY_MS = 3e4;
11939
11970
  var WAIT_NUDGE_TEXT = "Nothing is running in the background any more, so there is nothing left to wait for. Check the results of the background work you started, finish the task, and report your structured result.";
11940
11971
  var RATE_LIMIT_TEXT2 = /rate[_ ]limit|usage limit|\b429\b|too many requests/i;
11972
+ var STRUCTURED_OUTPUT_TOOL = "StructuredOutput";
11973
+ var BUDGET_WRAP_UP_SHARE = 0.25;
11974
+ var BUDGET_WRAP_UP_TURNS = 2;
11975
+ var BUDGET_WRAP_UP_TEXT = "Your token budget for this task is spent, so no more tools will run. Stop exploring and report your structured result now from what you have already read; where you couldn't check something, say so in your result instead of guessing.";
11976
+ var BUDGET_SPENT_TOOL_TEXT = "The token budget for this task is spent, so no more tools run. Report your result now from what you have.";
11941
11977
  var PERMISSION_DENIED_TEXT = "A person had to approve this in the tracker (the repository's Claude Code settings ask about it) and denied it or didn't answer in time. Don't retry it: carry on without it, or report what it blocks.";
11942
11978
  function sessionEvents(message) {
11943
11979
  if (message.type !== "assistant" || message.parent_tool_use_id !== null) return [];
@@ -12091,12 +12127,28 @@ function startsTurn(message) {
12091
12127
  function messageUsage(message) {
12092
12128
  const raw = message.message.usage ?? {};
12093
12129
  const num = (key2) => typeof raw[key2] === "number" ? raw[key2] : 0;
12094
- return {
12095
- inputTokens: num("input_tokens") + num("cache_creation_input_tokens") + num("cache_read_input_tokens"),
12130
+ const counts = {
12131
+ inputTokens: num("input_tokens"),
12132
+ cacheCreationInputTokens: num("cache_creation_input_tokens"),
12133
+ cacheReadInputTokens: num("cache_read_input_tokens"),
12096
12134
  outputTokens: num("output_tokens")
12097
12135
  };
12136
+ return {
12137
+ inputTokens: counts.inputTokens + counts.cacheCreationInputTokens + counts.cacheReadInputTokens,
12138
+ outputTokens: counts.outputTokens,
12139
+ budget: budgetTokens(counts)
12140
+ };
12141
+ }
12142
+ function workToolCalls(message) {
12143
+ return (message.message.content ?? []).filter(
12144
+ (block) => block.type === "tool_use" && block.name !== STRUCTURED_OUTPUT_TOOL
12145
+ ).length;
12146
+ }
12147
+ function reportsResult(message) {
12148
+ return (message.message.content ?? []).some(
12149
+ (block) => block.type === "tool_use" && block.name === STRUCTURED_OUTPUT_TOOL
12150
+ );
12098
12151
  }
12099
- var total = (usage) => usage.inputTokens + usage.outputTokens;
12100
12152
  async function runQuery(query, request, seen) {
12101
12153
  const controller = new AbortController();
12102
12154
  const onAbort = () => controller.abort(request.signal.reason);
@@ -12130,6 +12182,7 @@ async function runQuery(query, request, seen) {
12130
12182
  const id = randomUUID2();
12131
12183
  outstanding.add(id);
12132
12184
  input.push(userMessage(text3, id, priority));
12185
+ return id;
12133
12186
  };
12134
12187
  let injectionTimer;
12135
12188
  const finishInput = () => {
@@ -12188,25 +12241,49 @@ async function runQuery(query, request, seen) {
12188
12241
  clearTimeout(nudgeTimer);
12189
12242
  };
12190
12243
  const perMessage = /* @__PURE__ */ new Map();
12244
+ let spent = 0;
12245
+ const messageKey = (message) => message.message.id ?? message.uuid;
12191
12246
  const recordUsage = (message) => {
12192
12247
  const next = messageUsage(message);
12193
- const key2 = message.message.id ?? message.uuid;
12248
+ const key2 = messageKey(message);
12194
12249
  const prev = perMessage.get(key2);
12195
12250
  const merged = {
12196
12251
  inputTokens: Math.max(prev?.inputTokens ?? 0, next.inputTokens),
12197
- outputTokens: Math.max(prev?.outputTokens ?? 0, next.outputTokens)
12252
+ outputTokens: Math.max(prev?.outputTokens ?? 0, next.outputTokens),
12253
+ budget: Math.max(prev?.budget ?? 0, next.budget)
12198
12254
  };
12199
12255
  perMessage.set(key2, merged);
12200
12256
  let inputTokens = 0;
12201
12257
  let outputTokens = 0;
12258
+ let budget2 = 0;
12202
12259
  for (const u of perMessage.values()) {
12203
12260
  inputTokens += u.inputTokens;
12204
12261
  outputTokens += u.outputTokens;
12262
+ budget2 += u.budget;
12205
12263
  }
12206
12264
  usage.inputTokens = Math.max(usage.inputTokens, inputTokens);
12207
12265
  usage.outputTokens = Math.max(usage.outputTokens, outputTokens);
12266
+ spent = Math.max(spent, budget2);
12208
12267
  return merged;
12209
12268
  };
12269
+ const budget = request.tokenBudget;
12270
+ let wrapUp;
12271
+ const startWrapUp = (askForResult) => {
12272
+ if (wrapUp || budget === void 0) return;
12273
+ wrapUp = { ceiling: Math.max(spent, budget) + budget * BUDGET_WRAP_UP_SHARE, turns: /* @__PURE__ */ new Set() };
12274
+ if (askForResult) wrapUp.messageId = send(BUDGET_WRAP_UP_TEXT, "next");
12275
+ };
12276
+ const budgetGuard = async (input2) => {
12277
+ const tool2 = input2.tool_name;
12278
+ if (!wrapUp || tool2 === STRUCTURED_OUTPUT_TOOL) return {};
12279
+ return {
12280
+ hookSpecificOutput: {
12281
+ hookEventName: "PreToolUse",
12282
+ permissionDecision: "deny",
12283
+ permissionDecisionReason: BUDGET_SPENT_TOOL_TEXT
12284
+ }
12285
+ };
12286
+ };
12210
12287
  const texts = [];
12211
12288
  const last = () => texts.at(-1) ?? "";
12212
12289
  let rateLimited = false;
@@ -12250,10 +12327,14 @@ async function runQuery(query, request, seen) {
12250
12327
  } : void 0;
12251
12328
  resetIdle();
12252
12329
  try {
12253
- const messages = query({
12254
- prompt: input,
12255
- options: sessionOptions(request, controller, canUseTool)
12256
- });
12330
+ const options = sessionOptions(request, controller, canUseTool);
12331
+ if (budget !== void 0) {
12332
+ options.hooks = {
12333
+ ...options.hooks,
12334
+ PreToolUse: [...options.hooks?.PreToolUse ?? [], { hooks: [budgetGuard] }]
12335
+ };
12336
+ }
12337
+ const messages = query({ prompt: input, options });
12257
12338
  for await (const message of messages) {
12258
12339
  if (message.type === "system" && message.subtype === "background_tasks_changed") {
12259
12340
  live.clear();
@@ -12299,6 +12380,10 @@ async function runQuery(query, request, seen) {
12299
12380
  models.recordResult(message);
12300
12381
  usage.inputTokens = Math.max(usage.inputTokens, final.inputTokens);
12301
12382
  usage.outputTokens = Math.max(usage.outputTokens, final.outputTokens);
12383
+ spent = Math.max(
12384
+ spent,
12385
+ Object.values(message.modelUsage ?? {}).reduce((acc, m) => acc + budgetTokens(m), 0)
12386
+ );
12302
12387
  if (message.subtype === "success" && !message.is_error) {
12303
12388
  const result = {
12304
12389
  stop: "completed",
@@ -12308,6 +12393,7 @@ async function runQuery(query, request, seen) {
12308
12393
  };
12309
12394
  const ids = message.user_message_uuids ?? (message.user_message_uuid ? [message.user_message_uuid] : [...outstanding]);
12310
12395
  for (const id of ids) outstanding.delete(id);
12396
+ if (wrapUp?.messageId) outstanding.delete(wrapUp.messageId);
12311
12397
  const waits = request.isWaiting?.(message.structured_output) === true;
12312
12398
  if (!waits && outstanding.size === 0) return result;
12313
12399
  answered = result;
@@ -12331,10 +12417,14 @@ async function runQuery(query, request, seen) {
12331
12417
  default:
12332
12418
  break;
12333
12419
  }
12334
- const budget = request.tokenBudget;
12335
12420
  if (budget !== void 0 && turn && message.type === "assistant") {
12336
- const callsTool = message.parent_tool_use_id === null && (message.message.content ?? []).some((block) => block.type === "tool_use");
12337
- if (total(usage) >= budget || callsTool && total(usage) + total(turn) > budget) {
12421
+ const calls = workToolCalls(message);
12422
+ if (!wrapUp && (spent >= budget || calls > 0 && spent + turn.budget > budget)) {
12423
+ startWrapUp(calls > 0);
12424
+ } else if (wrapUp && message.parent_tool_use_id === null && !reportsResult(message)) {
12425
+ wrapUp.turns.add(messageKey(message));
12426
+ }
12427
+ if (wrapUp && calls > 0 && (spent > wrapUp.ceiling || wrapUp.turns.size > BUDGET_WRAP_UP_TURNS)) {
12338
12428
  controller.abort(new Error("the token budget is exhausted"));
12339
12429
  return { stop: "budget_exhausted", output: last(), usage };
12340
12430
  }
@@ -13808,9 +13898,9 @@ function formatAttachments(entries) {
13808
13898
  return e.path ? `- ${name} ${from}: \`${e.path}\`` : `- ${name} ${from}: could not be downloaded (${e.error ?? "unknown error"}). Don't guess what it shows; say so if it matters.`;
13809
13899
  }).join("\n");
13810
13900
  }
13811
- function failedAttachmentsNote(failed, total2) {
13901
+ function failedAttachmentsNote(failed, total) {
13812
13902
  if (failed.length === 0) return void 0;
13813
- return `I couldn't download ${failed.length} of ${total2} attachment(s) from the tracker, so I can't see them:
13903
+ return `I couldn't download ${failed.length} of ${total} attachment(s) from the tracker, so I can't see them:
13814
13904
 
13815
13905
  ${failed.map(
13816
13906
  (e) => `- ${e.title ?? "attachment"} (${e.sources.join(", ")}): ${e.error ?? "unknown error"}`
@@ -14737,10 +14827,10 @@ var DOWNLOAD_TIMEOUT_MS = 12e4;
14737
14827
  async function readCapped(res, max) {
14738
14828
  if (!res.body) return Buffer.alloc(0);
14739
14829
  const chunks = [];
14740
- let total2 = 0;
14830
+ let total = 0;
14741
14831
  for await (const chunk of res.body) {
14742
- total2 += chunk.byteLength;
14743
- if (total2 > max) {
14832
+ total += chunk.byteLength;
14833
+ if (total > max) {
14744
14834
  await res.body.cancel().catch(() => void 0);
14745
14835
  return `larger than ${max / 1024 / 1024} MB`;
14746
14836
  }
@@ -15409,10 +15499,10 @@ function labelOf(attachment) {
15409
15499
  async function readBody(res, max) {
15410
15500
  if (!res.body) return Buffer.alloc(0);
15411
15501
  const chunks = [];
15412
- let total2 = 0;
15502
+ let total = 0;
15413
15503
  for await (const chunk of res.body) {
15414
- total2 += chunk.byteLength;
15415
- if (total2 > max) {
15504
+ total += chunk.byteLength;
15505
+ if (total > max) {
15416
15506
  await res.body.cancel().catch(() => void 0);
15417
15507
  return `it is larger than ${max / 1024 / 1024} MB`;
15418
15508
  }