@eum-agent/context-management 1.0.0 → 1.1.0

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/dist/index.js +2084 -231
  2. package/package.json +5 -5
  3. package/ui/ui.js +295 -226
package/ui/ui.js CHANGED
@@ -1,41 +1,86 @@
1
- import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
2
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
1
+ import { useEffect, useState, useSyncExternalStore } from "react";
2
+ import { jsx, jsxs } from "react/jsx-runtime";
3
3
  //#region ui-src/lib/status.ts
4
- /** Refreshes observed sessions from this owner's validated method and change frames. */
4
+ /** Coalesces watched IDs into bounded collections and fences late replies to connection and watch epochs. */
5
5
  function createContextStatusView(ctx) {
6
6
  const values = /* @__PURE__ */ new Map();
7
7
  const watched = /* @__PURE__ */ new Map();
8
- let nextEpoch = 0;
9
- const pending = /* @__PURE__ */ new Set();
10
- const dirty = /* @__PURE__ */ new Set();
8
+ const queued = /* @__PURE__ */ new Set();
9
+ const active = /* @__PURE__ */ new Map();
10
+ const serverEpochs = /* @__PURE__ */ new Map();
11
11
  const listeners = /* @__PURE__ */ new Set();
12
- function refresh(sessionId) {
13
- if (ctx.signal.aborted || !watched.has(sessionId)) return;
14
- if (pending.has(sessionId)) {
15
- dirty.add(sessionId);
16
- return;
17
- }
18
- const epoch = watched.get(sessionId).epoch;
19
- pending.add(sessionId);
20
- ctx.invoke("status", { sessionId }).then((value) => {
21
- if (ctx.signal.aborted || watched.get(sessionId)?.epoch !== epoch) return;
22
- if (value) values.set(sessionId, value);
23
- else values.delete(sessionId);
24
- for (const listener of [...listeners]) listener();
25
- }).catch(() => {}).finally(() => {
26
- pending.delete(sessionId);
27
- if (dirty.delete(sessionId)) refresh(sessionId);
12
+ let nextEpoch = 0, generation = 0, scheduled = false;
13
+ let online = ctx.gateway.connection.status === "online";
14
+ const notify = () => {
15
+ for (const listener of [...listeners]) listener();
16
+ };
17
+ const schedule = (ids = []) => {
18
+ for (const id of ids) if (watched.has(id)) queued.add(id);
19
+ if (scheduled || ctx.signal.aborted) return;
20
+ scheduled = true;
21
+ queueMicrotask(() => {
22
+ scheduled = false;
23
+ if (ctx.signal.aborted || !online) return;
24
+ const selected = [...queued].filter((id) => watched.has(id) && !active.has(id));
25
+ for (let offset = 0; offset < selected.length; offset += 31) {
26
+ const sessionIds = selected.slice(offset, offset + 31), token = Symbol(), at = generation;
27
+ const epochs = sessionIds.map((id) => watched.get(id).epoch);
28
+ for (const id of sessionIds) {
29
+ queued.delete(id);
30
+ active.set(id, token);
31
+ }
32
+ ctx.invoke("statuses", { sessionIds }).then(({ results }) => {
33
+ if (ctx.signal.aborted || generation !== at || results.length !== sessionIds.length) return;
34
+ if (results.some((one, index) => one.index !== index || one.target !== sessionIds[index])) return;
35
+ let changed = false;
36
+ for (const [index, one] of results.entries()) {
37
+ if (watched.get(one.target)?.epoch !== epochs[index] || !one.ok) continue;
38
+ if (one.value === null) {
39
+ changed = values.delete(one.target) || changed;
40
+ continue;
41
+ }
42
+ const nextOrder = one.value.statusOrder;
43
+ const previous = values.get(one.target);
44
+ if (nextOrder) {
45
+ const epoch = serverEpochs.get(one.target);
46
+ if (epoch !== void 0 && epoch !== nextOrder.epoch) continue;
47
+ const prior = previous?.statusOrder;
48
+ if (epoch && prior && (nextOrder.sequence <= prior.sequence || nextOrder.historyGeneration < prior.historyGeneration)) continue;
49
+ serverEpochs.set(one.target, nextOrder.epoch);
50
+ } else if ((previous?.revision ?? -1) > one.value.revision) continue;
51
+ values.set(one.target, one.value);
52
+ changed = true;
53
+ }
54
+ if (changed) notify();
55
+ }).catch(() => {}).finally(() => {
56
+ for (const id of sessionIds) if (active.get(id) === token) active.delete(id);
57
+ if (queued.size) schedule();
58
+ });
59
+ }
28
60
  });
29
- }
61
+ };
30
62
  ctx.on("statusChanged", (event) => {
31
- if (event.sessionId) refresh(event.sessionId);
32
- });
33
- ctx.onCore("session.updated", () => {
34
- for (const id of watched.keys()) refresh(id);
63
+ if (event.sessionId) schedule([event.sessionId]);
35
64
  });
65
+ ctx.onCore("session.updated", () => schedule([...watched.keys()]));
36
66
  ctx.gateway.watchConnection((connection) => {
37
- if (connection.status === "online") for (const id of watched.keys()) refresh(id);
67
+ const next = connection.status === "online";
68
+ if (next !== online) {
69
+ generation++;
70
+ active.clear();
71
+ serverEpochs.clear();
72
+ }
73
+ if (next && !online) schedule([...watched.keys()]);
74
+ online = next;
38
75
  });
76
+ ctx.signal.addEventListener("abort", () => {
77
+ generation++;
78
+ queued.clear();
79
+ active.clear();
80
+ values.clear();
81
+ serverEpochs.clear();
82
+ listeners.clear();
83
+ }, { once: true });
39
84
  return {
40
85
  get: (sessionId) => values.get(sessionId),
41
86
  subscribe(listener) {
@@ -51,49 +96,48 @@ function createContextStatusView(ctx) {
51
96
  count: 1,
52
97
  epoch: ++nextEpoch
53
98
  });
54
- refresh(sessionId);
99
+ if (!current) schedule([sessionId]);
100
+ let stopped = false;
55
101
  return () => {
102
+ if (stopped) return;
103
+ stopped = true;
56
104
  const current = watched.get(sessionId);
57
105
  if (!current) return;
58
- const count = current.count - 1;
59
- if (count) watched.set(sessionId, {
106
+ if (current.count > 1) watched.set(sessionId, {
60
107
  ...current,
61
- count
108
+ count: current.count - 1
62
109
  });
63
110
  else {
64
111
  watched.delete(sessionId);
65
- values.delete(sessionId);
112
+ queued.delete(sessionId);
113
+ active.delete(sessionId);
114
+ serverEpochs.delete(sessionId);
115
+ if (values.delete(sessionId)) notify();
66
116
  }
67
117
  };
68
118
  }
69
119
  };
70
120
  }
71
121
  //#endregion
72
- //#region ui-src/lib/failure.ts
73
- /** Presents gateway failures through the plugin's host controls. */
74
- function failureText(value, t) {
75
- if (value == null || value === "") return null;
76
- if (typeof value === "string") return value === t("connection.offline") ? null : value;
77
- if (typeof value === "object") {
78
- const failure = value;
79
- const kind = failure.kind ?? failure.failure;
80
- if (kind === "offline" || kind === "authentication") return null;
81
- if (kind === "refused") return failure.reason ?? failure.message ?? String(value);
82
- }
83
- return value instanceof Error ? value.message : String(value);
84
- }
85
- function useFailureToast(host) {
86
- const toast = host.ui.useToast();
87
- return useCallback((failure, title) => {
88
- const text = failureText(failure, host.i18n.t);
89
- if (text === null) return;
90
- toast.add({
91
- id: `failure:${title ?? ""}:${text}`,
92
- tone: "destructive",
93
- title: title ?? text,
94
- ...title === void 0 ? {} : { description: text }
95
- });
96
- }, [host, toast]);
122
+ //#region ui-src/lib/host.ts
123
+ /** Shares popover dismissal without any gateway state or requests. */
124
+ function createStatusPopovers() {
125
+ let value;
126
+ const listeners = /* @__PURE__ */ new Set();
127
+ return {
128
+ get: () => value,
129
+ subscribe: (listener) => {
130
+ listeners.add(listener);
131
+ return () => {
132
+ listeners.delete(listener);
133
+ };
134
+ },
135
+ set: (next) => {
136
+ if (value === next) return;
137
+ value = next;
138
+ for (const listener of listeners) listener();
139
+ }
140
+ };
97
141
  }
98
142
  //#endregion
99
143
  //#region ui-src/lib/context-window.ts
@@ -106,23 +150,6 @@ function formatContextWindow(value) {
106
150
  }
107
151
  //#endregion
108
152
  //#region ui-src/components/context-usage.tsx
109
- var REASONS = /* @__PURE__ */ new Set([
110
- "capacity_unknown",
111
- "context_projection_degraded",
112
- "fixed_context_too_large",
113
- "recovery_unavailable",
114
- "summary_budget_too_small",
115
- "summary_failed",
116
- "summary_no_gain",
117
- "summary_network_error",
118
- "summary_invalid",
119
- "summary_unavailable",
120
- "summary_provider_unavailable",
121
- "summary_group_too_large",
122
- "protected_context_exceeds_budget",
123
- "context_still_exceeds_budget",
124
- "cancelled"
125
- ]);
126
153
  /** Cells in the popover's window map, one per half percent of the window. */
127
154
  var CELLS = 200;
128
155
  /** Share of the window at which the meter turns from green to yellow, and from yellow to red. */
@@ -199,44 +226,21 @@ function cellsOf(occupancy, window) {
199
226
  const filled = categories === void 0 ? Array.from({ length: used }, () => "used") : apportion(used, categories.map((one) => one.tokens)).flatMap((count, index) => Array.from({ length: count }, () => categories[index]?.category ?? "used"));
200
227
  return [...filled, ...Array.from({ length: CELLS - filled.length }, () => "free")];
201
228
  }
202
- /** Elapsed time is display-only; it never cancels a context operation. */
203
- function PreparationProgress({ startedAt, completedChunks, t }) {
204
- const [now, setNow] = useState(Date.now);
205
- useEffect(() => {
206
- if (startedAt === void 0) return;
207
- const timer = setInterval(() => setNow(Date.now()), 1e3);
208
- return () => clearInterval(timer);
209
- }, [startedAt]);
210
- return /* @__PURE__ */ jsxs("p", {
211
- role: "status",
212
- children: [
213
- t("usage.preparing"),
214
- startedAt !== void 0 && ` · ${t("usage.elapsed", { seconds: Math.max(0, Math.floor((now - startedAt) / 1e3)) })}`,
215
- completedChunks !== void 0 && ` · ${t("usage.completedChunks", { count: completedChunks })}`
216
- ]
217
- });
218
- }
219
229
  /** Draws the host's occupancy as a meter, its window map and the legend by category. */
220
230
  function contextUsageFor(host) {
221
231
  return function ContextUsage({ sessionId }) {
222
- const state = useSyncExternalStore(host.host.subscribe, host.host.get);
223
- const fail = useFailureToast(host);
224
232
  const [toolsOpen, setToolsOpen] = useState(false);
225
- const [pending, setPending] = useState(false);
226
- const running = useRef(false);
233
+ const popover = useSyncExternalStore(host.popovers.subscribe, host.popovers.get);
227
234
  const t = host.i18n.t;
228
235
  const context = useSyncExternalStore(host.context.subscribe, () => host.context.get(sessionId));
229
236
  useEffect(() => host.context.watch(sessionId), [sessionId]);
230
- const occupancy = context?.occupancy?.source === "unmeasured" ? void 0 : context?.occupancy;
231
- const limit = context?.measurement?.contextWindow;
237
+ const currentOccupancy = context?.occupancy?.source === "unmeasured" ? void 0 : context?.occupancy;
238
+ const historical = currentOccupancy === void 0 ? context?.lastObservation : void 0;
239
+ const occupancy = currentOccupancy ?? historical?.occupancy;
240
+ const limit = (historical?.measurement ?? context?.measurement)?.contextWindow;
232
241
  const share = occupancy === void 0 || limit === void 0 ? void 0 : Math.min(100, Math.round(occupancy.inputTokens / limit * 100));
233
242
  const level = share === void 0 ? void 0 : contextLevel(share);
234
243
  const mark = occupancy?.source === "estimated" ? "~" : "";
235
- const operation = context?.operation;
236
- const measurement = context?.measurement;
237
- const blocked = measurement?.inputBudget !== void 0 && measurement.inputTokens > measurement.inputBudget;
238
- const reason = context?.lastResult?.reason ?? context?.diagnostic;
239
- const reasonText = reason === void 0 ? void 0 : t(REASONS.has(reason) ? `usage.reason.${reason}` : "usage.failed");
240
244
  const tokens = (value) => value === void 0 ? "—" : compactTokens(value);
241
245
  const percent = (value) => {
242
246
  if (limit === void 0) return "";
@@ -254,35 +258,14 @@ function contextUsageFor(host) {
254
258
  tokens: Math.max(0, limit - occupancy.inputTokens)
255
259
  }]];
256
260
  const owners = [...occupancy?.tools ?? []].filter((one) => one.tokens > 0).sort((a, b) => b.tokens - a.tokens);
257
- async function run(action) {
258
- if (running.current) return;
259
- running.current = true;
260
- setPending(true);
261
- try {
262
- await action();
263
- } catch {
264
- fail(t("usage.failed"));
265
- } finally {
266
- running.current = false;
267
- setPending(false);
268
- }
269
- }
270
- function cancel() {
271
- if (operation === void 0) return Promise.resolve();
272
- return run(() => host.call("cancel", {
273
- sessionId,
274
- operationId: operation.operationId
275
- }));
276
- }
277
- function retry() {
278
- return run(() => host.call("compact", { sessionId }));
279
- }
280
261
  function nameOf(key) {
281
262
  if (key === "used") return t("usage.used");
282
263
  if (key === "free") return t("usage.free");
283
264
  return t(`usage.category.${key}`);
284
265
  }
285
266
  return /* @__PURE__ */ jsxs(host.ui.Popover, {
267
+ open: popover === `context:${sessionId}`,
268
+ onOpenChange: (open) => host.popovers.set(open ? `context:${sessionId}` : void 0),
286
269
  width: 360,
287
270
  label: t("usage.context"),
288
271
  side: "top",
@@ -397,106 +380,111 @@ function contextUsageFor(host) {
397
380
  }, one.owner ?? ""))
398
381
  })]
399
382
  }, row.key))
