codexmate 0.1.31 → 0.1.33

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 (92) hide show
  1. package/README.md +8 -3
  2. package/README.vi.md +8 -3
  3. package/README.zh.md +8 -3
  4. package/cli/agents-files.js +18 -4
  5. package/cli/claude-proxy.js +2 -2
  6. package/cli/plugin-config.js +64 -0
  7. package/cli/prompt-history.js +19 -4
  8. package/cli/system-prompt-files.js +7 -2
  9. package/cli.js +200 -214
  10. package/lib/cli-config-engine.js +15 -4
  11. package/lib/cli-file-utils.js +6 -1
  12. package/lib/config-change-fs.js +132 -0
  13. package/lib/config-changes.js +293 -0
  14. package/lib/handoff-mcp.js +18 -2
  15. package/lib/local-feature-store.js +39 -0
  16. package/lib/session-bookmarks.js +72 -0
  17. package/lib/session-context-health.js +102 -0
  18. package/lib/session-context-records.js +153 -0
  19. package/lib/session-diagnostics.js +75 -0
  20. package/lib/session-feature-settings.js +21 -0
  21. package/lib/session-features.js +63 -0
  22. package/lib/session-handoff-draft.js +43 -0
  23. package/lib/session-projects.js +76 -0
  24. package/lib/session-search-index.js +188 -0
  25. package/lib/thread-handoff.js +8 -0
  26. package/lib/web-server.js +216 -0
  27. package/lib/web-startup-auth.js +5 -1
  28. package/package.json +1 -1
  29. package/plugins/prompt-templates/computed.mjs +3 -3
  30. package/plugins/prompt-templates/invocation.mjs +73 -0
  31. package/plugins/prompt-templates/methods.mjs +48 -3
  32. package/plugins/prompt-templates/overview.mjs +2 -0
  33. package/web-ui/app.js +32 -1
  34. package/web-ui/index.html +2 -0
  35. package/web-ui/logic.context-health.mjs +144 -0
  36. package/web-ui/logic.context-window.mjs +15 -0
  37. package/web-ui/modules/api.mjs +72 -39
  38. package/web-ui/modules/app.computed.prompts.mjs +11 -0
  39. package/web-ui/modules/app.methods.agents.mjs +25 -3
  40. package/web-ui/modules/app.methods.claude-config.mjs +2 -0
  41. package/web-ui/modules/app.methods.codex-config.mjs +9 -0
  42. package/web-ui/modules/app.methods.config-changes.mjs +124 -0
  43. package/web-ui/modules/app.methods.index.mjs +4 -0
  44. package/web-ui/modules/app.methods.kilocode-config.mjs +2 -0
  45. package/web-ui/modules/app.methods.openclaw-persist.mjs +2 -0
  46. package/web-ui/modules/app.methods.opencode-config.mjs +2 -0
  47. package/web-ui/modules/app.methods.pi-config.mjs +12 -3
  48. package/web-ui/modules/app.methods.provider-cache.mjs +9 -3
  49. package/web-ui/modules/app.methods.providers.mjs +6 -0
  50. package/web-ui/modules/app.methods.startup-claude.mjs +8 -47
  51. package/web-ui/modules/app.methods.system-prompt.mjs +17 -2
  52. package/web-ui/modules/config-change-actions.mjs +9 -0
  53. package/web-ui/modules/context-health.methods.mjs +70 -0
  54. package/web-ui/modules/i18n/locales/en.mjs +164 -4
  55. package/web-ui/modules/i18n/locales/ja.mjs +164 -4
  56. package/web-ui/modules/i18n/locales/vi.mjs +164 -4
  57. package/web-ui/modules/i18n/locales/zh-tw.mjs +164 -4
  58. package/web-ui/modules/i18n/locales/zh.mjs +164 -4
  59. package/web-ui/modules/plugins.methods.mjs +2 -0
  60. package/web-ui/modules/prompt-ecosystem.methods.mjs +136 -0
  61. package/web-ui/modules/request-deadline.mjs +33 -0
  62. package/web-ui/modules/session-features.mjs +279 -0
  63. package/web-ui/modules/thread-handoff.mjs +1 -1
  64. package/web-ui/partials/index/config-changes.html +25 -0
  65. package/web-ui/partials/index/context-health.html +45 -0
  66. package/web-ui/partials/index/context-window-reference.html +17 -0
  67. package/web-ui/partials/index/layout-header.html +7 -30
  68. package/web-ui/partials/index/modal-openclaw-config.html +0 -2
  69. package/web-ui/partials/index/modal-prompt-invocation.html +17 -0
  70. package/web-ui/partials/index/modal-skills.html +0 -1
  71. package/web-ui/partials/index/modals-basic.html +0 -8
  72. package/web-ui/partials/index/modals-pi-provider.html +0 -1
  73. package/web-ui/partials/index/panel-config-codex.html +0 -3
  74. package/web-ui/partials/index/panel-config-openclaw.html +16 -13
  75. package/web-ui/partials/index/panel-dashboard.html +0 -2
  76. package/web-ui/partials/index/panel-plugins.html +37 -10
  77. package/web-ui/partials/index/panel-prompts.html +18 -3
  78. package/web-ui/partials/index/panel-sessions.html +23 -11
  79. package/web-ui/partials/index/panel-settings.html +1 -12
  80. package/web-ui/partials/index/panel-trash.html +0 -1
  81. package/web-ui/partials/index/session-diagnostics.html +29 -0
  82. package/web-ui/partials/index/session-features.html +107 -0
  83. package/web-ui/partials/index/thread-handoff.html +6 -3
  84. package/web-ui/res/web-ui-render.precompiled.js +1863 -271
  85. package/web-ui/styles/config-changes.css +30 -0
  86. package/web-ui/styles/context-health.css +107 -0
  87. package/web-ui/styles/openclaw-structured.css +205 -189
  88. package/web-ui/styles/prompts-editor.css +23 -0
  89. package/web-ui/styles/session-features.css +148 -0
  90. package/web-ui/styles/sessions-preview.css +21 -0
  91. package/web-ui/styles/sub-tabs.css +181 -0
  92. package/web-ui/styles.css +5 -1
