@dudko.dev/agent-web 0.0.30 → 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,13 +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
- synthesizer: c.limits?.perCall?.synthesizer ?? c.budgets?.synthesizer ?? 400,
673
- compaction: c.limits?.perCall?.compaction ?? c.compaction?.summaryMaxTokens ?? 1024
674
- },
746
+ budgets: resolveBudgets(c, resolveCompaction(c.compaction).contextWindowTokens),
675
747
  limits: c.limits ?? {},
676
748
  temperature: c.temperature,
677
749
  replan: c.replan ?? true,
@@ -3237,6 +3309,7 @@ ${nudge}` : goal;
3237
3309
  }
3238
3310
  return kept;
3239
3311
  };
3312
+ let wasted = normalizeUsage();
3240
3313
  if (ctx.plannerMode === "native") {
3241
3314
  try {
3242
3315
  const result2 = await generateStructured(ctx.plannerModel, PlanSchema, commonFor("native"));
@@ -3252,6 +3325,7 @@ ${nudge}` : goal;
3252
3325
  if (refused) throw refused;
3253
3326
  const overflow = contextOverflowOf(err, ctx.plannerModel);
3254
3327
  if (overflow) throw overflow;
3328
+ wasted = usageOfError(err);
3255
3329
  ctx.log.warn("planner: native structured output failed, salvaging:", asMessage(err));
3256
3330
  ctx.emit({ type: "retry", phase: "plan", attempt: 1, error: asMessage(err) });
3257
3331
  }