400
- }),
401
- occupancy !== void 0 && /* @__PURE__ */ jsxs("p", {
402
- className: "cu-note",
403
- children: [t(occupancy.source === "reported" ? "usage.noteReported" : "usage.noteEstimated"), occupancy.categories === void 0 && ` ${t("usage.noSplit")}`]
404
- }),
405
- /* @__PURE__ */ jsxs("dl", {
406
- className: "cu-stats",
407
- children: [
408
- measurement?.inputBudget !== void 0 && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("dt", { children: t("usage.inputBudget") }), /* @__PURE__ */ jsx("dd", { children: /* @__PURE__ */ jsx(AlignedNumber, {
409
- className: "cu-stat",
410
- text: tokens(measurement.inputBudget)
411
- }) })] }),
412
- measurement !== void 0 && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("dt", { children: t("usage.outputReserve") }), /* @__PURE__ */ jsx("dd", { children: /* @__PURE__ */ jsx(AlignedNumber, {
413
- className: "cu-stat",
414
- text: tokens(measurement.outputReserve)
415
- }) })] }),
416
- /* @__PURE__ */ jsx("dt", { children: t("usage.actual") }),
417
- /* @__PURE__ */ jsx("dd", { children: /* @__PURE__ */ jsx(AlignedNumber, {
418
- className: "cu-stat",
419
- text: tokens(context?.actualInputTokens)
420
- }) }),
421
- /* @__PURE__ */ jsx("dt", { children: t("usage.total") }),
422
- /* @__PURE__ */ jsx("dd", { children: /* @__PURE__ */ jsx(AlignedNumber, {
423
- className: "cu-stat",
424
- text: tokens(context?.totalTokens ?? state.tokensUsed ?? void 0)
425
- }) }),
426
- /* @__PURE__ */ jsx("dt", { children: t("usage.auxiliary") }),
427
- /* @__PURE__ */ jsx("dd", { children: /* @__PURE__ */ jsx(AlignedNumber, {
428
- className: "cu-stat",
429
- text: tokens(context?.auxiliaryTokens)
430
- }) })
431
- ]
432
- }),
433
- measurement?.outputReserveSource !== void 0 && /* @__PURE__ */ jsx("p", {
434
- className: "cu-note",
435
- children: t(`usage.reserveSource.${measurement.outputReserveSource}`)
436
- }),
437
- operation !== void 0 && /* @__PURE__ */ jsx(PreparationProgress, {
438
- startedAt: operation.startedAt,
439
- completedChunks: operation.completedChunks,
440
- t
441
- }),
442
- context?.lastResult && /* @__PURE__ */ jsxs("section", {
443
- "aria-label": t(operation ? "usage.previousResult" : "usage.latestResult"),
444
- children: [
445
- /* @__PURE__ */ jsx("p", {
446
- className: "cu-note",
447
- children: t(operation ? "usage.previousResult" : "usage.latestResult")
448
- }),
449
- /* @__PURE__ */ jsxs("p", {
450
- role: "status",
451
- className: "cu-note",
452
- children: [
453
- t(context.lastResult.status === "changed" && context.lastResult.layer === "none" ? "usage.previewChanged" : `usage.${context.lastResult.status}`),
454
- context.lastResult.layer !== "none" && ` · ${context.lastResult.layer}`,
455
- " · ",
456
- t(`usage.trigger.${context.lastResult.trigger}`),
457
- " · ",
458
- context.lastResult.elapsedMs,
459
- " ms",
460
- context.lastResult.before && context.lastResult.after && ` · ${tokens(context.lastResult.before.inputTokens)} → ${tokens(context.lastResult.after.inputTokens)}`,
461
- context.lastResult.summaryModel && ` · ${t("usage.summaryModel")} ${context.lastResult.summaryModel.model}`,
462
- context.lastResult.completedChunks !== void 0 && ` · ${t("usage.completedChunks", { count: context.lastResult.completedChunks })}`
463
- ]
464
- }),
465
- context.lastResult.reason && reasonText && /* @__PURE__ */ jsx(host.ui.Alert, {
466
- tone: "warning",
467
- children: reasonText
468
- })
469
- ]
470
- }),
471
- !context?.lastResult?.reason && reasonText && /* @__PURE__ */ jsx(host.ui.Alert, {
472
- tone: "warning",
473
- children: reasonText
474
- }),
475
- context?.lastResult?.status === "failed" && operation === void 0 && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("p", {
476
- role: "status",
477
- className: "cu-note",
478
- children: t(blocked ? "usage.blocked" : "usage.canContinue")
479
- }), /* @__PURE__ */ jsx(host.ui.Button, {
480
- variant: "ghost",
481
- type: "button",
482
- loading: pending,
483
- disabled: pending || state.connection !== "online" || state.phase !== void 0 && state.phase !== "idle",
484
- onClick: () => void retry(),
485
- children: t("usage.retry")
486
- })] }),
487
- operation !== void 0 && /* @__PURE__ */ jsx(host.ui.Button, {
488
- variant: "ghost",
489
- type: "button",
490
- loading: pending,
491
- disabled: pending || state.connection !== "online",
492
- onClick: () => void cancel(),
493
- children: t("usage.cancel")
494
383
  })