@@ -0,0 +1,188 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const readline = require('readline');
5
+ const crypto = require('crypto');
6
+ const { createLocalFeatureStore, digest } = require('./local-feature-store');
7
+ const { projectKey } = require('./session-bookmarks');
8
+ const SOURCES = ['codex', 'claude', 'gemini', 'codebuddy', 'workbuddy', 'pi', 'opencode', 'zed'];
9
+ const DEFAULT_DISCOVERY_LIMIT = 3000;
10
+ const MAX_DISCOVERY_LIMIT = 10000;
11
+ const MAX_RESULTS = 100;
12
+ const SNIPPET_LENGTH = 1200;
13
+ const BLOOM_BYTES = 256;
14
+
15
+ async function fileRevision(session) {
16
+ if (session.source === 'opencode' || session.source === 'zed') return null;
17
+ const hash = crypto.createHash('sha256');
18
+ for await (const chunk of fs.createReadStream(session.filePath)) hash.update(chunk);
19
+ return hash.digest('hex');
20
+ }
21
+ async function* readShard(file) {
22
+ const stream = fs.createReadStream(file, { encoding: 'utf8' });
23
+ const lines = readline.createInterface({ input: stream, crlfDelay: Infinity });
24
+ let failure;
25
+ stream.on('error', (error) => { failure = error; lines.close(); });
26
+ try {
27
+ for await (const line of lines) if (line) yield JSON.parse(line);
28
+ if (failure) throw failure;
29
+ } finally { lines.close(); stream.destroy(); }
30
+ }
31
+ function createSessionSearchIndex({ root, inventory, nodes }) {
32
+ const directory = path.join(root, 'index');
33
+ const store = createLocalFeatureStore(path.join(directory, 'catalog.json'), { version: 1, items: [], failures: [], coverage: [] });
34
+ let job = { status: 'idle', processed: 0, candidates: 0, failures: [] };
35
+ let activePromise;
36
+ let activeSearches = 0;
37
+ function status() {
38
+ const snapshot = store.read().value;
39
+ return { job: { ...job, failures: [...job.failures] }, indexed: snapshot.items.length,
40
+ failures: snapshot.failures, coverage: snapshot.coverage, updatedAt: snapshot.updatedAt || '' };
41
+ }
42
+ async function writeShard(session, before) {
43
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
44
+ const temporary = path.join(directory, `${crypto.randomBytes(16).toString('hex')}.tmp`);
45
+ const output = await fs.promises.open(temporary, 'wx', 0o600);
46
+ const hash = crypto.createHash('sha256');
47
+ const bloom = Buffer.alloc(BLOOM_BYTES);
48
+ let count = 0;
49
+ let previous = '';
50
+ let pending;
51
+ async function emit(nextText) {
52
+ const line = JSON.stringify({ ...pending, before: previous, after: nextText.slice(0, SNIPPET_LENGTH) }) + '\n';
53
+ hash.update(line); await output.write(line); previous = pending.text.slice(-SNIPPET_LENGTH);
54
+ const text = `${session.title || ''}\n${pending.text}`.toLowerCase();
55
+ for (let index = 0; index + 1 < text.length; index++) {
56
+ const bit = (text.charCodeAt(index) * 31 + text.charCodeAt(index + 1)) % (BLOOM_BYTES * 8);
57
+ bloom[bit >> 3] |= 1 << (bit & 7);
58
+ }
59
+ }
60
+ try {
61
+ for await (const node of nodes(session)) {
62
+ if (job.cancelled) throw new Error('index-cancelled');
63
+ if (pending) await emit(node.text);
64
+ pending = { id: node.id, role: node.role, text: node.text, textHash: digest(node.text), timestamp: node.timestamp };
65
+ count++;
66
+ }
67
+ if (pending) await emit('');
68
+ if (before !== null && await fileRevision(session) !== before) throw new Error('index-source-changed');
69
+ await output.close();
70
+ const shard = `${digest(JSON.stringify([session.source, session.sessionId, session.filePath, hash.digest('hex')]))}.jsonl`;
71
+ await fs.promises.rename(temporary, path.join(directory, shard));
72
+ await fs.promises.writeFile(path.join(directory, shard + '.bloom'), bloom, { mode: 0o600 });
73
+ return { shard, count };
74
+ } finally {
75
+ await output.close();
76
+ if (fs.existsSync(temporary)) await fs.promises.unlink(temporary);
77
+ }
78
+ }
79
+ async function refresh(params) {
80
+ let snapshot;
81
+ try { snapshot = store.read(); }
82
+ catch (error) {
83
+ if (!params.rebuild) throw error;
84
+ const catalog = path.join(directory, 'catalog.json');
85
+ if (fs.lstatSync(catalog).isSymbolicLink()) throw new Error('feature-store-invalid');
86
+ fs.renameSync(catalog, catalog + '.invalid-' + Date.now());
87
+ snapshot = store.read();
88
+ params = { ...params, source: 'all' };
89
+ }
90
+ const sources = !params.source || params.source === 'all' ? SOURCES : [params.source];
91
+ if (sources.some((source) => !SOURCES.includes(source))) throw new Error('index-source-invalid');
92
+ const limit = Math.min(MAX_DISCOVERY_LIMIT, Math.max(1, Number(params.limit) || DEFAULT_DISCOVERY_LIMIT));
93
+ const entries = snapshot.value.items.filter((item) => !sources.includes(item.source));
94
+ const failures = snapshot.value.failures.filter((item) => !sources.includes(item.source));
95
+ const coverage = snapshot.value.coverage.filter((item) => !sources.includes(item.source));
96
+ for (const source of sources) {
97
+ if (job.cancelled) throw new Error('index-cancelled');
98
+ let sessions;
99
+ try { sessions = await inventory(source, limit); }
100
+ catch (_) { failures.push({ source, code: 'index-source-unavailable' }); continue; }
101
+ job.candidates += sessions.length;
102
+ coverage.push({ source, candidates: sessions.length, discoveryLimit: limit, scope: 'discovered-candidates' });
103
+ for (const session of sessions) {
104
+ if (job.cancelled) throw new Error('index-cancelled');
105
+ try {
106
+ const revision = await fileRevision(session);
107
+ const key = digest(JSON.stringify([source, session.sessionId, session.filePath]));
108
+ const old = snapshot.value.items.find((item) => item.key === key);
109
+ const cached = params.rebuild !== true && revision !== null && /^[a-f0-9]{64}\.jsonl$/.test(old?.shard || '') && old?.revision === revision && fs.existsSync(path.join(directory, old.shard));
110
+ const shard = cached ? { shard: old.shard, count: old.count } : await writeShard(session, revision);
111
+ entries.push({ key, source, sessionId: session.sessionId || '', filePath: session.filePath || '',
112
+ cwd: session.cwd || '', title: session.title || '', timestamp: session.updatedAt || session.timestamp || '', updatedAt: session.updatedAt || session.timestamp || '', revision, ...shard });
113
+ } catch (_) { failures.push({ source, sessionId: session.sessionId || '', code: 'index-source-unavailable' }); }
114
+ job.processed++; job.failures = failures;
115
+ }
116
+ }
117
+ if (job.cancelled) throw new Error('index-cancelled');
118
+ store.write({ version: 1, items: entries, failures, coverage, updatedAt: new Date().toISOString() }, snapshot.revision);
119
+ }
120
+ async function pruneShards() {
121
+ if (activeSearches || !fs.existsSync(directory)) return;
122
+ const keep = new Set(store.read().value.items.flatMap((item) => [item.shard, item.shard + '.bloom']));
123
+ for (const name of await fs.promises.readdir(directory)) {
124
+ if (/^[a-f0-9]{64}\.jsonl(?:\.bloom)?$/.test(name) && !keep.has(name)) await fs.promises.unlink(path.join(directory, name));
125
+ }
126
+ }
127
+ function start(params = {}) {
128
+ if (job.status === 'running') throw new Error('index-busy');
129
+ if (params.rebuild !== undefined && typeof params.rebuild !== 'boolean') throw new Error('index-input-invalid');
130
+ if (params.source && params.source !== 'all' && !SOURCES.includes(params.source)) throw new Error('index-source-invalid');
131
+ if (params.limit !== undefined && (!Number.isSafeInteger(params.limit) || params.limit < 1 || params.limit > MAX_DISCOVERY_LIMIT)) throw new Error('index-input-invalid');
132
+ job = { status: 'running', processed: 0, candidates: 0, failures: [], cancelled: false };
133
+ activePromise = refresh(params).finally(pruneShards).then(() => { job.status = job.failures.length ? 'partial' : 'success'; }).catch((error) => { job.status = job.cancelled ? 'cancelled' : 'failed';
134
+ job.errorCode = /^index-/.test(error.message) ? error.message : 'index-refresh-failed'; });
135
+ return status();
136
+ }
137
+ function cancel() { if (job.status === 'running') job.cancelled = true; return status(); }
138
+ async function search(params = {}) {
139
+ const query = String(params.query || '').trim().toLowerCase();
140
+ if (!query) throw new Error('index-query-empty');
141
+ const tokens = query.split(/\s+/).filter(Boolean);
142
+ const snapshot = store.read().value;
143
+ const items = snapshot.items.filter((item) => (!params.source || params.source === 'all' || item.source === params.source)
144
+ && (!params.project || projectKey(item.cwd) === projectKey(params.project)));
145
+ const results = [];
146
+ const failures = [...snapshot.failures];
147
+ let scanned = 0;
148
+ let truncated = false;
149
+ activeSearches++;
150
+ try {
151
+ for (const session of items) {
152
+ if (!/^[a-f0-9]{64}\.jsonl$/.test(session.shard)) throw new Error('feature-store-invalid');
153
+ try {
154
+ const bloomPath = path.join(directory, session.shard + '.bloom');
155
+ if (fs.existsSync(bloomPath)) {
156
+ const bloom = await fs.promises.readFile(bloomPath);
157
+ const absent = (token) => {
158
+ for (let index = 0; index + 1 < token.length; index++) {
159
+ const bit = (token.charCodeAt(index) * 31 + token.charCodeAt(index + 1)) % (BLOOM_BYTES * 8);
160
+ if (!(bloom[bit >> 3] & (1 << (bit & 7)))) return true;
161
+ }
162
+ return false;
163
+ };
164
+ const skip = params.mode === 'any' ? tokens.every(absent) : tokens.some(absent);
165
+ if (bloom.length === BLOOM_BYTES && skip) { scanned++; continue; }
166
+ }
167
+ for await (const node of readShard(path.join(directory, session.shard))) {
168
+ if (params.role && params.role !== 'all' && node.role !== params.role) continue;
169
+ const text = `${params.scope === 'all' ? session.title : ''}\n${node.text}`.toLowerCase();
170
+ const hit = params.mode === 'any' ? tokens.some((token) => text.includes(token)) : tokens.every((token) => text.includes(token));
171
+ if (!hit) continue;
172
+ if (results.length >= MAX_RESULTS) { truncated = true; break; }
173
+ const position = node.text.toLowerCase().indexOf(tokens[0]);
174
+ results.push({ session, nodeId: node.id, textHash: node.textHash, role: node.role,
175
+ snippet: node.text.slice(Math.max(0, position - SNIPPET_LENGTH / 4), Math.max(0, position - SNIPPET_LENGTH / 4) + SNIPPET_LENGTH),
176
+ before: node.before, after: node.after });
177
+ }
178
+ scanned++;
179
+ } catch (_) { failures.push({ source: session.source, sessionId: session.sessionId, code: 'index-shard-unavailable' }); }
180
+ if (truncated) break;
181
+ }
182
+ } finally { activeSearches--; }
183
+ return { results, truncated, scanned, candidates: items.length, failures, coverage: snapshot.coverage,
184
+ complete: scanned === items.length && !failures.length && !truncated, scope: 'indexed-discovered-candidates' };
185
+ }
186
+ return { status, start, cancel, search, wait: () => activePromise };
187
+ }
188
+ module.exports = { createSessionSearchIndex, SOURCES };
@@ -57,6 +57,14 @@ async function createHandoff(params, options = {}) {
57
57
  const handoff = { id, threadId: params.threadId, target: params.target, createdAt, card,
58
58
  acknowledgement: { command: `codexmate thread ack ${params.threadId} --handoff ${id} --agent ${params.target} --evidence <读取证据>`,
59
59
  instruction: '目标 Agent 实际读取本卡后,使用原始 threadId、id、target 调用 thread ack;evidence 填写目标会话或检索记录标识。此确认为目标自报,非自动验证。' } };
60
+ if (params.evidence !== undefined) {
61
+ if (!Array.isArray(params.evidence) || params.evidence.length > 100 || params.evidence.some((item) =>
62
+ !item || typeof item.nodeId !== 'string' || typeof item.source !== 'string' || typeof item.excerpt !== 'string'
63
+ || item.excerpt.length > 800 || !/^[a-f0-9]{64}$/.test(item.textHash || ''))) throw new Error('交接证据格式无效');
64
+ handoff.evidence = params.evidence.map((item) => ({ source: item.source, sessionId: item.sessionId || '',
65
+ nodeId: item.nodeId, textHash: item.textHash, excerpt: item.excerpt, status: item.status,
66
+ origin: 'user_reviewed_selection' }));
67
+ }
60
68
  fs.mkdirSync(directory, { recursive: true });
61
69
  const filePath = path.join(directory, `${id}.json`);
62
70
  fs.writeFileSync(filePath, JSON.stringify(handoff, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
@@ -0,0 +1,216 @@
1
+ function createWebServerLifecycle(options, dependencies) {
2
+ const { server, host, port, httpToken, openBrowser } = options;
3
+ const { http, spawn, process, console, setTimeout, formatHostForUrl, DEFAULT_WEB_OPEN_HOST, isAnyAddressHost, getUnattendedWorkflowRunner } = dependencies;
4
+ const connections = new Set();
5
+
6
+ const probeWebUiReadiness = (callback) => {
7
+ const payload = JSON.stringify({ action: 'health-check', params: {} });
8
+ const requestOptions = {
9
+ hostname: openHost,
10
+ port,
11
+ path: '/api',
12
+ method: 'POST',
13
+ headers: {
14
+ 'Content-Type': 'application/json; charset=utf-8',
15
+ 'Content-Length': Buffer.byteLength(payload, 'utf-8'),
16
+ ...(httpToken ? { Authorization: `Bearer ${httpToken}` } : {})
17
+ }
18
+ };
19
+ let settled = false;
20
+ const finish = (ready) => {
21
+ if (settled) return;
22
+ settled = true;
23
+ callback(ready);
24
+ };
25
+ const req = http.request(requestOptions, (probeRes) => {
26
+ if (typeof probeRes.resume === 'function') {
27
+ probeRes.resume();
28
+ }
29
+ probeRes.on('end', () => {
30
+ finish(probeRes.statusCode === 200);
31
+ });
32
+ });
33
+ req.on('error', () => finish(false));
34
+ req.setTimeout(1000, () => {
35
+ try { req.destroy(); } catch (_) { }
36
+ finish(false);
37
+ });
38
+ req.end(payload, 'utf-8');
39
+ };
40
+
41
+ const probeWebUiAssetReadiness = (callback) => {
42
+ const requestOptions = {
43
+ hostname: openHost,
44
+ port,
45
+ path: '/web-ui/app.js',
46
+ method: 'GET',
47
+ headers: httpToken ? { Authorization: `Bearer ${httpToken}` } : {}
48
+ };
49
+ let settled = false;
50
+ const finish = (ready) => {
51
+ if (settled) return;
52
+ settled = true;
53
+ callback(ready);
54
+ };
55
+ const req = http.request(requestOptions, (probeRes) => {
56
+ if (typeof probeRes.resume === 'function') {
57
+ probeRes.resume();
58
+ }
59
+ probeRes.on('end', () => {
60
+ finish(probeRes.statusCode === 200);
61
+ });
62
+ });
63
+ req.on('error', () => finish(false));
64
+ req.setTimeout(1000, () => {
65
+ try { req.destroy(); } catch (_) { }
66
+ finish(false);
67
+ });
68
+ req.end();
69
+ };
70
+
71
+ const openBrowserAfterReady = (url) => {
72
+ // Some environments may start the listener before the bundled web-ui assets
73
+ // are ready for the first browser hit; wait until both API and assets respond.
74
+ const maxAttempts = 120;
75
+ const retryDelayMs = 200;
76
+ let finished = false;
77
+
78
+ const finish = (ready) => {
79
+ if (finished) return;
80
+ finished = true;
81
+ if (!ready) {
82
+ console.warn('! Web UI 就绪探测超时,未自动打开浏览器,请手动访问:', url);
83
+ return;
84
+ }
85
+
86
+ const platform = process.platform;
87
+ const commandSpec = platform === 'win32'
88
+ ? { command: 'cmd', args: ['/c', 'start', '', url] }
89
+ : (platform === 'darwin'
90
+ ? { command: 'open', args: [url] }
91
+ : { command: 'xdg-open', args: [url] });
92
+
93
+ try {
94
+ const child = spawn(commandSpec.command, commandSpec.args, {
95
+ stdio: 'ignore',
96
+ detached: true,
97
+ windowsHide: true
98
+ });
99
+ child.on('error', () => {
100
+ console.warn('无法自动打开浏览器,请手动访问:', url);
101
+ });
102
+ if (typeof child.unref === 'function') {
103
+ child.unref();
104
+ }
105
+ } catch (_) {
106
+ console.warn('无法自动打开浏览器,请手动访问:', url);
107
+ }
108
+ };
109
+ const scheduleProbe = (attempt) => {
110
+ probeWebUiReadiness((apiReady) => {
111
+ if (!apiReady) {
112
+ if (attempt >= maxAttempts) {
113
+ finish(false);
114
+ return;
115
+ }
116
+ setTimeout(() => scheduleProbe(attempt + 1), retryDelayMs);
117
+ return;
118
+ }
119
+ probeWebUiAssetReadiness((assetReady) => {
120
+ if (assetReady) {
121
+ finish(true);
122
+ return;
123
+ }
124
+ if (attempt >= maxAttempts) {
125
+ finish(false);
126
+ return;
127
+ }
128
+ setTimeout(() => scheduleProbe(attempt + 1), retryDelayMs);
129
+ });
130
+ });
131
+ };
132
+
133
+ scheduleProbe(1);
134
+ };
135
+
136
+ server.on('connection', (socket) => {
137
+ connections.add(socket);
138
+ socket.on('close', () => connections.delete(socket));
139
+ });
140
+
141
+ const printPortOverrideHint = () => {
142
+ const examplePort = port === 8080 ? 8081 : 8080;
143
+ console.error(` 临时换端口(macOS/Linux): CODEXMATE_PORT=${examplePort} codexmate run`);
144
+ console.error(` 临时换端口(Windows PowerShell): $env:CODEXMATE_PORT=${examplePort}; codexmate run`);
145
+ console.error(` 临时换端口(Windows CMD): set CODEXMATE_PORT=${examplePort} && codexmate run`);
146
+ };
147
+
148
+ server.once('error', (err) => {
149
+ if (err && err.code === 'EADDRINUSE') {
150
+ console.error(`! 启动失败: 端口 ${port} 已被占用,可能有残留的 codexmate run 实例。`);
151
+ console.error(' 请先停止旧实例或更换端口后重试。');
152
+ printPortOverrideHint();
153
+ } else if (err && err.code === 'EACCES') {
154
+ console.error(`! 启动失败: 没有权限监听 ${host}:${port}。`);
155
+ console.error(' 请检查系统/安全软件限制,或更换端口后重试。');
156
+ printPortOverrideHint();
157
+ } else {
158
+ console.error('! 启动 Web UI 失败:', err && err.message ? err.message : err);
159
+ }
160
+ process.exit(1);
161
+ });
162
+
163
+ const openHost = host === '::'
164
+ ? '::1'
165
+ : (host === '0.0.0.0' ? DEFAULT_WEB_OPEN_HOST : host);
166
+
167
+ const openUrl = `http://${formatHostForUrl(openHost)}:${port}/?token=${encodeURIComponent(httpToken)}`;
168
+
169
+ server.listen(port, host, () => {
170
+ getUnattendedWorkflowRunner().recover();
171
+ console.log('\n✓ Web UI 已启动');
172
+ const willOpenBrowser = !!openBrowser && !process.env.CODEXMATE_NO_BROWSER;
173
+ console.log(` ${willOpenBrowser ? '已打开' : '待访问'}: ${openUrl}`);
174
+ if (host && host !== openHost) {
175
+ console.log(' 监听地址:', host);
176
+ }
177
+ console.log(' 退出: Ctrl+C\n');
178
+ if (isAnyAddressHost(host)) {
179
+ console.warn('! 安全提示: 当前监听所有网卡,局域网访问需要访问令牌。');
180
+ console.warn(' 远程 /bridge/ 请求需携带 Authorization: Bearer <访问令牌>。');
181
+ const allowedIps = (process.env.CODEXMATE_ALLOWED_IPS || '').trim();
182
+ if (allowedIps) {
183
+ console.warn(` 已启用的来源 IP 白名单: ${allowedIps}`);
184
+ }
185
+ }
186
+
187
+ if (willOpenBrowser) {
188
+ openBrowserAfterReady(openUrl);
189
+ }
190
+ });
191
+
192
+ const stop = () => new Promise((resolve) => {
193
+ let done = false;
194
+ const finish = () => {
195
+ if (done) return;
196
+ done = true;
197
+ for (const socket of connections) {
198
+ try { socket.destroy(); } catch (_) { }
199
+ }
200
+ connections.clear();
201
+ resolve();
202
+ };
203
+
204
+ if (!server.listening) {
205
+ finish();
206
+ return;
207
+ }
208
+
209
+ server.close(() => finish());
210
+ setTimeout(() => finish(), 800);
211
+ });
212
+
213
+ return { server, stop };
214
+ }
215
+
216
+ module.exports = { createWebServerLifecycle };
@@ -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.33",
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) {