@dudko.dev/agent-web 0.0.31 → 0.0.32

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/index.cjs CHANGED
@@ -36,12 +36,16 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
36
36
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
37
 
38
38
  // src/llm/util.ts
39
- var clip, promptOf, normalizeUsage, timeoutSignal;
39
+ var clip, promptOf, usageOfError, normalizeUsage, timeoutSignal;
40
40
  var init_util = __esm({
41
41
  "src/llm/util.ts"() {
42
42
  "use strict";
43
43
  clip = (s, max) => s.length > max ? `${s.slice(0, max - 1)}\u2026` : s;
44
44
  promptOf = (opts) => opts.messages ? { messages: opts.messages } : { prompt: opts.prompt ?? "" };
45
+ usageOfError = (err) => {
46
+ const u = err?.usage;
47
+ return normalizeUsage(u && typeof u === "object" ? u : void 0);
48
+ };
45
49
  normalizeUsage = (u) => {
46
50
  const inputTokens = u?.inputTokens ?? 0;
47
51
  const outputTokens = u?.outputTokens ?? 0;
@@ -100,18 +104,22 @@ var init_generate = __esm({
100
104
  });
101
105
 
102
106
  // src/memory/compress.ts
103
- var resolveCompaction, estimateTokens, messageTokens, SUMMARY_SYSTEM, compressHistory, compactHistory, TRACE_SYSTEM, compactSteps;
107
+ var DEFAULT_COMPACTION_THRESHOLD_RATIO, ratioOf, resolveCompaction, isWide, estimateTokens, messageTokens, newestWithin, SUMMARY_SYSTEM, compressHistory, compactHistory, TRACE_SYSTEM, compactSteps;
104
108
  var init_compress = __esm({
105
109
  "src/memory/compress.ts"() {
106
110
  "use strict";
107
111
  init_generate();
108
112
  init_util();
113
+ DEFAULT_COMPACTION_THRESHOLD_RATIO = 0.85;
114
+ ratioOf = (r) => typeof r === "number" && r > 0 && r <= 1 ? r : DEFAULT_COMPACTION_THRESHOLD_RATIO;
109
115
  resolveCompaction = (c) => {
110
116
  const contextWindowTokens = c?.contextWindowTokens ?? 128e3;
117
+ const thresholdRatio = ratioOf(c?.thresholdRatio);
111
118
  return {
112
119
  auto: c?.auto ?? true,
113
120
  contextWindowTokens,
114
- thresholdTokens: c?.thresholdTokens ?? Math.floor(contextWindowTokens / 2),
121
+ thresholdTokens: c?.thresholdTokens ?? Math.floor(contextWindowTokens * thresholdRatio),
122
+ thresholdRatio,
115
123
  keepRecentTurns: c?.keepRecentTurns ?? 4,
116
124
  keepRecentSteps: c?.keepRecentSteps ?? 3,
117
125
  summaryMaxTokens: c?.summaryMaxTokens ?? 1024,
@@ -120,9 +128,48 @@ var init_compress = __esm({
120
128
  keepToolResults: c?.keepToolResults ?? 3
121
129
  };
122
130
  };
123
- estimateTokens = (text) => Math.ceil((text ?? "").length / 4);
131
+ isWide = (c) => c >= 12352 && c <= 40959 || c >= 44032 && c <= 55215 || c >= 55296 && c <= 57343;
132
+ estimateTokens = (text) => {
133
+ const s = text ?? "";
134
+ let letters = 0;
135
+ let digits = 0;
136
+ let spaces = 0;
137
+ let newlines = 0;
138
+ let punct = 0;
139
+ let other = 0;
140
+ let wide = 0;
141
+ for (let i = 0; i < s.length; i += 1) {
142
+ const c = s.charCodeAt(i);
143
+ if (c < 128) {
144
+ if (c >= 97 && c <= 122 || c >= 65 && c <= 90) letters += 1;
145
+ else if (c >= 48 && c <= 57) digits += 1;
146
+ else if (c === 32 || c === 9) spaces += 1;
147
+ else if (c === 10) newlines += 1;
148
+ else punct += 1;
149
+ } else if (isWide(c)) wide += 1;
150
+ else other += 1;
151
+ }
152
+ return Math.ceil(
153
+ (440 * letters + 1100 * digits + 1210 * punct + 275 * spaces + 1100 * newlines + 550 * other + 1100 * wide) / 1e3
154
+ );
155
+ };
124
156
  messageTokens = (msgs) => msgs.reduce((n, m) => n + estimateTokens(`${m.role}: ${m.content}
125
157
  `), 0);
158
+ newestWithin = (lines, maxTokens) => {
159
+ if (maxTokens === void 0) return lines.join("\n").slice(-48e3);
160
+ const kept = [];
161
+ let used = 0;
162
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
163
+ const t = estimateTokens(lines[i]) + 1;
164
+ if (used + t > maxTokens) {
165
+ if (kept.length === 0) kept.push(lines[i].slice(-Math.max(1, maxTokens) * 2));
166
+ break;
167
+ }
168
+ kept.unshift(lines[i]);
169
+ used += t;
170
+ }
171
+ return kept.join("\n");
172
+ };
126
173
  SUMMARY_SYSTEM = "Summarize the following conversation into a compact set of durable facts, decisions, identifiers, open tasks and user preferences. Keep names, numbers and IDs verbatim. Output plain text only.";
127
174
  compressHistory = async (messages, model, opts = {}) => {
128
175
  const keepRecent = opts.keepRecent ?? 6;
@@ -140,7 +187,10 @@ var init_compress = __esm({
140
187
  }
141
188
  const head = messages.slice(0, messages.length - keepRecent);
142
189
  const tail = messages.slice(messages.length - keepRecent);
143
- const transcript = head.map((m) => `${m.role}: ${m.content}`).join("\n").slice(-48e3);
190
+ const transcript = newestWithin(
191
+ head.map((m) => `${m.role}: ${m.content}`),
192
+ opts.maxInputTokens
193
+ );
144
194
  try {
145
195
  const result = await generate(model, {
146
196
  system: SUMMARY_SYSTEM,
@@ -173,7 +223,10 @@ ${clean}`,
173
223
  try {
174
224
  const result = await generate(model, {
175
225
  system: TRACE_SYSTEM,
176
- prompt: head.map((d, i) => `${i + 1}. ${d}`).join("\n"),
226
+ prompt: newestWithin(
227
+ head.map((d, i) => `${i + 1}. ${d}`),
228
+ opts.maxInputTokens ?? 1e9
229
+ ),
177
230
  maxOutputTokens: opts.summaryMaxTokens ?? 600,
178
231
  timeoutMs: opts.timeoutMs,
179
232
  abortSignal: opts.abortSignal
@@ -279,7 +332,7 @@ var init_images = __esm({
279
332
  });
280
333
 
281
334
  // src/context-window.ts
282
- var import_ai2, WEBLLM_DEFAULT_CONTEXT_WINDOW, withWebLLMContextWindow, webLLMContextWindow, contextWindowOf, fitCompactionToWindow, toolDefinitionTokens, TOOL_SEARCH_WINDOW_SHARE, ContextWindowExceededError, OVERFLOW_RE, WEBLLM_SIZES_RE, contextOverflowOf;
335
+ var import_ai2, WEBLLM_DEFAULT_CONTEXT_WINDOW, withWebLLMContextWindow, webLLMContextWindow, contextWindowOf, fitCompactionToWindow, toolDefinitionTokens, BASE_PROMPT_TOKENS, SEARCH_TOOLS_ALLOWANCE, promptOverheadTokens, TOOL_SEARCH_WINDOW_SHARE, ContextWindowExceededError, OVERFLOW_RE, WEBLLM_SIZES_RE, contextOverflowOf;
283
336
  var init_context_window = __esm({
284
337
  "src/context-window.ts"() {
285
338
  "use strict";
@@ -329,13 +382,17 @@ var init_context_window = __esm({
329
382
  modelWindow ?? Infinity
330
383
  );
331
384
  if (window === resolved.contextWindowTokens && modelWindow === void 0) return resolved;
332
- const half = Math.floor(window / 2);
333
385
  const quarter = Math.floor(window / 4);
334
386
  const clearAfter = configured?.clearToolResultsAfterTokens;
335
387
  return {
336
388
  ...resolved,
337
389
  contextWindowTokens: window,
338
- thresholdTokens: Math.min(configured?.thresholdTokens ?? half, half),
390
+ // A threshold the host set for a larger window comes down with the window: never past 95%
391
+ // of what the model really has (the answer and a step's growth need the rest).
392
+ thresholdTokens: Math.min(
393
+ configured?.thresholdTokens ?? Math.floor(window * resolved.thresholdRatio),
394
+ Math.floor(window * 0.95)
395
+ ),
339
396
  // 0 = never stays never.
340
397
  clearToolResultsAfterTokens: clearAfter === 0 ? 0 : Math.min(clearAfter ?? quarter, quarter),
341
398
  // One result may take a quarter of the window (~4 chars per token).
@@ -358,6 +415,9 @@ var init_context_window = __esm({
358
415
  );
359
416
  return sizes.reduce((a, b) => a + b, 0);
360
417
  };
418
+ BASE_PROMPT_TOKENS = 1500;
419
+ SEARCH_TOOLS_ALLOWANCE = 3e3;
420
+ promptOverheadTokens = (p) => BASE_PROMPT_TOKENS + estimateTokens(p.systemPrompt ?? "") + (p.searching ? Math.min(p.toolTokens, SEARCH_TOOLS_ALLOWANCE) : p.toolTokens) + estimateTokens(p.skillsText);
361
421
  TOOL_SEARCH_WINDOW_SHARE = 0.25;
362
422
  ContextWindowExceededError = class extends Error {
363
423
  /** The prompt's size as the provider counted it, when it said. */
@@ -465,6 +525,7 @@ var src_exports = {};
465
525
  __export(src_exports, {
466
526
  AttachmentsNotSupportedError: () => AttachmentsNotSupportedError,
467
527
  ContextWindowExceededError: () => ContextWindowExceededError,
528
+ DEFAULT_COMPACTION_THRESHOLD_RATIO: () => DEFAULT_COMPACTION_THRESHOLD_RATIO,
468
529
  EgressError: () => EgressError,
469
530
  FILES_STORE: () => FILES_STORE,
470
531
  FIND_TOOLS_NAME: () => FIND_TOOLS_NAME,
@@ -572,6 +633,7 @@ __export(src_exports, {
572
633
  renderSearchCatalog: () => renderSearchCatalog,
573
634
  renderSkillIndex: () => renderSkillIndex,
574
635
  replanWanted: () => replanWanted,
636
+ resolveBudgets: () => resolveBudgets,
575
637
  resolveCaching: () => resolveCaching,
576
638
  resolveCompaction: () => resolveCompaction,
577
639
  resolveConfig: () => resolveConfig,
@@ -653,6 +715,22 @@ var withRollingBreakpoint = (messages, caching) => {
653
715
 
654
716
  // src/config.ts
655
717
  init_compress();
718
+ var BUDGET_SHARES = {
719
+ planner: { num: 1, den: 160, min: 256, max: 2e3 },
720
+ executor: { num: 3, den: 320, min: 384, max: 8192 },
721
+ replanner: { num: 1, den: 320, min: 192, max: 1500 },
722
+ synthesizer: { num: 3, den: 128, min: 512, max: 8192 },
723
+ compaction: { num: 1, den: 125, min: 256, max: 4096 }
724
+ };
725
+ var share = (window, s) => Math.min(s.max, Math.max(s.min, Math.round(window * s.num / s.den)));
726
+ var resolveBudgets = (c, contextWindowTokens) => ({
727
+ planner: c.limits?.perCall?.planner ?? c.budgets?.planner ?? share(contextWindowTokens, BUDGET_SHARES.planner),
728
+ executor: c.limits?.perCall?.executor ?? c.budgets?.executor ?? share(contextWindowTokens, BUDGET_SHARES.executor),
729
+ replanner: c.limits?.perCall?.replanner ?? c.budgets?.replanner ?? share(contextWindowTokens, BUDGET_SHARES.replanner),
730
+ // The final answer is the one call whose text the user reads: 400 cut a normal answer short.
731
+ synthesizer: c.limits?.perCall?.synthesizer ?? c.budgets?.synthesizer ?? share(contextWindowTokens, BUDGET_SHARES.synthesizer),
732
+ compaction: c.limits?.perCall?.compaction ?? c.compaction?.summaryMaxTokens ?? share(contextWindowTokens, BUDGET_SHARES.compaction)
733
+ });
656
734
  var resolveConfig = (c) => ({
657
735
  clientName: c.clientName ?? "agent-web",
658
736
  sessionId: c.sessionId ?? "default",
@@ -665,14 +743,7 @@ var resolveConfig = (c) => ({
665
743
  maxToolCalls: c.maxToolCalls ?? 0,
666
744
  maxPlanSteps: c.maxPlanSteps ?? 8,
667
745
  chatTimeoutMs: c.chatTimeoutMs ?? 12e4,
668
- budgets: {
669
- planner: c.limits?.perCall?.planner ?? c.budgets?.planner ?? 800,
670
- executor: c.limits?.perCall?.executor ?? c.budgets?.executor ?? 1200,
671
- replanner: c.limits?.perCall?.replanner ?? c.budgets?.replanner ?? 400,
672
- // The final answer is the one call whose text the user reads: 400 cut a normal answer short.
673
- synthesizer: c.limits?.perCall?.synthesizer ?? c.budgets?.synthesizer ?? 3e3,
674
- compaction: c.limits?.perCall?.compaction ?? c.compaction?.summaryMaxTokens ?? 1024
675
- },
746
+ budgets: resolveBudgets(c, resolveCompaction(c.compaction).contextWindowTokens),
676
747
  limits: c.limits ?? {},
677
748
  temperature: c.temperature,
678
749
  replan: c.replan ?? true,
@@ -3238,6 +3309,7 @@ ${nudge}` : goal;
3238
3309
  }
3239
3310
  return kept;
3240
3311
  };
3312
+ let wasted = normalizeUsage();
3241
3313
  if (ctx.plannerMode === "native") {
3242
3314
  try {
3243
3315
  const result2 = await generateStructured(ctx.plannerModel, PlanSchema, commonFor("native"));
@@ -3253,6 +3325,7 @@ ${nudge}` : goal;
3253
3325
  if (refused) throw refused;
3254
3326
  const overflow = contextOverflowOf(err, ctx.plannerModel);
3255
3327
  if (overflow) throw overflow;
3328
+ wasted = usageOfError(err);
3256
3329
  ctx.log.warn("planner: native structured output failed, salvaging:", asMessage(err));
3257
3330
  ctx.emit({ type: "retry", phase: "plan", attempt: 1, error: asMessage(err) });
3258
3331
  }
@@ -3271,7 +3344,7 @@ ${nudge}` : goal;
3271
3344
  cap
3272
3345
  )
3273
3346
  },
3274
- usage: normalizeUsage(result.usage),
3347
+ usage: addUsage(wasted, normalizeUsage(result.usage)),
3275
3348
  skills: validSkills(parsed.skills)
3276
3349
  };
3277
3350
  };
@@ -3303,6 +3376,7 @@ var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
3303
3376
  timeoutMs: ctx.config.chatTimeoutMs
3304
3377
  };
3305
3378
  };
3379
+ let wasted = normalizeUsage();
3306
3380
  if (ctx.plannerMode === "native") {
3307
3381
  try {
3308
3382
  const result = await generateStructured(ctx.plannerModel, ReplanSchema, commonFor("native"));
@@ -3312,7 +3386,8 @@ var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
3312
3386
  plan: result.object.plan ?? [],
3313
3387
  usage: normalizeUsage(result.usage)
3314
3388
  };
3315
- } catch {
3389
+ } catch (err) {
3390
+ wasted = usageOfError(err);
3316
3391
  }
3317
3392
  }
3318
3393
  try {
@@ -3322,10 +3397,10 @@ var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
3322
3397
  decision: parsed.decision,
3323
3398
  reason: parsed.reason,
3324
3399
  plan: parsed.plan,
3325
- usage: normalizeUsage(result.usage)
3400
+ usage: addUsage(wasted, normalizeUsage(result.usage))
3326
3401
  };
3327
3402
  } catch {
3328
- return { decision: "continue", reason: "replanner unavailable", plan: [], usage: emptyUsage() };
3403
+ return { decision: "continue", reason: "replanner unavailable", plan: [], usage: wasted };
3329
3404
  }
3330
3405
  };
3331
3406
 
@@ -3487,6 +3562,7 @@ var createAgent = async (config) => {
3487
3562
  const modelWindows = [executorModel, plannerModel, synthesizerModel].map(contextWindowOf).filter((w) => w !== void 0);
3488
3563
  const modelWindow = modelWindows.length ? Math.min(...modelWindows) : void 0;
3489
3564
  cfg.compaction = fitCompactionToWindow(cfg.compaction, config.compaction, modelWindow);
3565
+ cfg.budgets = resolveBudgets(config, cfg.compaction.contextWindowTokens);
3490
3566
  const byTokens = Boolean(config.compaction) || modelWindow !== void 0;
3491
3567
  const log = createLogger(cfg.logLevel, config.logger);
3492
3568
  const skills = (config.skills ?? []).map(defineSkill);
@@ -3509,7 +3585,8 @@ var createAgent = async (config) => {
3509
3585
  config.excludedTools
3510
3586
  );
3511
3587
  const catalog = toolCatalogOf(baseTools);
3512
- const toolTokens = cfg.toolSelectionStrategy === "auto" ? await toolDefinitionTokens(baseTools) : 0;
3588
+ const toolDefTokens = await toolDefinitionTokens(baseTools);
3589
+ const toolTokens = cfg.toolSelectionStrategy === "auto" ? toolDefTokens : 0;
3513
3590
  const strategy = cfg.toolSelectionStrategy === "auto" ? catalog.length > cfg.toolSearchThreshold || toolTokens > cfg.compaction.contextWindowTokens * TOOL_SEARCH_WINDOW_SHARE ? "search" : "all" : cfg.toolSelectionStrategy;
3514
3591
  const reserved = [
3515
3592
  ...skills.length || learning ? SKILL_TOOL_NAMES : [],
@@ -3523,6 +3600,14 @@ var createAgent = async (config) => {
3523
3600
  }
3524
3601
  }
3525
3602
  const builtinTools = new Set(reserved);
3603
+ const fixedPromptTokens = (active) => promptOverheadTokens({
3604
+ systemPrompt: config.systemPrompt,
3605
+ toolTokens: toolDefTokens,
3606
+ searching: strategy === "search",
3607
+ skillsText: `${renderSkillIndex(skills)}
3608
+ ${renderActiveSkills(active)}`
3609
+ });
3610
+ const summaryInputTokens = Math.floor(cfg.compaction.contextWindowTokens * 0.6);
3526
3611
  const hints = /* @__PURE__ */ new Map();
3527
3612
  await Promise.all(
3528
3613
  Object.entries(baseTools).map(async ([name, t]) => {
@@ -3545,6 +3630,12 @@ var createAgent = async (config) => {
3545
3630
  log.info(
3546
3631
  `agent ready \u2014 ${catalog.length} tool(s) (${strategy}, ~${toolTokens || "?"} tokens), window ${cfg.compaction.contextWindowTokens}${modelWindow ? " (the model\u2019s)" : ""}, skills: [${skills.map((s) => s.name).join(", ") || "none"}], planner mode: ${plannerMode}, executor mode: ${executorMode}, approval: ${approval.mode}`
3547
3632
  );
3633
+ let spentAll = emptyUsage();
3634
+ const spentBySession = /* @__PURE__ */ new Map();
3635
+ const charge = (sessionId, u) => {
3636
+ spentAll = addUsage(spentAll, u);
3637
+ spentBySession.set(sessionId, addUsage(spentBySession.get(sessionId) ?? emptyUsage(), u));
3638
+ };
3548
3639
  const runCore = async (goal, opts, track, port) => {
3549
3640
  const resumed = await resolveResume(config.persistence, opts.resumeFromRunId);
3550
3641
  const emit = (event) => {
@@ -3575,6 +3666,7 @@ var createAgent = async (config) => {
3575
3666
  const isAborted = () => opts.signal?.aborted === true;
3576
3667
  const bumpUsage = (u, phase) => {
3577
3668
  usage = addUsage(usage, u);
3669
+ charge(sessionId, u);
3578
3670
  result.usage = usage;
3579
3671
  emit({ type: "usage", phase, usage: u });
3580
3672
  };
@@ -3690,11 +3782,13 @@ var createAgent = async (config) => {
3690
3782
  }
3691
3783
  if (config.memory && byTokens && cfg.compaction.auto && history.length > 0) {
3692
3784
  const before = messageTokens(history);
3693
- if (before > cfg.compaction.thresholdTokens) {
3785
+ const fixed = fixedPromptTokens(skills.filter((s) => activeSkillNames.has(s.name)));
3786
+ if (before + fixed > cfg.compaction.thresholdTokens) {
3694
3787
  const compacted = await compressHistory(history, synthesizerModel, {
3695
- thresholdTokens: cfg.compaction.thresholdTokens,
3788
+ thresholdTokens: Math.max(1, cfg.compaction.thresholdTokens - fixed),
3696
3789
  keepRecent: cfg.compaction.keepRecentTurns,
3697
3790
  summaryMaxTokens: cfg.budgets.compaction,
3791
+ maxInputTokens: summaryInputTokens,
3698
3792
  timeoutMs: cfg.chatTimeoutMs,
3699
3793
  abortSignal: opts.signal,
3700
3794
  onUsage: (u) => bumpUsage(u, "compact")
@@ -3905,11 +3999,16 @@ var createAgent = async (config) => {
3905
3999
  while (findings.join("\n").length > FINDINGS_BUDGET && findings.length > 1) findings.shift();
3906
4000
  if (cfg.compaction.auto) {
3907
4001
  const before = estimateTokens(done.join("\n"));
3908
- if (before > cfg.compaction.thresholdTokens) {
4002
+ const room = Math.max(
4003
+ 1,
4004
+ cfg.compaction.thresholdTokens - fixedPromptTokens(skills.filter((s) => activeSkillNames.has(s.name))) - messageTokens(history)
4005
+ );
4006
+ if (before > room) {
3909
4007
  const compacted = await compactSteps(done, synthesizerModel, {
3910
- thresholdTokens: cfg.compaction.thresholdTokens,
4008
+ thresholdTokens: room,
3911
4009
  keepRecent: cfg.compaction.keepRecentSteps,
3912
4010
  summaryMaxTokens: cfg.budgets.compaction,
4011
+ maxInputTokens: summaryInputTokens,
3913
4012
  timeoutMs: cfg.chatTimeoutMs,
3914
4013
  abortSignal: opts.signal,
3915
4014
  onUsage: (u) => bumpUsage(u, "compact")
@@ -3992,11 +4091,13 @@ var createAgent = async (config) => {
3992
4091
  try {
3993
4092
  const transcript = await config.memory.load(sessionId);
3994
4093
  const before = messageTokens(transcript);
4094
+ const fixed = fixedPromptTokens(skills.filter((s) => activeSkillNames.has(s.name)));
3995
4095
  const compacted = await compressHistory(transcript, synthesizerModel, {
3996
4096
  ...byTokens ? {
3997
- thresholdTokens: cfg.compaction.thresholdTokens,
4097
+ thresholdTokens: Math.max(1, cfg.compaction.thresholdTokens - fixed),
3998
4098
  keepRecent: cfg.compaction.keepRecentTurns,
3999
- summaryMaxTokens: cfg.budgets.compaction
4099
+ summaryMaxTokens: cfg.budgets.compaction,
4100
+ maxInputTokens: summaryInputTokens
4000
4101
  } : { maxChars: cfg.compressAfterChars },
4001
4102
  timeoutMs: cfg.chatTimeoutMs,
4002
4103
  abortSignal: opts.signal,
@@ -4055,11 +4156,13 @@ var createAgent = async (config) => {
4055
4156
  thresholdTokens: cfg.compaction.thresholdTokens,
4056
4157
  keepRecent: cfg.compaction.keepRecentTurns,
4057
4158
  summaryMaxTokens: cfg.budgets.compaction,
4159
+ maxInputTokens: summaryInputTokens,
4058
4160
  force: o.force ?? true,
4059
4161
  timeoutMs: cfg.chatTimeoutMs,
4060
4162
  abortSignal: o.signal,
4061
4163
  onUsage: (u) => {
4062
4164
  usage = addUsage(usage, u);
4165
+ charge(sessionId, u);
4063
4166
  }
4064
4167
  });
4065
4168
  if (compacted === transcript)
@@ -4082,6 +4185,16 @@ var createAgent = async (config) => {
4082
4185
  },
4083
4186
  listTools: () => catalog.map((e) => ({ ...e })),
4084
4187
  toolStrategy: strategy,
4188
+ get usage() {
4189
+ return { ...spentAll };
4190
+ },
4191
+ sessionUsage: (sessionId) => ({
4192
+ ...spentBySession.get(sessionId ?? cfg.sessionId) ?? emptyUsage()
4193
+ }),
4194
+ resetUsage: () => {
4195
+ spentAll = emptyUsage();
4196
+ spentBySession.clear();
4197
+ },
4085
4198
  contextWindowTokens: cfg.compaction.contextWindowTokens,
4086
4199
  get skills() {
4087
4200
  return skills.map((s) => ({
@@ -5040,6 +5153,7 @@ init_compress();
5040
5153
  0 && (module.exports = {
5041
5154
  AttachmentsNotSupportedError,
5042
5155
  ContextWindowExceededError,
5156
+ DEFAULT_COMPACTION_THRESHOLD_RATIO,
5043
5157
  EgressError,
5044
5158
  FILES_STORE,
5045
5159
  FIND_TOOLS_NAME,
@@ -5147,6 +5261,7 @@ init_compress();
5147
5261
  renderSearchCatalog,
5148
5262
  renderSkillIndex,
5149
5263
  replanWanted,
5264
+ resolveBudgets,
5150
5265
  resolveCaching,
5151
5266
  resolveCompaction,
5152
5267
  resolveConfig,