codexmate 0.1.31 → 0.1.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.
Files changed (43) hide show
  1. package/README.md +3 -3
  2. package/README.vi.md +3 -3
  3. package/README.zh.md +3 -3
  4. package/cli/agents-files.js +18 -4
  5. package/cli/plugin-config.js +64 -0
  6. package/cli/prompt-history.js +17 -4
  7. package/cli/system-prompt-files.js +7 -2
  8. package/cli.js +36 -2
  9. package/lib/cli-config-engine.js +9 -3
  10. package/lib/session-context-health.js +82 -0
  11. package/lib/session-context-records.js +153 -0
  12. package/lib/web-startup-auth.js +5 -1
  13. package/package.json +1 -1
  14. package/plugins/prompt-templates/computed.mjs +3 -3
  15. package/plugins/prompt-templates/invocation.mjs +73 -0
  16. package/plugins/prompt-templates/methods.mjs +48 -3
  17. package/plugins/prompt-templates/overview.mjs +2 -0
  18. package/web-ui/app.js +25 -0
  19. package/web-ui/index.html +1 -0
  20. package/web-ui/logic.context-health.mjs +144 -0
  21. package/web-ui/modules/app.computed.prompts.mjs +11 -0
  22. package/web-ui/modules/app.methods.agents.mjs +20 -3
  23. package/web-ui/modules/app.methods.index.mjs +4 -0
  24. package/web-ui/modules/app.methods.system-prompt.mjs +17 -2
  25. package/web-ui/modules/context-health.methods.mjs +70 -0
  26. package/web-ui/modules/i18n/locales/en.mjs +33 -0
  27. package/web-ui/modules/i18n/locales/ja.mjs +33 -0
  28. package/web-ui/modules/i18n/locales/vi.mjs +33 -0
  29. package/web-ui/modules/i18n/locales/zh-tw.mjs +33 -0
  30. package/web-ui/modules/i18n/locales/zh.mjs +33 -0
  31. package/web-ui/modules/plugins.methods.mjs +2 -0
  32. package/web-ui/modules/prompt-ecosystem.methods.mjs +136 -0
  33. package/web-ui/partials/index/context-health.html +45 -0
  34. package/web-ui/partials/index/modal-prompt-invocation.html +17 -0
  35. package/web-ui/partials/index/panel-plugins.html +37 -9
  36. package/web-ui/partials/index/panel-prompts.html +18 -2
  37. package/web-ui/partials/index/panel-sessions.html +14 -11
  38. package/web-ui/res/web-ui-render.precompiled.js +682 -32
  39. package/web-ui/styles/context-health.css +107 -0
  40. package/web-ui/styles/prompts-editor.css +23 -0
  41. package/web-ui/styles/sessions-preview.css +21 -0
  42. package/web-ui/styles/sub-tabs.css +181 -0
  43. package/web-ui/styles.css +2 -0