495
384
  ]
496
385
  });
497
386
  };
498
387
  }
499
388
  //#endregion
389
+ //#region ui-src/components/session-usage.tsx
390
+ /** Physical session consumption, independent of the current context window. */
391
+ /** Renders committed input/output totals and only cache counters reported by a provider. */
392
+ function sessionUsageFor(host) {
393
+ return function SessionUsage({ sessionId }) {
394
+ const context = useSyncExternalStore(host.context.subscribe, () => host.context.get(sessionId));
395
+ const popover = useSyncExternalStore(host.popovers.subscribe, host.popovers.get);
396
+ useEffect(() => host.context.watch(sessionId), [sessionId]);
397
+ const t = host.i18n.t;
398
+ const usage = context?.usage;
399
+ const rows = [
400
+ ["input", usage?.inputTokens ?? 0],
401
+ ["output", usage?.outputTokens ?? 0],
402
+ ["cacheRead", usage?.cacheReadTokens],
403
+ ["cacheWrite", usage?.cacheWriteTokens]
404
+ ];
405
+ return /* @__PURE__ */ jsxs(host.ui.Popover, {
406
+ label: t("consumption.title"),
407
+ width: 260,
408
+ side: "top",
409
+ align: "end",
410
+ className: "cu-panel",
411
+ open: popover === `usage:${sessionId}`,
412
+ onOpenChange: (open) => host.popovers.set(open ? `usage:${sessionId}` : void 0),
413
+ trigger: /* @__PURE__ */ jsxs(host.ui.Button, {
414
+ variant: "plain",
415
+ className: "cu cu-consumption",
416
+ children: [compactTokens(usage?.totalTokens ?? 0), " Tokens"]
417
+ }),
418
+ children: [/* @__PURE__ */ jsxs("p", {
419
+ className: "cu-head",
420
+ children: [/* @__PURE__ */ jsx("span", {
421
+ className: "cu-head-name",
422
+ children: t("consumption.total")
423
+ }), /* @__PURE__ */ jsx(AlignedNumber, {
424
+ className: "cu-head-value cu-consumption-total",
425
+ text: compactTokens(usage?.totalTokens ?? 0)
426
+ })]
427
+ }), /* @__PURE__ */ jsx("dl", {
428
+ className: "cu-stats",
429
+ children: rows.map(([key, value]) => value === void 0 ? null : /* @__PURE__ */ jsxs("div", {
430
+ className: "cu-consumption-row",
431
+ children: [/* @__PURE__ */ jsx("dt", { children: t(`consumption.${key}`) }), /* @__PURE__ */ jsx("dd", { children: /* @__PURE__ */ jsx(AlignedNumber, {
432
+ className: "cu-stat",
433
+ text: compactTokens(value)
434
+ }) })]
435
+ }, key))
436
+ })]
437
+ });
438
+ };
439
+ }
440
+ //#endregion
441
+ //#region ui-src/components/run-summary.ts
442
+ /** Registers owner-bound summaries without changing transcript messages or host terminology. */
443
+ function registerContextSummary(ctx, status) {
444
+ const matches = (left, right) => left.kind === "run" && right.kind === "run" ? left.historyGeneration === right.historyGeneration && left.turn === right.turn : left.kind === "maintenance" && right.kind === "maintenance" && left.operationId === right.operationId;
445
+ ctx.slots.register("chat.run.summary", {
446
+ id: "preparation",
447
+ order: 20,
448
+ subscribe: (changed) => {
449
+ let sessionId = null;
450
+ let unwatch = () => {};
451
+ const update = () => {
452
+ const next = ctx.host.get().sessionId ?? null;
453
+ if (next !== sessionId) {
454
+ unwatch();
455
+ sessionId = next;
456
+ unwatch = next === null ? () => {} : status.watch(next);
457
+ }
458
+ changed();
459
+ };
460
+ const offHost = ctx.host.subscribe(update);
461
+ const offStatus = status.subscribe(changed);
462
+ const offLanguage = ctx.i18n.subscribe(changed);
463
+ update();
464
+ return () => {
465
+ offHost();
466
+ offStatus();
467
+ offLanguage();
468
+ unwatch();
469
+ };
470
+ },
471
+ get: (props) => {
472
+ const operation = status.get(props.sessionId)?.operation;
473
+ if (!props.latest || !operation?.target || !matches(operation.target, props.target) || operation.phase !== "reduction" && operation.phase !== "summary") return null;
474
+ return {
475
+ key: operation.operationId,
476
+ label: ctx.i18n.t("usage.compacting"),
477
+ elapsedMs: operation.elapsedMs ?? 0,
478
+ running: true
479
+ };
480
+ },
481
+ maintenance: (sessionId) => {
482
+ const operation = status.get(sessionId)?.operation;
483
+ return operation?.target?.kind === "maintenance" && (operation.phase === "reduction" || operation.phase === "summary") ? [operation.target] : [];
484
+ }
485
+ });
486
+ }
487
+ //#endregion
500
488
  //#region ui-src/components/tool-preview.tsx