@@ -3270,7 +3344,7 @@ ${nudge}` : goal;
3270
3344
  cap
3271
3345
  )
3272
3346
  },
3273
- usage: normalizeUsage(result.usage),
3347
+ usage: addUsage(wasted, normalizeUsage(result.usage)),
3274
3348
  skills: validSkills(parsed.skills)
3275
3349
  };
3276
3350
  };
@@ -3302,6 +3376,7 @@ var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
3302
3376
  timeoutMs: ctx.config.chatTimeoutMs
3303
3377
  };
3304
3378
  };
3379
+ let wasted = normalizeUsage();
3305
3380
  if (ctx.plannerMode === "native") {
3306
3381
  try {
3307
3382
  const result = await generateStructured(ctx.plannerModel, ReplanSchema, commonFor("native"));
@@ -3311,7 +3386,8 @@ var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
3311
3386
  plan: result.object.plan ?? [],
3312
3387
  usage: normalizeUsage(result.usage)
3313
3388
  };
3314
- } catch {
3389
+ } catch (err) {
3390
+ wasted = usageOfError(err);
3315
3391
  }
3316
3392
  }
3317
3393
  try {
@@ -3321,10 +3397,10 @@ var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
3321
3397
  decision: parsed.decision,
3322
3398
  reason: parsed.reason,
3323
3399
  plan: parsed.plan,
3324
- usage: normalizeUsage(result.usage)
3400
+ usage: addUsage(wasted, normalizeUsage(result.usage))
3325
3401
  };
3326
3402
  } catch {
3327
- return { decision: "continue", reason: "replanner unavailable", plan: [], usage: emptyUsage() };
3403
+ return { decision: "continue", reason: "replanner unavailable", plan: [], usage: wasted };
3328
3404
  }
3329
3405
  };
3330
3406
 
@@ -3486,6 +3562,7 @@ var createAgent = async (config) => {
3486
3562
  const modelWindows = [executorModel, plannerModel, synthesizerModel].map(contextWindowOf).filter((w) => w !== void 0);
3487
3563
  const modelWindow = modelWindows.length ? Math.min(...modelWindows) : void 0;
3488
3564
  cfg.compaction = fitCompactionToWindow(cfg.compaction, config.compaction, modelWindow);
3565
+ cfg.budgets = resolveBudgets(config, cfg.compaction.contextWindowTokens);
3489
3566
  const byTokens = Boolean(config.compaction) || modelWindow !== void 0;
3490
3567
  const log = createLogger(cfg.logLevel, config.logger);
3491
3568
  const skills = (config.skills ?? []).map(defineSkill);
@@ -3508,7 +3585,8 @@ var createAgent = async (config) => {
3508
3585
  config.excludedTools
3509
3586
  );
3510
3587
  const catalog = toolCatalogOf(baseTools);
3511
- const toolTokens = cfg.toolSelectionStrategy === "auto" ? await toolDefinitionTokens(baseTools) : 0;
3588
+ const toolDefTokens = await toolDefinitionTokens(baseTools);
3589
+ const toolTokens = cfg.toolSelectionStrategy === "auto" ? toolDefTokens : 0;
3512
3590
  const strategy = cfg.toolSelectionStrategy === "auto" ? catalog.length > cfg.toolSearchThreshold || toolTokens > cfg.compaction.contextWindowTokens * TOOL_SEARCH_WINDOW_SHARE ? "search" : "all" : cfg.toolSelectionStrategy;
3513
3591
  const reserved = [
3514
3592
  ...skills.length || learning ? SKILL_TOOL_NAMES : [],
@@ -3522,6 +3600,14 @@ var createAgent = async (config) => {
3522
3600
  }
3523
3601
  }
3524
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);
3525
3611
  const hints = /* @__PURE__ */ new Map();
3526
3612
  await Promise.all(
3527
3613
  Object.entries(baseTools).map(async ([name, t]) => {
@@ -3544,6 +3630,12 @@ var createAgent = async (config) => {
3544
3630
  log.info(
3545
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}`
3546
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
+ };
3547
3639
  const runCore = async (goal, opts, track, port) => {
3548
3640
  const resumed = await resolveResume(config.persistence, opts.resumeFromRunId);
3549
3641
  const emit = (event) => {
@@ -3574,6 +3666,7 @@ var createAgent = async (config) => {
3574
3666
  const isAborted = () => opts.signal?.aborted === true;
3575
3667
  const bumpUsage = (u, phase) => {
3576
3668
  usage = addUsage(usage, u);
3669
+ charge(sessionId, u);
3577
3670
  result.usage = usage;
3578
3671
  emit({ type: "usage", phase, usage: u });
3579
3672
  };
@@ -3689,11 +3782,13 @@ var createAgent = async (config) => {
3689
3782
  }
3690
3783
  if (config.memory && byTokens && cfg.compaction.auto && history.length > 0) {
3691
3784
  const before = messageTokens(history);
3692
- if (before > cfg.compaction.thresholdTokens) {
3785
+ const fixed = fixedPromptTokens(skills.filter((s) => activeSkillNames.has(s.name)));
3786
+ if (before + fixed > cfg.compaction.thresholdTokens) {
3693
3787
  const compacted = await compressHistory(history, synthesizerModel, {
3694
- thresholdTokens: cfg.compaction.thresholdTokens,
3788
+ thresholdTokens: Math.max(1, cfg.compaction.thresholdTokens - fixed),
3695
3789
  keepRecent: cfg.compaction.keepRecentTurns,
3696
3790
  summaryMaxTokens: cfg.budgets.compaction,
3791
+ maxInputTokens: summaryInputTokens,
3697
3792
  timeoutMs: cfg.chatTimeoutMs,
3698
3793
  abortSignal: opts.signal,
3699
3794
  onUsage: (u) => bumpUsage(u, "compact")
@@ -3904,11 +3999,16 @@ var createAgent = async (config) => {
3904
3999
  while (findings.join("\n").length > FINDINGS_BUDGET && findings.length > 1) findings.shift();
3905
4000
  if (cfg.compaction.auto) {
3906
4001
  const before = estimateTokens(done.join("\n"));
3907
- 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) {
3908
4007
  const compacted = await compactSteps(done, synthesizerModel, {
3909
- thresholdTokens: cfg.compaction.thresholdTokens,
4008
+ thresholdTokens: room,
3910
4009
  keepRecent: cfg.compaction.keepRecentSteps,
3911
4010
  summaryMaxTokens: cfg.budgets.compaction,
4011
+ maxInputTokens: summaryInputTokens,
3912
4012
  timeoutMs: cfg.chatTimeoutMs,
3913
4013
  abortSignal: opts.signal,
3914
4014
  onUsage: (u) => bumpUsage(u, "compact")
@@ -3991,11 +4091,13 @@ var createAgent = async (config) => {
3991
4091
  try {
3992
4092
  const transcript = await config.memory.load(sessionId);
3993
4093
  const before = messageTokens(transcript);
4094
+ const fixed = fixedPromptTokens(skills.filter((s) => activeSkillNames.has(s.name)));
3994
4095
  const compacted = await compressHistory(transcript, synthesizerModel, {
3995
4096
  ...byTokens ? {
3996
- thresholdTokens: cfg.compaction.thresholdTokens,
4097
+ thresholdTokens: Math.max(1, cfg.compaction.thresholdTokens - fixed),
3997
4098
  keepRecent: cfg.compaction.keepRecentTurns,
3998
- summaryMaxTokens: cfg.budgets.compaction
4099
+ summaryMaxTokens: cfg.budgets.compaction,
4100
+ maxInputTokens: summaryInputTokens
3999
4101
  } : { maxChars: cfg.compressAfterChars },
4000
4102
  timeoutMs: cfg.chatTimeoutMs,
4001
4103
  abortSignal: opts.signal,
@@ -4054,11 +4156,13 @@ var createAgent = async (config) => {
4054
4156
  thresholdTokens: cfg.compaction.thresholdTokens,
4055
4157
  keepRecent: cfg.compaction.keepRecentTurns,
4056
4158
  summaryMaxTokens: cfg.budgets.compaction,
4159
+ maxInputTokens: summaryInputTokens,
4057
4160
  force: o.force ?? true,
4058
4161
  timeoutMs: cfg.chatTimeoutMs,
4059
4162
  abortSignal: o.signal,
4060
4163
  onUsage: (u) => {
4061
4164
  usage = addUsage(usage, u);
4165
+ charge(sessionId, u);
4062
4166
  }
4063
4167
  });
4064
4168
  if (compacted === transcript)
@@ -4081,6 +4185,16 @@ var createAgent = async (config) => {
4081
4185
  },
4082
4186
  listTools: () => catalog.map((e) => ({ ...e })),
4083
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
+ },
4084
4198
  contextWindowTokens: cfg.compaction.contextWindowTokens,
4085
4199
  get skills() {
4086
4200
  return skills.map((s) => ({
@@ -5039,6 +5153,7 @@ init_compress();
5039
5153
  0 && (module.exports = {
5040
5154
  AttachmentsNotSupportedError,
5041
5155
  ContextWindowExceededError,
5156
+ DEFAULT_COMPACTION_THRESHOLD_RATIO,
5042
5157
  EgressError,
5043
5158
  FILES_STORE,
5044
5159
  FIND_TOOLS_NAME,
@@ -5146,6 +5261,7 @@ init_compress();
5146
5261
  renderSearchCatalog,
5147
5262
  renderSkillIndex,
5148
5263
  replanWanted,
5264
+ resolveBudgets,
5149
5265
  resolveCaching,
5150
5266
  resolveCompaction,
5151
5267
  resolveConfig,