@@ -11,6 +11,7 @@ function createStartupAuth(configuredToken = '') {
11
11
  const token = configuredToken.trim() || crypto.randomBytes(TOKEN_BYTES).toString('hex');
12
12
  function respond(res, status, body, headers = {}) {
13
13
  res.writeHead(status, { 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer',
14
+ 'Content-Type': 'text/plain; charset=utf-8',
14
15
  'X-Content-Type-Options': 'nosniff', ...headers });
15
16
  res.end(body);
16
17
  }
@@ -32,7 +33,10 @@ function createStartupAuth(configuredToken = '') {
32
33
  const pathname = String(req.url || '/').split('?')[0];
33
34
  if (pathname.startsWith('/web-ui/') || pathname.startsWith('/res/') || pathname.startsWith('/bridge/')) { next(); return; }
34
35
  const headers = req.headers || {};
35
- if (headers['sec-fetch-site'] === 'cross-site') {
36
+ // 外部浏览器跳转只允许首页顶层导航进入令牌校验,不直接放行。
37
+ const isEntryNavigation = pathname === '/' && req.method === 'GET'
38
+ && headers['sec-fetch-mode'] === 'navigate' && headers['sec-fetch-dest'] === 'document';
39
+ if (headers['sec-fetch-site'] === 'cross-site' && !isEntryNavigation) {
36
40
  respond(res, 403, '跨站访问已拒绝');
37
41
  return;
38
42
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codexmate",
3
- "version": "0.1.31",
3
+ "version": "0.1.32",
4
4
  "description": "Codex/Claude Code/OpenClaw 配置、会话与任务编排 CLI + Web 工具",
5
5
  "main": "cli.js",
6
6
  "bin": {
@@ -26,7 +26,7 @@ function normalizePromptTemplateEntry(item) {
26
26
 
27
27
  const TEMPLATE_PARTS_CACHE = new Map();
28
28
 
29
- function parseTemplateVariables(templateText) {
29
+ export function parseTemplateVariables(templateText) {
30
30
  const text = typeof templateText === 'string' ? templateText : '';
31
31
  const vars = new Set();
32
32
  const re = /\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g;
@@ -91,13 +91,13 @@ function formatIsoDateLabel(iso) {
91
91
  return `${y}-${m}-${d}`;
92
92
  }
93
93
 
94
- function renderTemplate(templateText, values = {}) {
94
+ export function renderTemplate(templateText, values = {}) {
95
95
  const text = typeof templateText === 'string' ? templateText : '';
96
96
  const map = values && typeof values === 'object' ? values : {};
97
97
  return text.replace(/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g, (_whole, key) => {
98
98
  const name = String(key || '').trim();
99
99
  if (!name) return '';
100
- const value = map[name];
100
+ const value = Object.prototype.hasOwnProperty.call(map, name) ? map[name] : null;
101
101
  return value == null || String(value).trim() === '' ? _whole : String(value);
102
102
  });
103
103
  }
@@ -0,0 +1,73 @@
1
+ import { parseTemplateVariables, renderTemplate } from './computed.mjs';
2
+
3
+ export function createPromptInvocationMethods() {
4
+ return {
5
+ resolvePromptTemplateInvocation(options = {}) {
6
+ const template = typeof options.template === 'string' ? options.template : '';
7
+ const names = parseTemplateVariables(template);
8
+ const supplied = options.values || {};
9
+ const values = Object.fromEntries(names.map((name) => [name,
10
+ Object.prototype.hasOwnProperty.call(supplied, name) ? String(supplied[name] ?? '') : ''
11
+ ]));
12
+ if (names.every((name) => values[name].trim())) {
13
+ return Promise.resolve(renderTemplate(template, values));
14
+ }
15
+ this.closePromptTemplateInvocation();
16
+ this.promptInvocationTemplate = template;
17
+ this.promptInvocationNames = names;
18
+ this.promptInvocationValues = values;
19
+ this.promptInvocationReturnFocus = typeof document === 'undefined' ? null : document.activeElement;
20
+ this.promptInvocationVisible = true;
21
+ return new Promise((resolve) => {
22
+ this.promptInvocationResolve = resolve;
23
+ this.$nextTick(() => this.$refs.promptInvocationDialog?.querySelector('textarea')?.focus());
24
+ });
25
+ },
26
+ finishPromptTemplateInvocation() {
27
+ const missing = this.promptInvocationNames.find((name) => !this.promptInvocationValues[name]?.trim());
28
+ if (missing) {
29
+ this.promptInvocationError = this.t('ecosystem.variablesRequired');
30
+ const index = this.promptInvocationNames.indexOf(missing);
31
+ this.$refs.promptInvocationDialog?.querySelectorAll('textarea')[index]?.focus();
32
+ return;
33
+ }
34
+ const result = renderTemplate(this.promptInvocationTemplate, this.promptInvocationValues);
35
+ const resolve = this.promptInvocationResolve;
36
+ this.promptInvocationResolve = null;
37
+ this.closePromptTemplateInvocation();
38
+ if (resolve) resolve(result);
39
+ },
40
+ closePromptTemplateInvocation() {
41
+ const resolve = this.promptInvocationResolve;
42
+ const focus = this.promptInvocationReturnFocus;
43
+ this.promptInvocationVisible = false;
44
+ this.promptInvocationResolve = null;
45
+ this.promptInvocationTemplate = '';
46
+ this.promptInvocationNames = [];
47
+ this.promptInvocationValues = {};
48
+ this.promptInvocationError = '';
49
+ this.promptInvocationReturnFocus = null;
50
+ if (resolve) resolve(null);
51
+ if (focus && typeof this.$nextTick === 'function') this.$nextTick(() => focus.focus());
52
+ },
53
+ onPromptInvocationKeydown(event) {
54
+ if (event.key === 'Escape') {
55
+ event.preventDefault();
56
+ event.stopPropagation();
57
+ this.closePromptTemplateInvocation();
58
+ return;
59
+ }
60
+ if (event.key !== 'Tab') return;
61
+ const fields = [...event.currentTarget.querySelectorAll('textarea, button:not(:disabled)')];
62
+ const first = fields[0];
63
+ const last = fields[fields.length - 1];
64
+ if (event.shiftKey && event.target === first) {
65
+ event.preventDefault();
66
+ last.focus();
67
+ } else if (!event.shiftKey && event.target === last) {
68
+ event.preventDefault();
69
+ first.focus();
70
+ }
71
+ }
72
+ };
73
+ }
@@ -64,7 +64,7 @@ function nowIso() {
64
64
  return new Date().toISOString();
65
65
  }
66
66
 
67
- function normalizePromptTemplateDraft(draft) {
67
+ export function normalizePromptTemplateDraft(draft) {
68
68
  const safe = draft && typeof draft === 'object' ? draft : {};
69
69
  return {
70
70
  id: typeof safe.id === 'string' ? safe.id : '',
@@ -79,8 +79,36 @@ function normalizePromptTemplateDraft(draft) {
79
79
  };
80
80
  }
81
81
 
82
+ export function buildPromptTemplateSharePayload(template) {
83
+ const draft = normalizePromptTemplateDraft(template);
84
+ if (!draft.id || !draft.name.trim() || !draft.template.trim()) return '';
85
+ return JSON.stringify([draft], null, 2);
86
+ }
87
+
82
88
  export function createPromptTemplatesMethods() {
83
89
  return {
90
+ async sharePromptTemplate() {
91
+ const payload = buildPromptTemplateSharePayload(this.promptTemplateDraft);
92
+ if (!payload) { this.showMessage(this.t('toast.export.empty'), 'info'); return false; }
93
+ try {
94
+ if (navigator.clipboard && window.isSecureContext) {
95
+ await navigator.clipboard.writeText(payload);
96
+ this.showMessage(this.t('toast.copy.ok'), 'success');
97
+ return true;
98
+ }
99
+ } catch (_) {}
100
+ if (typeof this.fallbackCopyText === 'function' && this.fallbackCopyText(payload)) {
101
+ this.showMessage(this.t('toast.copy.ok'), 'success');
102
+ return true;
103
+ }
104
+ if (typeof this.downloadTextFile === 'function') {
105
+ this.downloadTextFile(`prompt-template-${Date.now()}.json`, payload, 'application/json;charset=utf-8');
106
+ this.showMessage(this.t('toast.export.ok'), 'success');
107
+ return true;
108
+ }
109
+ this.showMessage(this.t('toast.copy.fail'), 'error');
110
+ return false;
111
+ },
84
112
  resetPromptComposerVarValues() {
85
113
  this.promptComposerVarValuesRaw = {};
86
114
  persistComposerValuesForTemplate(this.promptComposerSelectedTemplateId, {});
@@ -257,7 +285,14 @@ export function createPromptTemplatesMethods() {
257
285
  },
258
286
 
259
287
  async copyPromptComposerRendered() {
260
- const text = typeof this.promptComposerRendered === 'string' ? this.promptComposerRendered.trim() : '';
288
+ let text = typeof this.promptComposerRendered === 'string' ? this.promptComposerRendered.trim() : '';
289
+ if (typeof this.resolvePromptTemplateInvocation === 'function' && this.promptComposerActiveTemplate) {
290
+ const rendered = await this.resolvePromptTemplateInvocation({
291
+ template: this.promptComposerActiveTemplate.template, values: this.promptComposerVarValues
292
+ });
293
+ if (rendered === null) return;
294
+ text = rendered.trim();
295
+ }
261
296
  if (!text) {
262
297
  this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.empty') : 'Nothing to copy', 'info');
263
298
  return;
@@ -374,7 +409,14 @@ export function createPromptTemplatesMethods() {
374
409
  },
375
410
 
376
411
  async copyRenderedPrompt() {
377
- const text = typeof this.renderedPrompt === 'string' ? this.renderedPrompt.trim() : '';
412
+ let text = typeof this.renderedPrompt === 'string' ? this.renderedPrompt.trim() : '';
413
+ if (typeof this.resolvePromptTemplateInvocation === 'function' && this.promptTemplateDraft) {
414
+ const rendered = await this.resolvePromptTemplateInvocation({
415
+ template: this.promptTemplateDraft.template, values: this.promptTemplateVarValues
416
+ });
417
+ if (rendered === null) return;
418
+ text = rendered.trim();
419
+ }
378
420
  if (!text) {
379
421
  this.showMessage(typeof this.t === 'function' ? this.t('toast.copy.empty') : 'Nothing to copy', 'info');
380
422
  return;
@@ -422,6 +464,7 @@ export function createPromptTemplatesMethods() {
422
464
  } else {
423
465
  list.unshift(entry);
424
466
  }
467
+ if (typeof this.persistPluginTemplates === 'function' && !await this.persistPluginTemplates(list)) return false;
425
468
  this.promptTemplatesListRaw = list;
426
469
  persistPromptTemplatesToStorage(list, localStorage);
427
470
  this.promptTemplateDraftRaw = entry;
@@ -469,6 +512,7 @@ export function createPromptTemplatesMethods() {
469
512
 
470
513
  const list = Array.isArray(this.promptTemplatesListRaw) ? this.promptTemplatesListRaw : [];
471
514
  const next = list.filter((item) => !(item && item.id === draft.id));
515
+ if (typeof this.persistPluginTemplates === 'function' && !await this.persistPluginTemplates(next)) return false;
472
516
  this.promptTemplatesListRaw = next;
473
517
  persistPromptTemplatesToStorage(next, localStorage);
474
518
  this.promptTemplateDraftRaw = null;
@@ -552,6 +596,7 @@ export function createPromptTemplatesMethods() {
552
596
  if (index >= 0) list[index] = entry;
553
597
  else list.unshift(entry);
554
598
  }
599
+ if (typeof this.persistPluginTemplates === 'function' && !await this.persistPluginTemplates(list)) return false;
555
600
  this.promptTemplatesListRaw = list;
556
601
  persistPromptTemplatesToStorage(list, localStorage);
557
602
  this.showMessage(typeof this.t === 'function' ? this.t('toast.import.ok') : 'Imported', 'success');
@@ -38,6 +38,8 @@ export async function loadPromptTemplatesOverview(ctx, options = {}) {
38
38
  app.promptTemplatesListRaw = normalized;
39
39
  persistPromptTemplatesToStorage(normalized, localStorage);
40
40
 
41
+ if (typeof app.loadPluginConfig === 'function' && !await app.loadPluginConfig()) return false;
42
+
41
43
  app.promptTemplatesLoadedOnce = true;
42
44
 
43
45
  if (!app.promptTemplatesMode) {
package/web-ui/app.js CHANGED
@@ -191,6 +191,23 @@ document.addEventListener('DOMContentLoaded', () => {
191
191
  promptComposerPickerKeyword: '',
192
192
  promptComposerSelectedTemplateId: '',
193
193
  promptComposerVarValuesRaw: {},
194
+ promptInvocationVisible: false,
195
+ promptInvocationTemplate: '',
196
+ promptInvocationNames: [],
197
+ promptInvocationValues: {},
198
+ promptInvocationResolve: null,
199
+ promptInvocationReturnFocus: null,
200
+ promptInvocationError: '',
201
+ pluginConfigHash: '',
202
+ pluginHistoryBucket: '',
203
+ pluginConfigLoaded: false,
204
+ pluginConfigSaving: false,
205
+ pluginHistoryVisible: false,
206
+ pluginHistoryLoading: false,
207
+ pluginHistoryItems: [],
208
+ pluginHistorySelectedId: '',
209
+ pluginHistoryContent: '',
210
+ pluginHistoryError: '',
194
211
  showConfirmDialog: false,
195
212
  confirmDialogTitle: '',
196
213
  confirmDialogMessage: '',
@@ -357,6 +374,14 @@ document.addEventListener('DOMContentLoaded', () => {
357
374
  activeSessionDetailClipped: false,
358
375
  sessionDetailLoading: false,
359
376
  sessionDetailRequestSeq: 0,
377
+ sessionContextHealth: null,
378
+ sessionContextHealthStamp: '',
379
+ sessionContextHealthLoading: false,
380
+ sessionContextHealthError: '',
381
+ sessionContextHealthExpanded: false,
382
+ sessionContextHealthPinned: false,
383
+ sessionContextHealthFocusedNode: null,
384
+ sessionContextHealthNodeLoading: false,
360
385
  sessionDetailInitialMessageLimit: 300,
361
386
  sessionDetailFetchStep: 300,
362
387
  sessionDetailMessageLimit: 80,
package/web-ui/index.html CHANGED
@@ -44,6 +44,7 @@
44
44
  <!-- @include ./partials/index/panel-prompts.html -->
45
45
  <!-- @include ./partials/index/layout-footer.html -->
46
46
  <!-- @include ./partials/index/modals-basic.html -->
47
+ <!-- @include ./partials/index/modal-prompt-invocation.html -->
47
48
  <!-- @include ./partials/index/modal-webhook.html -->
48
49
  <!-- @include ./partials/index/modal-openclaw-config.html -->
49
50
  <!-- @include ./partials/index/modal-config-template-agents.html -->
@@ -0,0 +1,144 @@
1
+ import { estimatePromptTokenCount } from './logic.prompts-token-count.mjs';
2
+
3
+ export const CONTEXT_CATEGORIES = ['system', 'user', 'assistant', 'tools', 'code'];
4
+ const HEALTHY_LIMIT = 32000;
5
+ const HEAVY_LIMIT = 64000;
6
+ const DOMINANT_SHARE = 0.15;
7
+ const TOP_CANDIDATES = 7;
8
+ const PREVIEW_LENGTH = 120;
9
+ const LONG_ERROR_TOKENS = 1024;
10
+ const LONG_ERROR_LINES = 100;
11
+ const ERROR_PATTERN = /Traceback|(?:Error|Exception)(?::|\b)|^\s+at .+\(.+:\d+/m;
12
+ const RULE_PATTERN = /<(system-reminder|instructions|user_instructions|developer_instructions|environment_context|project_rules|skills_instructions)>[\s\S]*?<\/\1>/gi;
13
+
14
+ export function contextHealthLevel(tokens) {
15
+ return tokens < HEALTHY_LIMIT ? 'healthy' : (tokens <= HEAVY_LIMIT ? 'heavy' : 'bloated');
16
+ }
17
+
18
+ function splitRules(text, category) {
19
+ if (category === 'system' || /^#\s*AGENTS\.md instructions\b/i.test(text.trimStart())) {
20
+ return [{ category: 'system', text }];
21
+ }
22
+ const parts = [];
23
+ let start = 0;
24
+ for (const match of text.matchAll(RULE_PATTERN)) {
25
+ if (match.index > start) parts.push({ category, text: text.slice(start, match.index) });
26
+ parts.push({ category: 'system', text: match[0] });
27
+ start = match.index + match[0].length;
28
+ }
29
+ if (start < text.length) parts.push({ category, text: text.slice(start) });
30
+ return parts;
31
+ }
32
+
33
+ export function splitContextText(text, category) {
34
+ if (!text) return [];
35
+ if (category === 'code') return [{ category, text }];
36
+ const lines = text.match(/[^\n]*\n|[^\n]+$/g) || [];
37
+ const parts = [];
38
+ let prose = '';
39
+ let code = '';
40
+ let fence = '';
41
+ let diff = false;
42
+ let patch = false;
43
+ for (let index = 0; index < lines.length; index++) {
44
+ const line = lines[index];
45
+ const marker = line.match(/^\s*(`{3,}|~{3,})/);
46
+ if (diff && !patch && !/^(?:[ +\-]|@@ |diff --git |index |new file|deleted file|rename |similarity |\\ No newline)/.test(line)) {
47
+ parts.push({ category: 'code', text: code });
48
+ code = ''; diff = false;
49
+ }
50
+ if (fence) {
51
+ code += line;
52
+ if (marker && marker[1][0] === fence[0] && marker[1].length >= fence.length && /^\s*(`{3,}|~{3,})\s*$/.test(line)) {
53
+ parts.push({ category: 'code', text: code }); code = ''; fence = '';
54
+ }
55
+ } else if (diff) {
56
+ code += line;
57
+ if (patch && /^\*\*\* End Patch/.test(line)) {
58
+ parts.push({ category: 'code', text: code }); code = ''; diff = false; patch = false;
59
+ }
60
+ } else if (/^(?:diff --git |@@ -|\*\*\* Begin Patch)/.test(line) || (/^--- /.test(line) && /^\+\+\+ /.test(lines[index + 1] || ''))) {
61
+ parts.push(...splitRules(prose, category)); prose = '';
62
+ code = line; diff = true; patch = /^\*\*\* Begin Patch/.test(line);
63
+ } else if (marker) {
64
+ parts.push(...splitRules(prose, category)); prose = '';
65
+ fence = marker[1]; code = line;
66
+ } else prose += line;
67
+ }
68
+ if (code) parts.push({ category: 'code', text: code });
69
+ parts.push(...splitRules(prose, category));
70
+ return parts;
71
+ }
72
+
73
+ function preview(text) {
74
+ return text.replace(/Bearer\s+[^\s,]+/gi, 'Bearer [redacted]')
75
+ .replace(/((?:api[_-]?key|token|authorization)['"]?\s*[:=]\s*['"]?)[^\s,]+/gi, '$1[redacted]')
76
+ .replace(/\s+/g, ' ').slice(0, PREVIEW_LENGTH);
77
+ }
78
+
79
+ export function createContextAnalyzer() {
80
+ const totals = Object.fromEntries(CONTEXT_CATEGORIES.map((id) => [id, { estimatedTokens: 0, characters: 0 }]));
81
+ const top = [];
82
+ const hotspots = new Map();
83
+ const files = new Map();
84
+ let messageCount = 0;
85
+ let totalEstimatedTokens = 0;
86
+ function mark(node, reason) {
87
+ const entry = hotspots.get(node.id) || { ...node, reasons: [] };
88
+ if (!entry.reasons.includes(reason)) entry.reasons.push(reason);
89
+ hotspots.set(node.id, entry);
90
+ }
91
+ return {
92
+ add(node) {
93
+ const counts = Object.fromEntries(CONTEXT_CATEGORIES.map((id) => [id, 0]));
94
+ const texts = [];
95
+ for (const part of node.parts) {
96
+ for (const segment of splitContextText(part.text, part.category)) {
97
+ const tokens = estimatePromptTokenCount(segment.text);
98
+ counts[segment.category] += tokens;
99
+ totals[segment.category].estimatedTokens += tokens;
100
+ totals[segment.category].characters += segment.text.length;
101
+ texts.push(segment.text);
102
+ }
103
+ }
104
+ const estimatedTokens = Object.values(counts).reduce((sum, value) => sum + value, 0);
105
+ totalEstimatedTokens += estimatedTokens;
106
+ messageCount++;
107
+ const text = texts.join('');
108
+ const summary = { id: node.id, recordLineIndex: node.recordLineIndex,
109
+ messageIndex: node.messageIndex, role: node.role, estimatedTokens,
110
+ categories: counts, preview: preview(text) };
111
+ top.push(summary);
112
+ top.sort((a, b) => b.estimatedTokens - a.estimatedTokens || a.id.localeCompare(b.id));
113
+ if (top.length > TOP_CANDIDATES) top.pop();
114
+ if (ERROR_PATTERN.test(text) && (estimatedTokens >= LONG_ERROR_TOKENS || text.split('\n').length >= LONG_ERROR_LINES)) {
115
+ mark(summary, 'long_error_log');
116
+ }
117
+ for (const file of node.readPaths || []) {
118
+ const previous = files.get(file);
119
+ if (previous) {
120
+ previous.count++;
121
+ mark(previous.first, 'repeated_file_read');
122
+ mark(summary, 'repeated_file_read');
123
+ } else files.set(file, { count: 1, first: summary });
124
+ }
125
+ },
126
+ finish() {
127
+ for (const node of top) {
128
+ if (node.estimatedTokens > totalEstimatedTokens * DOMINANT_SHARE) mark(node, 'dominant_message');
129
+ }
130
+ const percentage = (tokens) => totalEstimatedTokens ? tokens * 100 / totalEstimatedTokens : 0;
131
+ const describe = (node) => ({ ...node, percentage: percentage(node.estimatedTokens),
132
+ reasons: hotspots.get(node.id)?.reasons || [] });
133
+ return {
134
+ estimator: 'cjk-1-non-cjk-4-v1', estimated: true, messageCount, totalEstimatedTokens,
135
+ health: contextHealthLevel(totalEstimatedTokens),
136
+ categories: CONTEXT_CATEGORIES.map((id) => ({ id, ...totals[id], percentage: percentage(totals[id].estimatedTokens) })),
137
+ topMessages: top.slice(0, 5).map(describe),
138
+ hotspots: [...hotspots.values()].map(describe),
139
+ duplicateFiles: [...files].filter(([, value]) => value.count > 1)
140
+ .map(([path, value]) => ({ path, reads: value.count }))
141
+ };
142
+ }
143
+ };
144
+ }
@@ -1,7 +1,18 @@
1
+ import { buildLineDiff } from '../logic.agents-diff.mjs';
1
2
  import { estimatePromptTokenCount, buildPromptTokenDiffStats } from '../logic.prompts-token-count.mjs';
2
3
 
3
4
  export function createPromptsComputed() {
4
5
  return {
6
+ promptHistoryComparison() {
7
+ return buildLineDiff(this.promptHistoryPreviewContent, this.agentsContent);
8
+ },
9
+ sysHistoryComparison() {
10
+ return buildLineDiff(this.sysHistoryPreviewContent, this.sysPromptContent);
11
+ },
12
+ pluginHistoryComparison() {
13
+ const templates = this.promptTemplatesListRaw.filter((item) => item.isBuiltin !== true);
14
+ return buildLineDiff(this.pluginHistoryContent, JSON.stringify({ version: 1, templates }, null, 2) + '\n');
15
+ },
5
16
  agentsTokenCount() {
6
17
  return estimatePromptTokenCount(this.agentsContent);
7
18
  },
@@ -908,7 +908,10 @@ export function createAgentsMethods(options = {}) {
908
908
  },
909
909
  async applyPromptPresetToEditor(preset) {
910
910
  if (!preset || typeof preset.content !== 'string' || !preset.content) return;
911
- this.agentsContent = preset.content;
911
+ const content = typeof this.resolvePromptTemplateInvocation === 'function'
912
+ ? await this.resolvePromptTemplateInvocation({ template: preset.content }) : preset.content;
913
+ if (content === null) return;
914
+ this.agentsContent = content;
912
915
  this.onAgentsContentInput();
913
916
  this.selectedPromptPresetId = preset.id;
914
917
  this.showMessage(this.t('prompts.presets.toast.pasted'), 'success');
@@ -981,6 +984,8 @@ export function createAgentsMethods(options = {}) {
981
984
  ? bucketArg.trim()
982
985
  : (this.promptHistoryBucket || resolveAgentsHistoryBucket(this));
983
986
  this.promptHistoryBucket = bucket;
987
+ const requestToken = Symbol('history-list');
988
+ this._promptHistoryRequestToken = requestToken;
984
989
  this.promptHistoryLoading = true;
985
990
  this.promptHistoryError = '';
986
991
  this.promptHistoryItems = [];
@@ -988,20 +993,24 @@ export function createAgentsMethods(options = {}) {
988
993
  this.promptHistoryPreviewContent = '';
989
994
  try {
990
995
  const res = await api('list-prompt-history', { bucket });
996
+ if (this._promptHistoryRequestToken !== requestToken || !this.promptHistoryVisible || this.promptHistoryBucket !== bucket) return;
991
997
  if (res && res.error) {
992
998
  this.promptHistoryError = res.error;
993
999
  return;
994
1000
  }
995
1001
  this.promptHistoryItems = Array.isArray(res) ? res : [];
996
1002
  } catch (e) {
1003
+ if (this._promptHistoryRequestToken !== requestToken) return;
997
1004
  this.promptHistoryError = this.t('toast.load.fail');
998
1005
  } finally {
999
- this.promptHistoryLoading = false;
1006
+ if (this._promptHistoryRequestToken === requestToken) this.promptHistoryLoading = false;
1000
1007
  }
1001
1008
  },
1002
1009
 
1003
1010
  closePromptHistory() {
1004
1011
  this.promptHistoryVisible = false;
1012
+ this._promptHistoryRequestToken = null;
1013
+ this.promptHistoryLoading = false;
1005
1014
  this.promptHistoryPreviewId = '';
1006
1015
  this.promptHistoryPreviewContent = '';
1007
1016
  this.promptHistoryError = '';
@@ -1011,10 +1020,15 @@ export function createAgentsMethods(options = {}) {
1011
1020
  if (!item || !item.id) return;
1012
1021
  if (this.promptHistoryLoading) return;
1013
1022
  if (this.promptHistoryPreviewId === item.id && this.promptHistoryPreviewContent) return;
1023
+ const bucket = this.promptHistoryBucket;
1024
+ const requestToken = Symbol('history-preview');
1025
+ this._promptHistoryRequestToken = requestToken;
1026
+ this.promptHistoryLoading = true;
1014
1027
  this.promptHistoryPreviewId = item.id;
1015
1028
  this.promptHistoryPreviewContent = '';
1016
1029
  try {
1017
- const res = await api('get-prompt-history', { bucket: this.promptHistoryBucket, id: item.id });
1030
+ const res = await api('get-prompt-history', { bucket, id: item.id });
1031
+ if (this._promptHistoryRequestToken !== requestToken || !this.promptHistoryVisible || this.promptHistoryBucket !== bucket) return;
1018
1032
  if (res && res.error) {
1019
1033
  this.promptHistoryError = res.error;
1020
1034
  this.promptHistoryPreviewId = '';
@@ -1022,8 +1036,11 @@ export function createAgentsMethods(options = {}) {
1022
1036
  }
1023
1037
  this.promptHistoryPreviewContent = typeof res.content === 'string' ? res.content : '';
1024
1038
  } catch (e) {
1039
+ if (this._promptHistoryRequestToken !== requestToken) return;
1025
1040
  this.promptHistoryError = this.t('toast.load.fail');
1026
1041
  this.promptHistoryPreviewId = '';
1042
+ } finally {
1043
+ if (this._promptHistoryRequestToken === requestToken) this.promptHistoryLoading = false;
1027
1044
  }
1028
1045
  },
1029
1046
 
@@ -36,6 +36,8 @@ import { createSessionTrashMethods } from './app.methods.session-trash.mjs';
36
36
  import { createStartupClaudeMethods } from './app.methods.startup-claude.mjs';
37
37
  import { createSkillsMethods } from './skills.methods.mjs';
38
38
  import { createPluginsMethods } from './plugins.methods.mjs';
39
+ import { createPromptEcosystemMethods } from './prompt-ecosystem.methods.mjs';
40
+ import { createContextHealthMethods } from './context-health.methods.mjs';
39
41
  import { createI18nMethods } from './i18n.mjs';
40
42
  import { createWebhookMethods } from './app.methods.webhook.mjs';
41
43
  import { createWebUiPreferencesMethods } from './app.methods.web-ui-preferences.mjs';
@@ -90,6 +92,8 @@ export function createAppMethods() {
90
92
  }),
91
93
  ...createSkillsMethods({ api }),
92
94
  ...createPluginsMethods(),
95
+ ...createPromptEcosystemMethods({ api }),
96
+ ...createContextHealthMethods({ api }),
93
97
  ...createAgentsMethods({ api, apiWithMeta }),
94
98
  ...createSystemPromptMethods({ api, apiWithMeta }),
95
99
  ...createProvidersMethods({ api }),
@@ -76,6 +76,7 @@ export function createSystemPromptMethods(options = {}) {
76
76
  this.sysPromptPath = res.path || '';
77
77
  this.sysPromptExists = !!res.exists;
78
78
  this.sysPromptHash = res.hash || '';
79
+ this.sysHistoryBucket = res.historyBucket || '';
79
80
  } catch (e) {
80
81
  if (!isLatestRequestToken(this, '_sysPromptOpenRequestToken', requestToken)) return;
81
82
  this.showMessage(this.t('toast.load.fail'), 'error');
@@ -309,6 +310,8 @@ export function createSystemPromptMethods(options = {}) {
309
310
  ? bucketArg.trim()
310
311
  : this.resolveSysHistoryBucket();
311
312
  this.sysHistoryBucket = bucket;
313
+ const requestToken = Symbol('history-list');
314
+ this._sysHistoryRequestToken = requestToken;
312
315
  this.sysHistoryLoading = true;
313
316
  this.sysHistoryError = '';
314
317
  this.sysHistoryItems = [];
@@ -316,20 +319,24 @@ export function createSystemPromptMethods(options = {}) {
316
319
  this.sysHistoryPreviewContent = '';
317
320
  try {
318
321
  const res = await api('list-prompt-history', { bucket });
322
+ if (this._sysHistoryRequestToken !== requestToken || !this.sysHistoryVisible || this.sysHistoryBucket !== bucket) return;
319
323
  if (res && res.error) {
320
324
  this.sysHistoryError = res.error;
321
325
  return;
322
326
  }
323
327
  this.sysHistoryItems = Array.isArray(res) ? res : [];
324
328
  } catch (e) {
329
+ if (this._sysHistoryRequestToken !== requestToken) return;
325
330
  this.sysHistoryError = this.t('toast.load.fail');
326
331
  } finally {
327
- this.sysHistoryLoading = false;
332
+ if (this._sysHistoryRequestToken === requestToken) this.sysHistoryLoading = false;
328
333
  }
329
334
  },
330
335
 
331
336
  closeSysHistory() {
332
337
  this.sysHistoryVisible = false;
338
+ this._sysHistoryRequestToken = null;
339
+ this.sysHistoryLoading = false;
333
340
  this.sysHistoryPreviewId = '';
334
341
  this.sysHistoryPreviewContent = '';
335
342
  this.sysHistoryError = '';
@@ -339,10 +346,15 @@ export function createSystemPromptMethods(options = {}) {
339
346
  if (!item || !item.id) return;
340
347
  if (this.sysHistoryLoading) return;
341
348
  if (this.sysHistoryPreviewId === item.id && this.sysHistoryPreviewContent) return;
349
+ const bucket = this.sysHistoryBucket;
350
+ const requestToken = Symbol('history-preview');
351
+ this._sysHistoryRequestToken = requestToken;
352
+ this.sysHistoryLoading = true;
342
353
  this.sysHistoryPreviewId = item.id;
343
354
  this.sysHistoryPreviewContent = '';
344
355
  try {
345
- const res = await api('get-prompt-history', { bucket: this.sysHistoryBucket, id: item.id });
356
+ const res = await api('get-prompt-history', { bucket, id: item.id });
357
+ if (this._sysHistoryRequestToken !== requestToken || !this.sysHistoryVisible || this.sysHistoryBucket !== bucket) return;
346
358
  if (res && res.error) {
347
359
  this.sysHistoryError = res.error;
348
360
  this.sysHistoryPreviewId = '';
@@ -350,8 +362,11 @@ export function createSystemPromptMethods(options = {}) {
350
362
  }
351
363
  this.sysHistoryPreviewContent = typeof res.content === 'string' ? res.content : '';
352
364
  } catch (e) {
365
+ if (this._sysHistoryRequestToken !== requestToken) return;
353
366
  this.sysHistoryError = this.t('toast.load.fail');
354
367
  this.sysHistoryPreviewId = '';
368
+ } finally {
369
+ if (this._sysHistoryRequestToken === requestToken) this.sysHistoryLoading = false;
355
370
  }
356
371
  },
357
372