501
489
  /** Observes only mounted tool lines and withdraws together with the Context extension. */
502
490
  function registerPreviewNotice(ctx, status) {
@@ -524,7 +512,9 @@ function registerPreviewNotice(ctx, status) {
524
512
  var TOOL_NAMES = [
525
513
  "context_search",
526
514
  "context_restore",
527
- "session_note"
515
+ "session_note",
516
+ "tool_search",
517
+ "tool_call"
528
518
  ];
529
519
  //#endregion
530
520
  //#region ui-src/metadata.ts
@@ -534,14 +524,18 @@ var CATALOGUES = {
534
524
  group: "Context",
535
525
  context_search: "Search history",
536
526
  context_restore: "Restore history",
537
- session_note: "Update session notes"
527
+ session_note: "Update session notes",
528
+ tool_search: "Search tools",
529
+ tool_call: "Call tool"
538
530
  },
539
531
  "zh-CN": {
540
532
  section: "内置插件",
541
533
  group: "上下文",
542
534
  context_search: "搜索历史上下文",
543
535
  context_restore: "恢复历史上下文",
544
- session_note: "更新会话笔记"
536
+ session_note: "更新会话笔记",
537
+ tool_search: "检索工具",
538
+ tool_call: "调用工具"
545
539
  }
546
540
  };
547
541
  var names = new Set(TOOL_NAMES);
@@ -588,6 +582,19 @@ function registerMetadata(ctx) {
588
582
  });
