codexmate 0.1.30 → 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.
- package/README.md +98 -7
- package/README.vi.md +98 -7
- package/README.zh.md +99 -7
- package/cli/agents-files.js +18 -4
- package/cli/config-bootstrap.js +25 -11
- package/cli/plugin-config.js +64 -0
- package/cli/prompt-history.js +17 -4
- package/cli/system-prompt-files.js +7 -2
- package/cli.js +396 -46
- package/lib/cli-config-engine.js +266 -0
- package/lib/cli-utils.js +2 -1
- package/lib/cli-webhook.js +1 -1
- package/lib/handoff-mcp.js +282 -0
- package/lib/http-access-control.js +335 -0
- package/lib/session-context-health.js +82 -0
- package/lib/session-context-records.js +153 -0
- package/lib/thread-handoff.js +130 -0
- package/lib/web-startup-auth.js +53 -0
- package/lib/workflow-engine.js +92 -21
- package/lib/workflow-runner.js +261 -0
- package/package.json +1 -1
- package/plugins/prompt-templates/computed.mjs +3 -3
- package/plugins/prompt-templates/invocation.mjs +73 -0
- package/plugins/prompt-templates/methods.mjs +48 -3
- package/plugins/prompt-templates/overview.mjs +2 -0
- package/web-ui/app.js +48 -2
- package/web-ui/index.html +1 -0
- package/web-ui/logic.context-health.mjs +144 -0
- package/web-ui/modules/access-token.mjs +33 -0
- package/web-ui/modules/api.mjs +2 -1
- package/web-ui/modules/app.computed.prompts.mjs +11 -0
- package/web-ui/modules/app.methods.agents.mjs +20 -3
- package/web-ui/modules/app.methods.index.mjs +6 -0
- package/web-ui/modules/app.methods.navigation.mjs +17 -3
- package/web-ui/modules/app.methods.prompts-editor.mjs +7 -0
- package/web-ui/modules/app.methods.providers.mjs +2 -2
- package/web-ui/modules/app.methods.runtime.mjs +3 -2
- package/web-ui/modules/app.methods.session-actions.mjs +3 -0
- package/web-ui/modules/app.methods.session-browser.mjs +6 -2
- package/web-ui/modules/app.methods.system-prompt.mjs +17 -2
- package/web-ui/modules/app.methods.workflows.mjs +41 -0
- package/web-ui/modules/context-health.methods.mjs +70 -0
- package/web-ui/modules/i18n/locales/en.mjs +70 -2
- package/web-ui/modules/i18n/locales/ja.mjs +70 -2
- package/web-ui/modules/i18n/locales/vi.mjs +70 -2
- package/web-ui/modules/i18n/locales/zh-tw.mjs +70 -2
- package/web-ui/modules/i18n/locales/zh.mjs +70 -2
- package/web-ui/modules/plugins.methods.mjs +2 -0
- package/web-ui/modules/prompt-ecosystem.methods.mjs +136 -0
- package/web-ui/modules/sessions-filters-url.mjs +3 -0
- package/web-ui/modules/skills.methods.mjs +6 -5
- package/web-ui/modules/thread-handoff.mjs +142 -0
- package/web-ui/partials/index/context-health.html +45 -0
- package/web-ui/partials/index/modal-prompt-invocation.html +17 -0
- package/web-ui/partials/index/panel-config-claude.html +2 -0
- package/web-ui/partials/index/panel-config-codex.html +2 -0
- package/web-ui/partials/index/panel-config-kilocode.html +3 -1
- package/web-ui/partials/index/panel-config-openclaw.html +2 -0
- package/web-ui/partials/index/panel-config-opencode.html +3 -1
- package/web-ui/partials/index/panel-config-pi.html +2 -0
- package/web-ui/partials/index/panel-dashboard.html +59 -0
- package/web-ui/partials/index/panel-plugins.html +37 -9
- package/web-ui/partials/index/panel-prompts.html +46 -18
- package/web-ui/partials/index/panel-sessions.html +35 -44
- package/web-ui/partials/index/thread-handoff.html +59 -0
- package/web-ui/res/web-ui-render.precompiled.js +1289 -177
- package/web-ui/styles/context-health.css +107 -0
- package/web-ui/styles/controls-forms.css +9 -0
- package/web-ui/styles/dashboard.css +51 -0
- package/web-ui/styles/modals-core.css +87 -0
- package/web-ui/styles/navigation-panels.css +1 -1
- package/web-ui/styles/plugins-panel.css +62 -0
- package/web-ui/styles/prompts-editor.css +34 -4
- package/web-ui/styles/responsive.css +19 -10
- package/web-ui/styles/sessions-preview.css +206 -111
- package/web-ui/styles/sub-tabs.css +181 -0
- package/web-ui/styles.css +2 -0
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { threadHandoffMixin } from './modules/thread-handoff.mjs';
|
|
1
2
|
import {
|
|
2
3
|
DEFAULT_MODEL_AUTO_COMPACT_TOKEN_LIMIT,
|
|
3
4
|
DEFAULT_MODEL_CONTEXT_WINDOW,
|
|
@@ -57,8 +58,12 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
|
57
58
|
});
|
|
58
59
|
|
|
59
60
|
const appOptions = {
|
|
61
|
+
mixins: [threadHandoffMixin],
|
|
60
62
|
data() {
|
|
61
63
|
return {
|
|
64
|
+
workflowDefinitions: [], workflowRuns: [], workflowId: 'diagnose-config',
|
|
65
|
+
workflowInput: '{}', workflowAllowWrite: false, workflowBusy: false, workflowError: '',
|
|
66
|
+
workflowTimer: null,
|
|
62
67
|
lang: 'zh',
|
|
63
68
|
languageMenuOpen: false,
|
|
64
69
|
appVersion: '',
|
|
@@ -186,6 +191,23 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
|
186
191
|
promptComposerPickerKeyword: '',
|
|
187
192
|
promptComposerSelectedTemplateId: '',
|
|
188
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: '',
|
|
189
211
|
showConfirmDialog: false,
|
|
190
212
|
confirmDialogTitle: '',
|
|
191
213
|
confirmDialogMessage: '',
|
|
@@ -352,6 +374,14 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
|
352
374
|
activeSessionDetailClipped: false,
|
|
353
375
|
sessionDetailLoading: false,
|
|
354
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,
|
|
355
385
|
sessionDetailInitialMessageLimit: 300,
|
|
356
386
|
sessionDetailFetchStep: 300,
|
|
357
387
|
sessionDetailMessageLimit: 80,
|
|
@@ -585,7 +615,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
|
585
615
|
sessionLoadNativeDialog: false,
|
|
586
616
|
starPrompted: false,
|
|
587
617
|
webhookConfig: { enabled: false, url: '', events: ['provider-switch', 'claude-md-edit'] },
|
|
588
|
-
webhookEventOptions: ['provider-switch', 'claude-md-edit'],
|
|
618
|
+
webhookEventOptions: ['provider-switch', 'claude-md-edit', 'workflow-completed', 'workflow-failed', 'workflow-waiting'],
|
|
589
619
|
webhookSaving: false,
|
|
590
620
|
webhookTestResult: null,
|
|
591
621
|
webhookTesting: false,
|
|
@@ -593,6 +623,8 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
|
593
623
|
},
|
|
594
624
|
|
|
595
625
|
mounted() {
|
|
626
|
+
this.refreshWorkflowRuns();
|
|
627
|
+
this.workflowTimer = setInterval(() => this.refreshWorkflowRuns(), 3000);
|
|
596
628
|
// URL 规范化:将 /web-ui/* 重定向到根路径 /
|
|
597
629
|
try {
|
|
598
630
|
const pathname = window.location.pathname;
|
|
@@ -731,7 +763,14 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
|
731
763
|
const runInitialLoad = () => {
|
|
732
764
|
const triggerLoad = async () => {
|
|
733
765
|
this._initialLoadTimer = 0;
|
|
734
|
-
const
|
|
766
|
+
const sessionStartup = this.mainTab === 'sessions';
|
|
767
|
+
if (sessionStartup) {
|
|
768
|
+
this.loading = false;
|
|
769
|
+
if (!this.sessionsLoadedOnce && !this.sessionsLoading) {
|
|
770
|
+
await this.loadSessions();
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
const startupOk = await this.loadAll({ preserveLoading: sessionStartup });
|
|
735
774
|
if (!startupOk) {
|
|
736
775
|
return;
|
|
737
776
|
}
|
|
@@ -758,6 +797,12 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
|
758
797
|
void this.loadProviderCacheRecords({ background: true });
|
|
759
798
|
}
|
|
760
799
|
};
|
|
800
|
+
if (typeof this.scheduleAfterFrame === 'function') {
|
|
801
|
+
this.scheduleAfterFrame(() => {
|
|
802
|
+
this._initialLoadTimer = setTimeout(triggerLoad, 0);
|
|
803
|
+
});
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
761
806
|
if (typeof requestAnimationFrame === 'function') {
|
|
762
807
|
this._initialLoadRafId = requestAnimationFrame(() => {
|
|
763
808
|
this._initialLoadRafId = 0;
|
|
@@ -790,6 +835,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
|
790
835
|
},
|
|
791
836
|
|
|
792
837
|
beforeUnmount() {
|
|
838
|
+
clearInterval(this.workflowTimer);
|
|
793
839
|
this.teardownSessionTabRender();
|
|
794
840
|
this.cancelScheduledSessionTabDeferredTeardown();
|
|
795
841
|
this.disconnectSessionPreviewHeaderResizeObserver();
|
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
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
const accessTokenLocation = typeof location !== 'undefined' ? location : null;
|
|
2
|
+
const initialAccessToken = (() => {
|
|
3
|
+
try { return accessTokenLocation ? new URL(accessTokenLocation.href).searchParams.get('token') || '' : ''; }
|
|
4
|
+
catch (_) { return ''; }
|
|
5
|
+
})();
|
|
6
|
+
|
|
7
|
+
export function getAccessToken() {
|
|
8
|
+
if (!accessTokenLocation) return '';
|
|
9
|
+
try {
|
|
10
|
+
return new URL(accessTokenLocation.href).searchParams.get('token') || initialAccessToken;
|
|
11
|
+
} catch (_) {
|
|
12
|
+
return '';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function withAccessToken(url) {
|
|
17
|
+
const token = getAccessToken();
|
|
18
|
+
if (!token) return url;
|
|
19
|
+
try {
|
|
20
|
+
const parsed = new URL(url, accessTokenLocation && accessTokenLocation.origin ? accessTokenLocation.origin : 'http://localhost');
|
|
21
|
+
parsed.searchParams.set('token', token);
|
|
22
|
+
return parsed.pathname.startsWith('/') && accessTokenLocation && accessTokenLocation.origin
|
|
23
|
+
? `${parsed.pathname}${parsed.search}${parsed.hash}`
|
|
24
|
+
: parsed.toString();
|
|
25
|
+
} catch (_) {
|
|
26
|
+
return url;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function authorizationHeaders(extra = {}) {
|
|
31
|
+
const token = getAccessToken();
|
|
32
|
+
return token ? { ...extra, Authorization: `Bearer ${token}` } : { ...extra };
|
|
33
|
+
}
|
package/web-ui/modules/api.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { authorizationHeaders } from './access-token.mjs';
|
|
1
2
|
const browserLocation = typeof location !== 'undefined' ? location : null;
|
|
2
3
|
|
|
3
4
|
export const API_BASE = (browserLocation && browserLocation.origin && browserLocation.origin !== 'null')
|
|
@@ -7,7 +8,7 @@ export const API_BASE = (browserLocation && browserLocation.origin && browserLoc
|
|
|
7
8
|
async function postApi(action, params = {}) {
|
|
8
9
|
return await fetch(`${API_BASE}/api`, {
|
|
9
10
|
method: 'POST',
|
|
10
|
-
headers: { 'Content-Type': 'application/json' },
|
|
11
|
+
headers: authorizationHeaders({ 'Content-Type': 'application/json' }),
|
|
11
12
|
body: JSON.stringify({ action, params })
|
|
12
13
|
});
|
|
13
14
|
}
|
|
@@ -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.
|
|
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
|
|
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
|
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createWorkflowMethods } from './app.methods.workflows.mjs';
|
|
1
2
|
import {
|
|
2
3
|
API_BASE,
|
|
3
4
|
api,
|
|
@@ -35,6 +36,8 @@ import { createSessionTrashMethods } from './app.methods.session-trash.mjs';
|
|
|
35
36
|
import { createStartupClaudeMethods } from './app.methods.startup-claude.mjs';
|
|
36
37
|
import { createSkillsMethods } from './skills.methods.mjs';
|
|
37
38
|
import { createPluginsMethods } from './plugins.methods.mjs';
|
|
39
|
+
import { createPromptEcosystemMethods } from './prompt-ecosystem.methods.mjs';
|
|
40
|
+
import { createContextHealthMethods } from './context-health.methods.mjs';
|
|
38
41
|
import { createI18nMethods } from './i18n.mjs';
|
|
39
42
|
import { createWebhookMethods } from './app.methods.webhook.mjs';
|
|
40
43
|
import { createWebUiPreferencesMethods } from './app.methods.web-ui-preferences.mjs';
|
|
@@ -53,6 +56,7 @@ import {
|
|
|
53
56
|
export function createAppMethods() {
|
|
54
57
|
return {
|
|
55
58
|
...createI18nMethods(),
|
|
59
|
+
...createWorkflowMethods({ api }),
|
|
56
60
|
...createPromptsEditorMethods({ api }),
|
|
57
61
|
...createWebhookMethods(),
|
|
58
62
|
...createStartupClaudeMethods({
|
|
@@ -88,6 +92,8 @@ export function createAppMethods() {
|
|
|
88
92
|
}),
|
|
89
93
|
...createSkillsMethods({ api }),
|
|
90
94
|
...createPluginsMethods(),
|
|
95
|
+
...createPromptEcosystemMethods({ api }),
|
|
96
|
+
...createContextHealthMethods({ api }),
|
|
91
97
|
...createAgentsMethods({ api, apiWithMeta }),
|
|
92
98
|
...createSystemPromptMethods({ api, apiWithMeta }),
|
|
93
99
|
...createProvidersMethods({ api }),
|
|
@@ -86,8 +86,10 @@
|
|
|
86
86
|
pathname = '/';
|
|
87
87
|
}
|
|
88
88
|
url.pathname = pathname;
|
|
89
|
+
const accessToken = url.searchParams.get('token') || '';
|
|
89
90
|
url.search = '';
|
|
90
91
|
url.hash = '';
|
|
92
|
+
if (accessToken) url.searchParams.set('token', accessToken);
|
|
91
93
|
const nextUrl = url.toString();
|
|
92
94
|
if (nextUrl === window.location.href) return;
|
|
93
95
|
if (window.history && typeof window.history.replaceState === 'function') {
|
|
@@ -610,11 +612,23 @@
|
|
|
610
612
|
|
|
611
613
|
scheduleAfterFrame(task) {
|
|
612
614
|
const callback = typeof task === 'function' ? task : () => {};
|
|
615
|
+
const fallbackDelayMs = 100;
|
|
616
|
+
let completed = false;
|
|
617
|
+
let frameId;
|
|
618
|
+
let timer;
|
|
619
|
+
const run = () => {
|
|
620
|
+
if (completed) return;
|
|
621
|
+
completed = true;
|
|
622
|
+
clearTimeout(timer);
|
|
623
|
+
if (frameId !== undefined && typeof cancelAnimationFrame === 'function') {
|
|
624
|
+
cancelAnimationFrame(frameId);
|
|
625
|
+
}
|
|
626
|
+
callback();
|
|
627
|
+
};
|
|
628
|
+
timer = setTimeout(run, fallbackDelayMs);
|
|
613
629
|
if (typeof requestAnimationFrame === 'function') {
|
|
614
|
-
requestAnimationFrame(
|
|
615
|
-
return;
|
|
630
|
+
frameId = requestAnimationFrame(run);
|
|
616
631
|
}
|
|
617
|
-
setTimeout(callback, 16);
|
|
618
632
|
},
|
|
619
633
|
scheduleIdleTask(task, timeoutMs = 160) {
|
|
620
634
|
const callback = typeof task === 'function' ? task : () => {};
|