589
583
  }
590
584
  //#endregion
585
+ //#region ui-src/lib/failure.ts
586
+ function failureText(value, t) {
587
+ if (value == null || value === "") return null;
588
+ if (typeof value === "string") return value === t("connection.offline") ? null : value;
589
+ if (typeof value === "object") {
590
+ const failure = value;
591
+ const kind = failure.kind ?? failure.failure;
592
+ if (kind === "offline" || kind === "authentication") return null;
593
+ if (kind === "refused") return failure.reason ?? failure.message ?? String(value);
594
+ }
595
+ return value instanceof Error ? value.message : String(value);
596
+ }
597
+ //#endregion
591
598
  //#region ui-src/lib/commands.ts
592
599
  /** Registers the manual context command with the plugin's withdrawal lifetime. */
593
600
  function registerCommands(ctx) {
@@ -639,9 +646,45 @@ function registerCommands(ctx) {
639
646
  });
640
647
  }
641
648
  //#endregion
649
+ //#region ui-src/lib/tool-preload.ts
650
+ function object(value) {
651
+ if (value === void 0) return {};
652
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error("Tool preload configuration must be an object");
653
+ return value;
654
+ }
655
+ function read(value) {
656
+ const overrides = object(object(value).toolPreload);
657
+ for (const [name, enabled] of Object.entries(overrides)) {
658
+ if (!/^[a-zA-Z0-9_-]{1,64}$/.test(name) || typeof enabled !== "boolean") throw new Error("Tool preload overrides must map valid tool names to booleans");
659
+ if (name === "tool_search" || name === "tool_call") throw new Error("System tool preload cannot be overridden");
660
+ }
661
+ return { ...overrides };
662
+ }
663
+ /** Retains other owner fields and replaces sparse overrides; invalid data throws before editing. */
664
+ var toolPreloadConfiguration = {
665
+ owner: "@eum-agent/context-management",
666
+ read,
667
+ replace: (value, overrides) => {
668
+ read(value);
669
+ const toolPreload = read({ toolPreload: overrides });
670
+ return {
671
+ ...object(value),
672
+ toolPreload
673
+ };
674
+ }
675
+ };
676
+ //#endregion
642
677
  //#region ui-src/locales/en-US.ts
643
678
  /** Context surface translations. */
644
679
  var catalogue$1 = {
680
+ consumption: {
681
+ title: "Token usage",
682
+ total: "Total",
683
+ input: "Input",
684
+ output: "Output",
685
+ cacheRead: "Cache read",
686
+ cacheWrite: "Cache write"
687
+ },
645
688
  connection: {
646
689
  offline: "Not connected to the gateway",
647
690
  authenticationRequired: "Authentication is unavailable. Run yaoguang webui to reopen this page."
@@ -659,6 +702,7 @@ var catalogue$1 = {
659
702
  },
660
703
  status: { context: "Context usage" },
661
704
  usage: {
705
+ compacting: "Compacting context",
662
706
  context: "Context",
663
707
  unmeasured: "unmeasured",
664
708
  used: "Used",
@@ -731,6 +775,14 @@ var catalogue$1 = {
731
775
  //#region ui-src/locales/zh-CN.ts
732
776
  /** Context surface translations. */
733
777
  var catalogue = {
778
+ consumption: {
779
+ title: "Token 用量",
780
+ total: "总用量",
781
+ input: "输入",
782
+ output: "输出",
783
+ cacheRead: "缓存读取",
784
+ cacheWrite: "缓存写入"
785
+ },
734
786
  connection: {
735
787
  offline: "未连接到网关服务",
736
788
  authenticationRequired: "认证不可用,请运行 yaoguang webui 重新打开"
@@ -748,6 +800,7 @@ var catalogue = {
748
800
  },
749
801
  status: { context: "上下文占用" },
750
802
  usage: {
803
+ compacting: "正在压缩上下文",
751
804
  context: "上下文",
752
805
  unmeasured: "未测得",
753
806
  used: "已用",
@@ -817,26 +870,41 @@ var catalogue = {
817
870
  };
818
871
  //#endregion
819
872
  //#region ui-src/styles.css?raw
820
- var styles_default = "/* A portalled panel can be the scope root; :where preserves selector specificity. */\n:is(:where(:scope).cu-panel, .cu-panel) {\n overflow-wrap: anywhere;\n}\n:is(:where(:scope).cu-panel, .cu-panel) > p {\n margin: 0 0 0.5rem;\n}\n.cu {\n --cu-tone: var(--meter-low);\n display: flex;\n align-items: center;\n padding: 0;\n height: auto;\n}\n.cu[data-level=\"mid\"],\n.cu-map[data-level=\"mid\"],\n.cu-legend[data-level=\"mid\"] {\n --cu-tone: var(--meter-mid);\n}\n.cu[data-level=\"high\"],\n.cu-map[data-level=\"high\"],\n.cu-legend[data-level=\"high\"] {\n --cu-tone: var(--meter-high);\n}\n.cu-map,\n.cu-legend {\n --cu-tone: var(--meter-low);\n}\n.cu-bar {\n position: relative;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 7rem;\n height: 1.125rem;\n overflow: hidden;\n border-radius: var(--radius-xs);\n background: var(--meter-free);\n}\n.cu-fill {\n position: absolute;\n inset-block: 0;\n inset-inline-start: 0;\n background: var(--cu-tone);\n transition: inline-size 240ms ease;\n}\n.cu-share,\n.cu-unknown {\n position: relative;\n color: var(--foreground);\n font-variant-numeric: tabular-nums;\n line-height: 1;\n}\n.cu-unknown {\n color: var(--muted-foreground);\n}\n.cu-name {\n position: absolute;\n width: 1px;\n height: 1px;\n overflow: hidden;\n clip-path: inset(50%);\n}\n.cu-head {\n display: flex;\n align-items: baseline;\n justify-content: space-between;\n gap: 0.75rem;\n}\n.cu-head-name {\n font-weight: 600;\n}\n.cu-head-value {\n display: inline-flex;\n align-items: baseline;\n gap: 0.25rem;\n font-variant-numeric: tabular-nums;\n}\n.cu-head-share {\n font-weight: 600;\n}\n.cu-head-count {\n color: var(--muted-foreground);\n}\n/* A column of numbers aligned on the decimal point: the whole part is\n right-aligned by the cell, the fraction and the unit share one fixed slot. */\n.cu-num {\n display: inline-flex;\n justify-content: flex-end;\n font-variant-numeric: tabular-nums;\n}\n.cu-num-tail {\n display: inline-block;\n min-inline-size: 3ch;\n text-align: start;\n}\n.cu-head-count,\n.cu-legend-count,\n.cu-legend-share,\n.cu-stats dd {\n font-variant-numeric: tabular-nums;\n}\n.cu-map {\n display: grid;\n grid-template-columns: repeat(20, 1fr);\n gap: 2px;\n margin-block-end: 0.75rem;\n}\n.cu-cell {\n aspect-ratio: 1;\n border-radius: 2px;\n background: var(--meter-free);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"used\"] {\n background: var(--cu-tone);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"system\"] {\n background: var(--meter-cat-system);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"rules\"] {\n background: var(--meter-cat-rules);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"skills\"] {\n background: var(--meter-cat-skills);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"agents\"] {\n background: var(--meter-cat-agents);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"tools\"] {\n background: var(--meter-cat-tools);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"messages\"] {\n background: var(--meter-cat-messages);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"volatile\"] {\n background: var(--meter-cat-volatile);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"files\"] {\n background: var(--meter-cat-files);\n}\n.cu-legend {\n display: grid;\n gap: 0.25rem;\n margin: 0 0 0.75rem;\n padding: 0;\n list-style: none;\n}\n.cu-legend-row {\n display: grid;\n grid-template-columns: 0.625rem 1fr auto 3.5rem;\n align-items: center;\n gap: 0.5rem;\n}\n.cu-owners {\n display: grid;\n gap: 0.25rem;\n margin: 0.25rem 0 0;\n padding: 0;\n list-style: none;\n}\n.cu-owner-name {\n overflow: hidden;\n color: var(--muted-foreground);\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.cu-tools-toggle {\n padding: 0;\n border: 0;\n background: none;\n color: inherit;\n font: inherit;\n text-align: start;\n text-decoration: underline dotted;\n text-underline-offset: 3px;\n cursor: pointer;\n}\n.cu-swatch {\n width: 0.625rem;\n height: 0.625rem;\n border-radius: 2px;\n background: var(--meter-free);\n}\n.cu-legend-count,\n.cu-legend-share {\n text-align: end;\n}\n.cu-legend-share,\n.cu-note {\n color: var(--muted-foreground);\n}\n.cu-stats {\n display: grid;\n grid-template-columns: 1fr auto;\n gap: 0.25rem 0.75rem;\n margin: 0 0 0.5rem;\n padding-block-start: 0.5rem;\n border-block-start: 1px solid var(--border);\n}\n.cu-stats dt {\n color: var(--muted-foreground);\n}\n.cu-stats dd {\n margin: 0;\n text-align: end;\n}\n";
873
+ var styles_default = "/* A portalled panel can be the scope root; :where preserves selector specificity. */\n:is(:where(:scope).cu-panel, .cu-panel) {\n overflow-wrap: anywhere;\n}\n:is(:where(:scope).cu-panel, .cu-panel) > p {\n margin: 0 0 0.5rem;\n}\n.cu {\n --cu-tone: var(--meter-low);\n display: flex;\n align-items: center;\n padding: 0;\n height: auto;\n}\n.cu[data-level=\"mid\"],\n.cu-map[data-level=\"mid\"],\n.cu-legend[data-level=\"mid\"] {\n --cu-tone: var(--meter-mid);\n}\n.cu[data-level=\"high\"],\n.cu-map[data-level=\"high\"],\n.cu-legend[data-level=\"high\"] {\n --cu-tone: var(--meter-high);\n}\n.cu-map,\n.cu-legend {\n --cu-tone: var(--meter-low);\n}\n.cu-bar {\n position: relative;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 7rem;\n height: 1.125rem;\n overflow: hidden;\n border-radius: var(--radius-xs);\n background: var(--meter-free);\n}\n.cu-fill {\n position: absolute;\n inset-block: 0;\n inset-inline-start: 0;\n background: var(--cu-tone);\n transition: inline-size 240ms ease;\n}\n.cu-share,\n.cu-unknown {\n position: relative;\n color: var(--foreground);\n font-variant-numeric: tabular-nums;\n line-height: 1;\n}\n.cu-unknown {\n color: var(--muted-foreground);\n}\n.cu-name {\n position: absolute;\n width: 1px;\n height: 1px;\n overflow: hidden;\n clip-path: inset(50%);\n}\n.cu-head {\n display: flex;\n align-items: baseline;\n justify-content: space-between;\n gap: 0.75rem;\n}\n.cu-head-name {\n font-weight: 600;\n}\n.cu-head-value {\n display: inline-flex;\n align-items: baseline;\n gap: 0.25rem;\n font-variant-numeric: tabular-nums;\n}\n.cu-head-share {\n font-weight: 600;\n}\n.cu-head-count {\n color: var(--muted-foreground);\n}\n.cu-consumption-total {\n font-size: 1rem;\n font-weight: 600;\n}\n/* A column of numbers aligned on the decimal point: the whole part is\n right-aligned by the cell, the fraction and the unit share one fixed slot. */\n.cu-num {\n display: inline-flex;\n justify-content: flex-end;\n font-variant-numeric: tabular-nums;\n}\n.cu-num-tail {\n display: inline-block;\n min-inline-size: 3ch;\n text-align: start;\n}\n.cu-head-count,\n.cu-legend-count,\n.cu-legend-share,\n.cu-stats dd {\n font-variant-numeric: tabular-nums;\n}\n.cu-map {\n display: grid;\n grid-template-columns: repeat(20, 1fr);\n gap: 2px;\n margin-block-end: 0.75rem;\n}\n.cu-cell {\n aspect-ratio: 1;\n border-radius: 2px;\n background: var(--meter-free);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"used\"] {\n background: var(--cu-tone);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"system\"] {\n background: var(--meter-cat-system);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"rules\"] {\n background: var(--meter-cat-rules);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"skills\"] {\n background: var(--meter-cat-skills);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"agents\"] {\n background: var(--meter-cat-agents);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"tools\"] {\n background: var(--meter-cat-tools);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"messages\"] {\n background: var(--meter-cat-messages);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"volatile\"] {\n background: var(--meter-cat-volatile);\n}\n:is(:where(:scope).cu-panel, .cu-panel) [data-cell=\"files\"] {\n background: var(--meter-cat-files);\n}\n.cu-legend {\n display: grid;\n gap: 0.25rem;\n margin: 0 0 0.75rem;\n padding: 0;\n list-style: none;\n}\n.cu-legend-row {\n display: grid;\n grid-template-columns: 0.625rem 1fr auto 3.5rem;\n align-items: center;\n gap: 0.5rem;\n}\n.cu-owners {\n display: grid;\n gap: 0.25rem;\n margin: 0.25rem 0 0;\n padding: 0;\n list-style: none;\n}\n.cu-owner-name {\n overflow: hidden;\n color: var(--muted-foreground);\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.cu-tools-toggle {\n padding: 0;\n border: 0;\n background: none;\n color: inherit;\n font: inherit;\n text-align: start;\n text-decoration: underline dotted;\n text-underline-offset: 3px;\n cursor: pointer;\n}\n.cu-swatch {\n width: 0.625rem;\n height: 0.625rem;\n border-radius: 2px;\n background: var(--meter-free);\n}\n.cu-legend-count,\n.cu-legend-share {\n text-align: end;\n}\n.cu-legend-share,\n.cu-note {\n color: var(--muted-foreground);\n}\n.cu-stats {\n display: grid;\n grid-template-columns: 1fr auto;\n gap: 0.25rem 0.75rem;\n margin: 0 0 0.5rem;\n padding-block-start: 0.5rem;\n}\n.cu-stats dt {\n color: var(--muted-foreground);\n}\n.cu-stats dd {\n margin: 0;\n text-align: end;\n}\n\n.cu-consumption-row {\n display: contents;\n}\n";
821
874
  //#endregion
822
875
  //#region ui-src/index.tsx
823
876
  function flatten(value, prefix = "") {
824
877
  return Object.fromEntries(Object.entries(value).flatMap(([key, item]) => typeof item === "string" ? [[prefix + key, item]] : Object.entries(flatten(item, `${prefix}${key}.`))));
825
878
  }
826
879
  var runtimeVersion = 5;
880
+ /** Optional Agent preference editor service, withdrawn with the Context browser owner. */
881
+ var provides = ["tool-preload:configuration"];
827
882
  var register = (ctx) => {
883
+ ctx.services.provide("tool-preload:configuration", toolPreloadConfiguration);
828
884
  ctx.i18n.register({
829
885
  "en-US": flatten(catalogue$1),
830
886
  "zh-CN": flatten(catalogue)
831
887
  }, "en-US");
832
888
  ctx.styles.add(styles_default, { layer: "unlayered" });
833
889
  const status = createContextStatusView(ctx);
834
- const Context = contextUsageFor({
890
+ const host = {
891
+ popovers: createStatusPopovers(),
835
892
  ui: ctx.ui,
836
893
  host: ctx.host,
837
894
  context: status,
838
895
  i18n: ctx.i18n,
839
896
  call: (method, params) => ctx.invoke(method, params ?? {})
897
+ };
898
+ const Context = contextUsageFor(host);
899
+ const Usage = sessionUsageFor(host);
900
+ function UsageStatus({ sessionId }) {
901
+ useSyncExternalStore(ctx.i18n.subscribe, ctx.i18n.language);
902
+ return sessionId === null ? null : /* @__PURE__ */ jsx(Usage, { sessionId });
903
+ }
904
+ ctx.slots.register("chat.status.item", {
905
+ id: "usage",
906
+ order: 10,
907
+ component: UsageStatus
840
908
  });
841
909
  function Status({ sessionId }) {
842
910
  useSyncExternalStore(ctx.i18n.subscribe, ctx.i18n.language);
@@ -856,9 +924,10 @@ var register = (ctx) => {
856
924
  order: 20,
857
925
  component: Status
858
926
  });
927
+ registerContextSummary(ctx, status);
859
928
  registerCommands(ctx);
860
929
  registerMetadata(ctx);
861
930
  registerPreviewNotice(ctx, status);
862
931
  };
863
932
  //#endregion
864
- export { register, runtimeVersion };
933
+ export { provides, register, runtimeVersion };