@microi.net/cli 5.9.6 → 5.9.8

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 (62) hide show
  1. package/.codebuddy-plugin/marketplace.json +2 -2
  2. package/.codebuddy-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/.mcp.json +1 -1
  5. package/.workbuddy-plugin/marketplace.json +2 -2
  6. package/.workbuddy-plugin/plugin.json +1 -1
  7. package/LICENSE +21 -21
  8. package/README.md +71 -71
  9. package/assets/build-meta.json +7 -7
  10. package/assets/feature-matrix.json +138 -138
  11. package/assets/logo.svg +4 -4
  12. package/cordis.patch.yml +1 -1
  13. package/package.json +1 -1
  14. package/scripts/codex-marketplace.json +20 -20
  15. package/scripts/mcp-codex-stdio-adapter.js +189 -189
  16. package/scripts/mcp-server.js +165 -436
  17. package/scripts/mcp-trae-windows-launcher.cmd +21 -21
  18. package/scripts/microi-cli-mcp.js +7 -7
  19. package/scripts/microi-cli.js +61 -665
  20. package/scripts/microi-codex-broker.js +466 -466
  21. package/scripts/microi-codex-router.js +635 -635
  22. package/scripts/microi-skills.meta.json +237 -237
  23. package/skills/.microi-skills-version.json +2 -2
  24. package/skills/.progressive-disclosure-manifest.json +24 -24
  25. package/skills/ai-engine/agents/openai.yaml +4 -4
  26. package/skills/app-store/agents/openai.yaml +4 -4
  27. package/skills/datasource-engine/agents/openai.yaml +4 -4
  28. package/skills/job-engine/agents/openai.yaml +4 -4
  29. package/skills/message-notification/agents/openai.yaml +5 -5
  30. package/skills/microi-ai-app-auth.js +652 -652
  31. package/skills/microi-ai-application/agents/openai.yaml +4 -4
  32. package/skills/microi-client-frontend/SKILL.md +8 -2
  33. package/skills/microi-codex-installer/agents/openai.yaml +7 -7
  34. package/skills/microi-db-schema/agents/openai.yaml +4 -4
  35. package/skills/microi-deployment/SKILL.md +6 -0
  36. package/skills/microi-docs-coverage/references/capability-map.md +1 -1
  37. package/skills/microi-docs-coverage/scripts/audit-doc-skill-coverage.mjs +894 -894
  38. package/skills/microi-solution-quotation/agents/openai.yaml +4 -4
  39. package/skills/microi-solution-quotation/scripts/build_solution_quote.py +296 -296
  40. package/skills/microi-system-delivery/references/progressive-02-/350/207/252/345/212/250/345/214/226/346/265/213/350/257/225/345/277/205/351/241/273/350/246/206/347/233/226/347/232/204/345/235/221.md +20 -2
  41. package/skills/microi-uniapp-frontend/SKILL.md +5 -1
  42. package/skills/microi.v8.js +1921 -1921
  43. package/skills/module-engine/SKILL.md +10 -0
  44. package/skills/ocr-engine/agents/openai.yaml +4 -4
  45. package/skills/page-engine/examples/compact-dashboard.json +1444 -1444
  46. package/skills/playwright-e2e/SKILL.md +2 -0
  47. package/skills/report-engine/agents/openai.yaml +4 -4
  48. package/skills/scripts/optimize-progressive-disclosure.mjs +204 -204
  49. package/skills/scripts/refresh-progressive-disclosure.mjs +64 -64
  50. package/skills/scripts/sync-embedded-skills.mjs +46 -46
  51. package/skills/scripts/validate-progressive-disclosure.mjs +57 -57
  52. package/skills/search-engine/agents/openai.yaml +4 -4
  53. package/skills/translate-engine/agents/openai.yaml +4 -4
  54. package/skills/ui-design/assets/pattern-showcase/app.js +54 -54
  55. package/skills/ui-design/assets/pattern-showcase/index.html +163 -163
  56. package/skills/ui-design/assets/pattern-showcase/styles.css +311 -311
  57. package/skills/unity-integration/agents/openai.yaml +4 -4
  58. package/skills/v8-image-processing/agents/openai.yaml +4 -4
  59. package/skills/v8-mq-mqtt/scripts/check-mqtt-skill-coverage.mjs +203 -203
  60. package/skills/v8-tcp-integration/agents/openai.yaml +4 -4
  61. package/skills/vision-engine/agents/openai.yaml +4 -4
  62. package/skills/workspace-conventions/SKILL.md +4 -4
@@ -1,466 +1,466 @@
1
- #!/usr/bin/env node
2
- /*
3
- * Shared Microi Agentx MCP broker.
4
- *
5
- * Every Codex task still owns a tiny stdio router, but all routers for the same
6
- * workspace and tool version share this broker. The broker owns at most one
7
- * real MCP child per connection profile, uses an exclusive lease to survive
8
- * concurrent starts, and exits after the last router has been idle.
9
- */
10
-
11
- 'use strict';
12
-
13
- const childProcess = require('node:child_process');
14
- const crypto = require('node:crypto');
15
- const fs = require('node:fs');
16
- const net = require('node:net');
17
- const os = require('node:os');
18
- const path = require('node:path');
19
-
20
- const PROTOCOL_VERSION = '2024-11-05';
21
- const endpoint = String(process.env.MICROI_CODEX_BROKER_ENDPOINT || '');
22
- const leasePath = path.resolve(String(process.env.MICROI_CODEX_BROKER_LEASE || ''));
23
- const workspaceRoot = path.resolve(String(process.env.MICROI_WORKSPACE_ROOT || process.cwd()));
24
- const mcpServerPath = path.resolve(String(process.env.MICROI_MCP_SERVER_PATH || path.join(__dirname, 'mcp-server.js')));
25
- const toolVersion = String(process.env.MICROI_TOOL_VERSION || '0.0.0');
26
- const idleMilliseconds = Math.max(250, Number(process.env.MICROI_CODEX_BROKER_IDLE_MS || 30000));
27
- // The launching router may not get scheduled again immediately on a busy host.
28
- // Do not retire the listening pipe before its first client has had time to join.
29
- const initialClientGraceMilliseconds = Math.max(10000, idleMilliseconds);
30
- const heartbeatMilliseconds = Math.max(500, Number(process.env.MICROI_CODEX_BROKER_HEARTBEAT_MS || 5000));
31
- const staleMilliseconds = Math.max(heartbeatMilliseconds * 3, Number(process.env.MICROI_CODEX_BROKER_STALE_MS || 20000));
32
- function testDiagnostic(message) {
33
- if (process.env.MICROI_CODEX_TEST_DIAGNOSTICS !== '1' || !process.env.MICROI_CODEX_TEST_LOG) return;
34
- try { if (!fs.existsSync(process.env.MICROI_CODEX_TEST_LOG) || fs.statSync(process.env.MICROI_CODEX_TEST_LOG).size < 65536) fs.appendFileSync(process.env.MICROI_CODEX_TEST_LOG, `${new Date().toISOString()} ${String(message).slice(0,8192)}\n`); } catch { /* tests report missing evidence */ }
35
- }
36
- testDiagnostic(`broker start ${process.version}`);
37
-
38
- if (!endpoint || !process.env.MICROI_CODEX_BROKER_LEASE) {
39
- process.stderr.write('[microi-codex-broker] Missing endpoint or lease path.\n');
40
- process.exit(1);
41
- }
42
-
43
- const ownerToken = crypto.randomBytes(24).toString('hex');
44
- const children = new Map();
45
- const clients = new Set();
46
- let requestSequence = 0;
47
- let leaseOwned = false;
48
- let shuttingDown = false;
49
- let idleTimer = null;
50
- let heartbeatTimer = null;
51
- let server = null;
52
-
53
- function processExists(pid) {
54
- if (!Number.isInteger(pid) || pid <= 1) return false;
55
- try {
56
- process.kill(pid, 0);
57
- return true;
58
- } catch (error) {
59
- return error?.code === 'EPERM';
60
- }
61
- }
62
-
63
- function readLease() {
64
- try {
65
- const parsed = JSON.parse(fs.readFileSync(leasePath, 'utf8'));
66
- return parsed && typeof parsed === 'object' ? parsed : null;
67
- } catch {
68
- return null;
69
- }
70
- }
71
-
72
- function leaseRecord() {
73
- return {
74
- pid: process.pid,
75
- token: ownerToken,
76
- endpoint,
77
- workspaceRoot,
78
- toolVersion,
79
- startedAt: startedAtIso,
80
- heartbeatAt: new Date().toISOString(),
81
- };
82
- }
83
-
84
- function writeLeaseRecord(record, exclusive = false) {
85
- fs.mkdirSync(path.dirname(leasePath), { recursive: true });
86
- const text = `${JSON.stringify(record, null, 2)}\n`;
87
- if (exclusive) {
88
- // Publish a complete lease atomically. Creating leasePath first and then
89
- // writing its JSON leaves a short empty-file window; concurrent brokers can
90
- // mistake that window for a stale lease, remove it, and leave connected
91
- // routers without an authentication token. A same-directory hard link is
92
- // both exclusive (EEXIST wins the race) and immediately complete.
93
- const staged = `${leasePath}.${process.pid}.${Date.now()}.${ownerToken.slice(0, 8)}.new`;
94
- try {
95
- fs.writeFileSync(staged, text, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
96
- fs.linkSync(staged, leasePath);
97
- } finally {
98
- try { if (fs.existsSync(staged)) fs.rmSync(staged, { force: true }); } catch { /* harmless */ }
99
- }
100
- return;
101
- }
102
- const current = readLease();
103
- if (!current || current.token !== ownerToken) throw new Error('Microi Agentx broker lease ownership changed');
104
- const staged = `${leasePath}.${process.pid}.${Date.now()}.tmp`;
105
- try {
106
- fs.writeFileSync(staged, text, { encoding: 'utf8', mode: 0o600 });
107
- fs.renameSync(staged, leasePath);
108
- } finally {
109
- try { if (fs.existsSync(staged)) fs.rmSync(staged, { force: true }); } catch { /* best effort */ }
110
- }
111
- }
112
-
113
- function acquireLease() {
114
- fs.mkdirSync(path.dirname(leasePath), { recursive: true });
115
- for (let attempt = 0; attempt < 4; attempt += 1) {
116
- try {
117
- writeLeaseRecord(leaseRecord(), true);
118
- leaseOwned = true;
119
- return true;
120
- } catch (error) {
121
- if (error?.code !== 'EEXIST') throw error;
122
- const existing = readLease();
123
- const heartbeat = Date.parse(String(existing?.heartbeatAt || ''));
124
- const fresh = Number.isFinite(heartbeat) && Date.now() - heartbeat < staleMilliseconds;
125
- if (existing && processExists(Number(existing.pid)) && fresh) return false;
126
- const stalePath = `${leasePath}.stale.${process.pid}.${Date.now()}`;
127
- try {
128
- fs.renameSync(leasePath, stalePath);
129
- try { fs.rmSync(stalePath, { force: true }); } catch { /* harmless */ }
130
- } catch (renameError) {
131
- if (!['ENOENT', 'EACCES', 'EPERM'].includes(renameError?.code)) throw renameError;
132
- }
133
- }
134
- }
135
- return false;
136
- }
137
-
138
- function releaseLease() {
139
- if (!leaseOwned) return;
140
- const current = readLease();
141
- if (current?.token === ownerToken) {
142
- try { fs.rmSync(leasePath, { force: true }); } catch { /* next owner can reclaim stale lease */ }
143
- }
144
- leaseOwned = false;
145
- }
146
-
147
- function safeText(value) {
148
- return String(value == null ? '' : value);
149
- }
150
-
151
- function profileIdentity(profile) {
152
- return safeText(profile?.identity) || [
153
- safeText(profile?.apiBaseUrl).replace(/\/+$/, ''),
154
- safeText(profile?.osClient).trim(),
155
- safeText(profile?.osClientType).trim(),
156
- safeText(profile?.osClientNetwork).trim(),
157
- ].join('|');
158
- }
159
-
160
- function workspaceSecretKey(baseKey, profileWorkspace) {
161
- const normalized = path.resolve(profileWorkspace).toLowerCase();
162
- const hash = crypto.createHash('sha256').update(normalized).digest('hex').slice(0, 16);
163
- return `${baseKey}.workspace.${hash}`;
164
- }
165
-
166
- function credentialSecretKey(baseKey, profile, profileWorkspace) {
167
- const apiBaseUrl = safeText(profile.apiBaseUrl).trim().replace(/\/+$/, '');
168
- const osClient = safeText(profile.osClient).trim();
169
- return workspaceSecretKey(`${baseKey}.${apiBaseUrl}|${osClient}`, profileWorkspace);
170
- }
171
-
172
- function validateProfile(raw) {
173
- const profile = raw && typeof raw === 'object' ? raw : {};
174
- const profileWorkspace = path.resolve(safeText(profile.workspaceRoot || workspaceRoot));
175
- if (process.platform === 'win32') {
176
- if (profileWorkspace.toLowerCase() !== workspaceRoot.toLowerCase()) throw new Error('Broker workspace mismatch');
177
- } else if (profileWorkspace !== workspaceRoot) {
178
- throw new Error('Broker workspace mismatch');
179
- }
180
- if (!/^https?:\/\//i.test(safeText(profile.apiBaseUrl))) throw new Error('Invalid Microi API URL');
181
- const syncRoot = path.resolve(safeText(profile.syncRoot || path.join(profileWorkspace, 'Microi-V8-Engine')));
182
- return {
183
- identity: profileIdentity(profile),
184
- name: safeText(profile.name || profile.osClient || 'microi'),
185
- label: safeText(profile.label),
186
- apiBaseUrl: safeText(profile.apiBaseUrl).replace(/\/+$/, ''),
187
- osClient: safeText(profile.osClient).trim(),
188
- osClientType: safeText(profile.osClientType).trim(),
189
- osClientNetwork: safeText(profile.osClientNetwork).trim(),
190
- workspaceRoot: profileWorkspace,
191
- syncRoot,
192
- tokenPath: path.resolve(safeText(profile.tokenPath || path.join(profileWorkspace, 'Microi-V8-Engine', '.microi-mcp-tokens.json'))),
193
- applicationsDir: path.resolve(safeText(profile.applicationsDir || path.join(profileWorkspace, 'Microi-V8-Engine'))),
194
- workspaceCredentialFilePath: path.join(syncRoot, '.microi-workspace-secrets.dpapi.json'),
195
- workspaceCredentialUsernameKey: credentialSecretKey('microi.username', profile, profileWorkspace),
196
- workspaceCredentialPasswordKey: credentialSecretKey('microi.password', profile, profileWorkspace),
197
- };
198
- }
199
-
200
- function deviceId() {
201
- const raw = `MCP:${os.hostname() || 'Unknown'}`;
202
- if (/^[\x20-\x7E]{1,128}$/.test(raw)) return raw;
203
- return `MCP-${crypto.createHash('sha256').update(raw).digest('hex').slice(0, 16)}`;
204
- }
205
-
206
- class ChildMcp {
207
- constructor(profile) {
208
- this.profile = profile;
209
- this.pending = new Map();
210
- this.buffer = '';
211
- this.stopping = false;
212
- this.ready = this.start();
213
- }
214
-
215
- async start() {
216
- if (!fs.existsSync(mcpServerPath)) throw new Error(`Microi MCP bundle does not exist: ${mcpServerPath}`);
217
- this.child = childProcess.spawn(process.execPath, [mcpServerPath], {
218
- cwd: this.profile.workspaceRoot,
219
- windowsHide: true,
220
- stdio: ['pipe', 'pipe', 'pipe'],
221
- env: {
222
- ...process.env,
223
- MICROI_API_URL: this.profile.apiBaseUrl,
224
- MICROI_TOKEN_FILE: this.profile.tokenPath,
225
- MICROI_AUTH_RECOVERY_DIR: `${this.profile.tokenPath}.recovery`,
226
- MICROI_WORKSPACE_CREDENTIAL_FILE: this.profile.workspaceCredentialFilePath,
227
- MICROI_WORKSPACE_USERNAME_KEY: this.profile.workspaceCredentialUsernameKey,
228
- MICROI_WORKSPACE_PASSWORD_KEY: this.profile.workspaceCredentialPasswordKey,
229
- MICROI_OS_CLIENT: this.profile.osClient,
230
- MICROI_OS_CLIENT_TYPE: this.profile.osClientType,
231
- MICROI_OS_CLIENT_NETWORK: this.profile.osClientNetwork,
232
- MICROI_WORKSPACE_ROOT: this.profile.workspaceRoot,
233
- MICROI_SYNC_ROOT: this.profile.syncRoot,
234
- MICROI_AI_APPLICATIONS_DIR: this.profile.applicationsDir,
235
- MICROI_LABEL_BASE64: Buffer.from(this.profile.label, 'utf8').toString('base64'),
236
- MICROI_MCP_DID: deviceId(),
237
- MICROI_TOOL_SOURCE: 'codex-broker',
238
- MICROI_TOOL_VERSION: toolVersion,
239
- MICROI_CODEX_MODE: '1',
240
- },
241
- });
242
- this.child.stdout.on('data', chunk => this.onData(chunk));
243
- this.child.stdin.on('error', error => this.rejectAll(error));
244
- this.child.stderr.on('data', chunk => { testDiagnostic(`MCP stderr ${chunk}`); process.stderr.write(`[${this.profile.name}] ${chunk}`); });
245
- this.child.on('error', error => this.rejectAll(error));
246
- this.child.on('exit', code => {
247
- testDiagnostic(`MCP child exit ${code}`);
248
- this.rejectAll(new Error(`Microi MCP ${this.profile.name} exited (${code ?? 'unknown'})`));
249
- if (!this.stopping && children.get(this.profile.identity) === this) children.delete(this.profile.identity);
250
- });
251
- await this.request('initialize', {
252
- protocolVersion: PROTOCOL_VERSION,
253
- capabilities: {},
254
- clientInfo: { name: 'microi-codex-shared-broker', version: toolVersion },
255
- }, true);
256
- this.notify('notifications/initialized', {});
257
- }
258
-
259
- onData(chunk) {
260
- this.buffer += chunk.toString('utf8');
261
- let newline;
262
- while ((newline = this.buffer.indexOf('\n')) >= 0) {
263
- const line = this.buffer.slice(0, newline).trim();
264
- this.buffer = this.buffer.slice(newline + 1);
265
- if (!line) continue;
266
- let message;
267
- try { message = JSON.parse(line); } catch { continue; }
268
- if (message.id == null) continue;
269
- const pending = this.pending.get(String(message.id));
270
- if (!pending) continue;
271
- this.pending.delete(String(message.id));
272
- if (message.error) pending.reject(new Error(message.error.message || JSON.stringify(message.error)));
273
- else pending.resolve(message.result);
274
- }
275
- }
276
-
277
- rejectAll(error) {
278
- for (const pending of this.pending.values()) pending.reject(error);
279
- this.pending.clear();
280
- }
281
-
282
- write(message) {
283
- if (!this.child || this.child.stdin.destroyed) throw new Error(`Microi MCP ${this.profile.name} is unavailable`);
284
- this.child.stdin.write(`${JSON.stringify(message)}\n`);
285
- }
286
-
287
- request(method, params, skipReady = false) {
288
- return (async () => {
289
- if (!skipReady) await this.ready;
290
- const id = `broker-${process.pid}-${++requestSequence}`;
291
- const response = new Promise((resolve, reject) => this.pending.set(id, { resolve, reject }));
292
- this.write({ jsonrpc: '2.0', id, method, params });
293
- return response;
294
- })();
295
- }
296
-
297
- notify(method, params) {
298
- this.write({ jsonrpc: '2.0', method, params });
299
- }
300
-
301
- stop() {
302
- this.stopping = true;
303
- try { this.child?.stdin.end(); } catch { /* best effort */ }
304
- try { this.child?.kill('SIGTERM'); } catch { /* best effort */ }
305
- const child = this.child;
306
- const forceTimer = setTimeout(() => {
307
- if (child && child.exitCode === null) {
308
- try { child.kill('SIGKILL'); } catch { /* best effort */ }
309
- }
310
- }, 2000);
311
- forceTimer.unref();
312
- }
313
- }
314
-
315
- function childFor(rawProfile) {
316
- const profile = validateProfile(rawProfile);
317
- const existing = children.get(profile.identity);
318
- if (existing) return existing;
319
- const child = new ChildMcp(profile);
320
- children.set(profile.identity, child);
321
- return child;
322
- }
323
-
324
- function send(socket, message) {
325
- if (!socket.destroyed) socket.write(`${JSON.stringify(message)}\n`);
326
- }
327
-
328
- async function handleMessage(socket, message) {
329
- const id = message?.id;
330
- if (id == null) return;
331
- if (message.auth !== ownerToken) {
332
- send(socket, { id, error: 'Unauthorized local broker client' });
333
- return;
334
- }
335
- try {
336
- if (message.type === 'status') {
337
- send(socket, {
338
- id,
339
- result: {
340
- pid: process.pid,
341
- workspaceRoot,
342
- toolVersion,
343
- clients: clients.size,
344
- childCount: children.size,
345
- childPids: [...children.values()].map(item => item.child?.pid).filter(Boolean),
346
- },
347
- });
348
- return;
349
- }
350
- if (message.type !== 'request') throw new Error('Unsupported broker request');
351
- const result = await childFor(message.profile).request(safeText(message.method), message.params || {});
352
- send(socket, { id, result });
353
- } catch (error) {
354
- send(socket, { id, error: error instanceof Error ? error.message : String(error) });
355
- }
356
- }
357
-
358
- function cancelIdleShutdown() {
359
- if (idleTimer) clearTimeout(idleTimer);
360
- idleTimer = null;
361
- }
362
-
363
- function scheduleIdleShutdown(initial = false) {
364
- cancelIdleShutdown();
365
- if (clients.size > 0 || shuttingDown) return;
366
- idleTimer = setTimeout(() => shutdown(0), initial ? initialClientGraceMilliseconds : idleMilliseconds);
367
- }
368
-
369
- function acceptClient(socket) {
370
- testDiagnostic('client connected');
371
- cancelIdleShutdown();
372
- clients.add(socket);
373
- socket.setEncoding('utf8');
374
- let buffer = '';
375
- socket.on('data', chunk => {
376
- buffer += chunk;
377
- let newline;
378
- while ((newline = buffer.indexOf('\n')) >= 0) {
379
- const line = buffer.slice(0, newline).trim();
380
- buffer = buffer.slice(newline + 1);
381
- if (!line) continue;
382
- let message;
383
- try { message = JSON.parse(line); }
384
- catch { send(socket, { id: null, error: 'Invalid broker JSON' }); continue; }
385
- Promise.resolve(handleMessage(socket, message)).catch(() => { /* handled above */ });
386
- }
387
- });
388
- const close = () => {
389
- testDiagnostic('client disconnected');
390
- clients.delete(socket);
391
- scheduleIdleShutdown();
392
- };
393
- socket.once('close', close);
394
- socket.once('error', close);
395
- }
396
-
397
- function removeUnixSocket() {
398
- if (process.platform === 'win32') return;
399
- try { if (fs.existsSync(endpoint)) fs.rmSync(endpoint, { force: true }); } catch { /* stale socket is reclaimable */ }
400
- }
401
-
402
- function shutdown(exitCode = 0) {
403
- testDiagnostic(`shutdown ${exitCode}`);
404
- if (shuttingDown) return;
405
- shuttingDown = true;
406
- cancelIdleShutdown();
407
- if (heartbeatTimer) clearInterval(heartbeatTimer);
408
- for (const socket of clients) {
409
- try { socket.end(); } catch { /* best effort */ }
410
- }
411
- clients.clear();
412
- for (const child of children.values()) child.stop();
413
- children.clear();
414
- const finish = () => {
415
- releaseLease();
416
- removeUnixSocket();
417
- process.exit(exitCode);
418
- };
419
- if (server) {
420
- try { server.close(finish); } catch { finish(); }
421
- const forceTimer = setTimeout(finish, 2200);
422
- forceTimer.unref();
423
- } else {
424
- finish();
425
- }
426
- }
427
-
428
- const startedAtIso = new Date().toISOString();
429
- // Windows 命名管道无需目录;macOS/Linux 首次连接必须先创建 Unix socket 的父目录。
430
- // 在领取租约前完成,目录不可写时不会留下貌似存活的 Broker 租约。
431
- if (process.platform !== 'win32') fs.mkdirSync(path.dirname(endpoint), { recursive: true, mode: 0o700 });
432
- if (!acquireLease()) process.exit(0);
433
-
434
- removeUnixSocket();
435
- server = net.createServer(acceptClient);
436
- server.on('error', error => {
437
- testDiagnostic(`server error ${error.message}`);
438
- process.stderr.write(`[microi-codex-broker] ${error.message}\n`);
439
- shutdown(1);
440
- });
441
- server.listen(endpoint, () => {
442
- testDiagnostic(`server listening ${JSON.stringify(endpoint)}`);
443
- if (process.platform !== 'win32') {
444
- try { fs.chmodSync(endpoint, 0o600); } catch { /* best effort */ }
445
- }
446
- heartbeatTimer = setInterval(() => {
447
- try { writeLeaseRecord(leaseRecord()); } catch (error) { testDiagnostic(`heartbeat failed ${error.message}`); shutdown(1); }
448
- }, heartbeatMilliseconds);
449
- scheduleIdleShutdown(true);
450
- });
451
-
452
- for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => shutdown(0));
453
- process.on('uncaughtException', error => {
454
- testDiagnostic(`uncaught ${error?.stack || error}`);
455
- process.stderr.write(`[microi-codex-broker] ${error?.stack || error}\n`);
456
- shutdown(1);
457
- });
458
- process.on('exit', () => {
459
- for (const child of children.values()) {
460
- try { if (child.child?.exitCode === null) child.child.kill('SIGKILL'); } catch { /* best effort */ }
461
- }
462
- if (leaseOwned) {
463
- releaseLease();
464
- removeUnixSocket();
465
- }
466
- });
1
+ #!/usr/bin/env node
2
+ /*
3
+ * Shared Microi Agentx MCP broker.
4
+ *
5
+ * Every Codex task still owns a tiny stdio router, but all routers for the same
6
+ * workspace and tool version share this broker. The broker owns at most one
7
+ * real MCP child per connection profile, uses an exclusive lease to survive
8
+ * concurrent starts, and exits after the last router has been idle.
9
+ */
10
+
11
+ 'use strict';
12
+
13
+ const childProcess = require('node:child_process');
14
+ const crypto = require('node:crypto');
15
+ const fs = require('node:fs');
16
+ const net = require('node:net');
17
+ const os = require('node:os');
18
+ const path = require('node:path');
19
+
20
+ const PROTOCOL_VERSION = '2024-11-05';
21
+ const endpoint = String(process.env.MICROI_CODEX_BROKER_ENDPOINT || '');
22
+ const leasePath = path.resolve(String(process.env.MICROI_CODEX_BROKER_LEASE || ''));
23
+ const workspaceRoot = path.resolve(String(process.env.MICROI_WORKSPACE_ROOT || process.cwd()));
24
+ const mcpServerPath = path.resolve(String(process.env.MICROI_MCP_SERVER_PATH || path.join(__dirname, 'mcp-server.js')));
25
+ const toolVersion = String(process.env.MICROI_TOOL_VERSION || '0.0.0');
26
+ const idleMilliseconds = Math.max(250, Number(process.env.MICROI_CODEX_BROKER_IDLE_MS || 30000));
27
+ // The launching router may not get scheduled again immediately on a busy host.
28
+ // Do not retire the listening pipe before its first client has had time to join.
29
+ const initialClientGraceMilliseconds = Math.max(10000, idleMilliseconds);
30
+ const heartbeatMilliseconds = Math.max(500, Number(process.env.MICROI_CODEX_BROKER_HEARTBEAT_MS || 5000));
31
+ const staleMilliseconds = Math.max(heartbeatMilliseconds * 3, Number(process.env.MICROI_CODEX_BROKER_STALE_MS || 20000));
32
+ function testDiagnostic(message) {
33
+ if (process.env.MICROI_CODEX_TEST_DIAGNOSTICS !== '1' || !process.env.MICROI_CODEX_TEST_LOG) return;
34
+ try { if (!fs.existsSync(process.env.MICROI_CODEX_TEST_LOG) || fs.statSync(process.env.MICROI_CODEX_TEST_LOG).size < 65536) fs.appendFileSync(process.env.MICROI_CODEX_TEST_LOG, `${new Date().toISOString()} ${String(message).slice(0,8192)}\n`); } catch { /* tests report missing evidence */ }
35
+ }
36
+ testDiagnostic(`broker start ${process.version}`);
37
+
38
+ if (!endpoint || !process.env.MICROI_CODEX_BROKER_LEASE) {
39
+ process.stderr.write('[microi-codex-broker] Missing endpoint or lease path.\n');
40
+ process.exit(1);
41
+ }
42
+
43
+ const ownerToken = crypto.randomBytes(24).toString('hex');
44
+ const children = new Map();
45
+ const clients = new Set();
46
+ let requestSequence = 0;
47
+ let leaseOwned = false;
48
+ let shuttingDown = false;
49
+ let idleTimer = null;
50
+ let heartbeatTimer = null;
51
+ let server = null;
52
+
53
+ function processExists(pid) {
54
+ if (!Number.isInteger(pid) || pid <= 1) return false;
55
+ try {
56
+ process.kill(pid, 0);
57
+ return true;
58
+ } catch (error) {
59
+ return error?.code === 'EPERM';
60
+ }
61
+ }
62
+
63
+ function readLease() {
64
+ try {
65
+ const parsed = JSON.parse(fs.readFileSync(leasePath, 'utf8'));
66
+ return parsed && typeof parsed === 'object' ? parsed : null;
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+
72
+ function leaseRecord() {
73
+ return {
74
+ pid: process.pid,
75
+ token: ownerToken,
76
+ endpoint,
77
+ workspaceRoot,
78
+ toolVersion,
79
+ startedAt: startedAtIso,
80
+ heartbeatAt: new Date().toISOString(),
81
+ };
82
+ }
83
+
84
+ function writeLeaseRecord(record, exclusive = false) {
85
+ fs.mkdirSync(path.dirname(leasePath), { recursive: true });
86
+ const text = `${JSON.stringify(record, null, 2)}\n`;
87
+ if (exclusive) {
88
+ // Publish a complete lease atomically. Creating leasePath first and then
89
+ // writing its JSON leaves a short empty-file window; concurrent brokers can
90
+ // mistake that window for a stale lease, remove it, and leave connected
91
+ // routers without an authentication token. A same-directory hard link is
92
+ // both exclusive (EEXIST wins the race) and immediately complete.
93
+ const staged = `${leasePath}.${process.pid}.${Date.now()}.${ownerToken.slice(0, 8)}.new`;
94
+ try {
95
+ fs.writeFileSync(staged, text, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
96
+ fs.linkSync(staged, leasePath);
97
+ } finally {
98
+ try { if (fs.existsSync(staged)) fs.rmSync(staged, { force: true }); } catch { /* harmless */ }
99
+ }
100
+ return;
101
+ }
102
+ const current = readLease();
103
+ if (!current || current.token !== ownerToken) throw new Error('Microi Agentx broker lease ownership changed');
104
+ const staged = `${leasePath}.${process.pid}.${Date.now()}.tmp`;
105
+ try {
106
+ fs.writeFileSync(staged, text, { encoding: 'utf8', mode: 0o600 });
107
+ fs.renameSync(staged, leasePath);
108
+ } finally {
109
+ try { if (fs.existsSync(staged)) fs.rmSync(staged, { force: true }); } catch { /* best effort */ }
110
+ }
111
+ }
112
+
113
+ function acquireLease() {
114
+ fs.mkdirSync(path.dirname(leasePath), { recursive: true });
115
+ for (let attempt = 0; attempt < 4; attempt += 1) {
116
+ try {
117
+ writeLeaseRecord(leaseRecord(), true);
118
+ leaseOwned = true;
119
+ return true;
120
+ } catch (error) {
121
+ if (error?.code !== 'EEXIST') throw error;
122
+ const existing = readLease();
123
+ const heartbeat = Date.parse(String(existing?.heartbeatAt || ''));
124
+ const fresh = Number.isFinite(heartbeat) && Date.now() - heartbeat < staleMilliseconds;
125
+ if (existing && processExists(Number(existing.pid)) && fresh) return false;
126
+ const stalePath = `${leasePath}.stale.${process.pid}.${Date.now()}`;
127
+ try {
128
+ fs.renameSync(leasePath, stalePath);
129
+ try { fs.rmSync(stalePath, { force: true }); } catch { /* harmless */ }
130
+ } catch (renameError) {
131
+ if (!['ENOENT', 'EACCES', 'EPERM'].includes(renameError?.code)) throw renameError;
132
+ }
133
+ }
134
+ }
135
+ return false;
136
+ }
137
+
138
+ function releaseLease() {
139
+ if (!leaseOwned) return;
140
+ const current = readLease();
141
+ if (current?.token === ownerToken) {
142
+ try { fs.rmSync(leasePath, { force: true }); } catch { /* next owner can reclaim stale lease */ }
143
+ }
144
+ leaseOwned = false;
145
+ }
146
+
147
+ function safeText(value) {
148
+ return String(value == null ? '' : value);
149
+ }
150
+
151
+ function profileIdentity(profile) {
152
+ return safeText(profile?.identity) || [
153
+ safeText(profile?.apiBaseUrl).replace(/\/+$/, ''),
154
+ safeText(profile?.osClient).trim(),
155
+ safeText(profile?.osClientType).trim(),
156
+ safeText(profile?.osClientNetwork).trim(),
157
+ ].join('|');
158
+ }
159
+
160
+ function workspaceSecretKey(baseKey, profileWorkspace) {
161
+ const normalized = path.resolve(profileWorkspace).toLowerCase();
162
+ const hash = crypto.createHash('sha256').update(normalized).digest('hex').slice(0, 16);
163
+ return `${baseKey}.workspace.${hash}`;
164
+ }
165
+
166
+ function credentialSecretKey(baseKey, profile, profileWorkspace) {
167
+ const apiBaseUrl = safeText(profile.apiBaseUrl).trim().replace(/\/+$/, '');
168
+ const osClient = safeText(profile.osClient).trim();
169
+ return workspaceSecretKey(`${baseKey}.${apiBaseUrl}|${osClient}`, profileWorkspace);
170
+ }
171
+
172
+ function validateProfile(raw) {
173
+ const profile = raw && typeof raw === 'object' ? raw : {};
174
+ const profileWorkspace = path.resolve(safeText(profile.workspaceRoot || workspaceRoot));
175
+ if (process.platform === 'win32') {
176
+ if (profileWorkspace.toLowerCase() !== workspaceRoot.toLowerCase()) throw new Error('Broker workspace mismatch');
177
+ } else if (profileWorkspace !== workspaceRoot) {
178
+ throw new Error('Broker workspace mismatch');
179
+ }
180
+ if (!/^https?:\/\//i.test(safeText(profile.apiBaseUrl))) throw new Error('Invalid Microi API URL');
181
+ const syncRoot = path.resolve(safeText(profile.syncRoot || path.join(profileWorkspace, 'Microi-V8-Engine')));
182
+ return {
183
+ identity: profileIdentity(profile),
184
+ name: safeText(profile.name || profile.osClient || 'microi'),
185
+ label: safeText(profile.label),
186
+ apiBaseUrl: safeText(profile.apiBaseUrl).replace(/\/+$/, ''),
187
+ osClient: safeText(profile.osClient).trim(),
188
+ osClientType: safeText(profile.osClientType).trim(),
189
+ osClientNetwork: safeText(profile.osClientNetwork).trim(),
190
+ workspaceRoot: profileWorkspace,
191
+ syncRoot,
192
+ tokenPath: path.resolve(safeText(profile.tokenPath || path.join(profileWorkspace, 'Microi-V8-Engine', '.microi-mcp-tokens.json'))),
193
+ applicationsDir: path.resolve(safeText(profile.applicationsDir || path.join(profileWorkspace, 'Microi-V8-Engine'))),
194
+ workspaceCredentialFilePath: path.join(syncRoot, '.microi-workspace-secrets.dpapi.json'),
195
+ workspaceCredentialUsernameKey: credentialSecretKey('microi.username', profile, profileWorkspace),
196
+ workspaceCredentialPasswordKey: credentialSecretKey('microi.password', profile, profileWorkspace),
197
+ };
198
+ }
199
+
200
+ function deviceId() {
201
+ const raw = `MCP:${os.hostname() || 'Unknown'}`;
202
+ if (/^[\x20-\x7E]{1,128}$/.test(raw)) return raw;
203
+ return `MCP-${crypto.createHash('sha256').update(raw).digest('hex').slice(0, 16)}`;
204
+ }
205
+
206
+ class ChildMcp {
207
+ constructor(profile) {
208
+ this.profile = profile;
209
+ this.pending = new Map();
210
+ this.buffer = '';
211
+ this.stopping = false;
212
+ this.ready = this.start();
213
+ }
214
+
215
+ async start() {
216
+ if (!fs.existsSync(mcpServerPath)) throw new Error(`Microi MCP bundle does not exist: ${mcpServerPath}`);
217
+ this.child = childProcess.spawn(process.execPath, [mcpServerPath], {
218
+ cwd: this.profile.workspaceRoot,
219
+ windowsHide: true,
220
+ stdio: ['pipe', 'pipe', 'pipe'],
221
+ env: {
222
+ ...process.env,
223
+ MICROI_API_URL: this.profile.apiBaseUrl,
224
+ MICROI_TOKEN_FILE: this.profile.tokenPath,
225
+ MICROI_AUTH_RECOVERY_DIR: `${this.profile.tokenPath}.recovery`,
226
+ MICROI_WORKSPACE_CREDENTIAL_FILE: this.profile.workspaceCredentialFilePath,
227
+ MICROI_WORKSPACE_USERNAME_KEY: this.profile.workspaceCredentialUsernameKey,
228
+ MICROI_WORKSPACE_PASSWORD_KEY: this.profile.workspaceCredentialPasswordKey,
229
+ MICROI_OS_CLIENT: this.profile.osClient,
230
+ MICROI_OS_CLIENT_TYPE: this.profile.osClientType,
231
+ MICROI_OS_CLIENT_NETWORK: this.profile.osClientNetwork,
232
+ MICROI_WORKSPACE_ROOT: this.profile.workspaceRoot,
233
+ MICROI_SYNC_ROOT: this.profile.syncRoot,
234
+ MICROI_AI_APPLICATIONS_DIR: this.profile.applicationsDir,
235
+ MICROI_LABEL_BASE64: Buffer.from(this.profile.label, 'utf8').toString('base64'),
236
+ MICROI_MCP_DID: deviceId(),
237
+ MICROI_TOOL_SOURCE: 'codex-broker',
238
+ MICROI_TOOL_VERSION: toolVersion,
239
+ MICROI_CODEX_MODE: '1',
240
+ },
241
+ });
242
+ this.child.stdout.on('data', chunk => this.onData(chunk));
243
+ this.child.stdin.on('error', error => this.rejectAll(error));
244
+ this.child.stderr.on('data', chunk => { testDiagnostic(`MCP stderr ${chunk}`); process.stderr.write(`[${this.profile.name}] ${chunk}`); });
245
+ this.child.on('error', error => this.rejectAll(error));
246
+ this.child.on('exit', code => {
247
+ testDiagnostic(`MCP child exit ${code}`);
248
+ this.rejectAll(new Error(`Microi MCP ${this.profile.name} exited (${code ?? 'unknown'})`));
249
+ if (!this.stopping && children.get(this.profile.identity) === this) children.delete(this.profile.identity);
250
+ });
251
+ await this.request('initialize', {
252
+ protocolVersion: PROTOCOL_VERSION,
253
+ capabilities: {},
254
+ clientInfo: { name: 'microi-codex-shared-broker', version: toolVersion },
255
+ }, true);
256
+ this.notify('notifications/initialized', {});
257
+ }
258
+
259
+ onData(chunk) {
260
+ this.buffer += chunk.toString('utf8');
261
+ let newline;
262
+ while ((newline = this.buffer.indexOf('\n')) >= 0) {
263
+ const line = this.buffer.slice(0, newline).trim();
264
+ this.buffer = this.buffer.slice(newline + 1);
265
+ if (!line) continue;
266
+ let message;
267
+ try { message = JSON.parse(line); } catch { continue; }
268
+ if (message.id == null) continue;
269
+ const pending = this.pending.get(String(message.id));
270
+ if (!pending) continue;
271
+ this.pending.delete(String(message.id));
272
+ if (message.error) pending.reject(new Error(message.error.message || JSON.stringify(message.error)));
273
+ else pending.resolve(message.result);
274
+ }
275
+ }
276
+
277
+ rejectAll(error) {
278
+ for (const pending of this.pending.values()) pending.reject(error);
279
+ this.pending.clear();
280
+ }
281
+
282
+ write(message) {
283
+ if (!this.child || this.child.stdin.destroyed) throw new Error(`Microi MCP ${this.profile.name} is unavailable`);
284
+ this.child.stdin.write(`${JSON.stringify(message)}\n`);
285
+ }
286
+
287
+ request(method, params, skipReady = false) {
288
+ return (async () => {
289
+ if (!skipReady) await this.ready;
290
+ const id = `broker-${process.pid}-${++requestSequence}`;
291
+ const response = new Promise((resolve, reject) => this.pending.set(id, { resolve, reject }));
292
+ this.write({ jsonrpc: '2.0', id, method, params });
293
+ return response;
294
+ })();
295
+ }
296
+
297
+ notify(method, params) {
298
+ this.write({ jsonrpc: '2.0', method, params });
299
+ }
300
+
301
+ stop() {
302
+ this.stopping = true;
303
+ try { this.child?.stdin.end(); } catch { /* best effort */ }
304
+ try { this.child?.kill('SIGTERM'); } catch { /* best effort */ }
305
+ const child = this.child;
306
+ const forceTimer = setTimeout(() => {
307
+ if (child && child.exitCode === null) {
308
+ try { child.kill('SIGKILL'); } catch { /* best effort */ }
309
+ }
310
+ }, 2000);
311
+ forceTimer.unref();
312
+ }
313
+ }
314
+
315
+ function childFor(rawProfile) {
316
+ const profile = validateProfile(rawProfile);
317
+ const existing = children.get(profile.identity);
318
+ if (existing) return existing;
319
+ const child = new ChildMcp(profile);
320
+ children.set(profile.identity, child);
321
+ return child;
322
+ }
323
+
324
+ function send(socket, message) {
325
+ if (!socket.destroyed) socket.write(`${JSON.stringify(message)}\n`);
326
+ }
327
+
328
+ async function handleMessage(socket, message) {
329
+ const id = message?.id;
330
+ if (id == null) return;
331
+ if (message.auth !== ownerToken) {
332
+ send(socket, { id, error: 'Unauthorized local broker client' });
333
+ return;
334
+ }
335
+ try {
336
+ if (message.type === 'status') {
337
+ send(socket, {
338
+ id,
339
+ result: {
340
+ pid: process.pid,
341
+ workspaceRoot,
342
+ toolVersion,
343
+ clients: clients.size,
344
+ childCount: children.size,
345
+ childPids: [...children.values()].map(item => item.child?.pid).filter(Boolean),
346
+ },
347
+ });
348
+ return;
349
+ }
350
+ if (message.type !== 'request') throw new Error('Unsupported broker request');
351
+ const result = await childFor(message.profile).request(safeText(message.method), message.params || {});
352
+ send(socket, { id, result });
353
+ } catch (error) {
354
+ send(socket, { id, error: error instanceof Error ? error.message : String(error) });
355
+ }
356
+ }
357
+
358
+ function cancelIdleShutdown() {
359
+ if (idleTimer) clearTimeout(idleTimer);
360
+ idleTimer = null;
361
+ }
362
+
363
+ function scheduleIdleShutdown(initial = false) {
364
+ cancelIdleShutdown();
365
+ if (clients.size > 0 || shuttingDown) return;
366
+ idleTimer = setTimeout(() => shutdown(0), initial ? initialClientGraceMilliseconds : idleMilliseconds);
367
+ }
368
+
369
+ function acceptClient(socket) {
370
+ testDiagnostic('client connected');
371
+ cancelIdleShutdown();
372
+ clients.add(socket);
373
+ socket.setEncoding('utf8');
374
+ let buffer = '';
375
+ socket.on('data', chunk => {
376
+ buffer += chunk;
377
+ let newline;
378
+ while ((newline = buffer.indexOf('\n')) >= 0) {
379
+ const line = buffer.slice(0, newline).trim();
380
+ buffer = buffer.slice(newline + 1);
381
+ if (!line) continue;
382
+ let message;
383
+ try { message = JSON.parse(line); }
384
+ catch { send(socket, { id: null, error: 'Invalid broker JSON' }); continue; }
385
+ Promise.resolve(handleMessage(socket, message)).catch(() => { /* handled above */ });
386
+ }
387
+ });
388
+ const close = () => {
389
+ testDiagnostic('client disconnected');
390
+ clients.delete(socket);
391
+ scheduleIdleShutdown();
392
+ };
393
+ socket.once('close', close);
394
+ socket.once('error', close);
395
+ }
396
+
397
+ function removeUnixSocket() {
398
+ if (process.platform === 'win32') return;
399
+ try { if (fs.existsSync(endpoint)) fs.rmSync(endpoint, { force: true }); } catch { /* stale socket is reclaimable */ }
400
+ }
401
+
402
+ function shutdown(exitCode = 0) {
403
+ testDiagnostic(`shutdown ${exitCode}`);
404
+ if (shuttingDown) return;
405
+ shuttingDown = true;
406
+ cancelIdleShutdown();
407
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
408
+ for (const socket of clients) {
409
+ try { socket.end(); } catch { /* best effort */ }
410
+ }
411
+ clients.clear();
412
+ for (const child of children.values()) child.stop();
413
+ children.clear();
414
+ const finish = () => {
415
+ releaseLease();
416
+ removeUnixSocket();
417
+ process.exit(exitCode);
418
+ };
419
+ if (server) {
420
+ try { server.close(finish); } catch { finish(); }
421
+ const forceTimer = setTimeout(finish, 2200);
422
+ forceTimer.unref();
423
+ } else {
424
+ finish();
425
+ }
426
+ }
427
+
428
+ const startedAtIso = new Date().toISOString();
429
+ // Windows 命名管道无需目录;macOS/Linux 首次连接必须先创建 Unix socket 的父目录。
430
+ // 在领取租约前完成,目录不可写时不会留下貌似存活的 Broker 租约。
431
+ if (process.platform !== 'win32') fs.mkdirSync(path.dirname(endpoint), { recursive: true, mode: 0o700 });
432
+ if (!acquireLease()) process.exit(0);
433
+
434
+ removeUnixSocket();
435
+ server = net.createServer(acceptClient);
436
+ server.on('error', error => {
437
+ testDiagnostic(`server error ${error.message}`);
438
+ process.stderr.write(`[microi-codex-broker] ${error.message}\n`);
439
+ shutdown(1);
440
+ });
441
+ server.listen(endpoint, () => {
442
+ testDiagnostic(`server listening ${JSON.stringify(endpoint)}`);
443
+ if (process.platform !== 'win32') {
444
+ try { fs.chmodSync(endpoint, 0o600); } catch { /* best effort */ }
445
+ }
446
+ heartbeatTimer = setInterval(() => {
447
+ try { writeLeaseRecord(leaseRecord()); } catch (error) { testDiagnostic(`heartbeat failed ${error.message}`); shutdown(1); }
448
+ }, heartbeatMilliseconds);
449
+ scheduleIdleShutdown(true);
450
+ });
451
+
452
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => shutdown(0));
453
+ process.on('uncaughtException', error => {
454
+ testDiagnostic(`uncaught ${error?.stack || error}`);
455
+ process.stderr.write(`[microi-codex-broker] ${error?.stack || error}\n`);
456
+ shutdown(1);
457
+ });
458
+ process.on('exit', () => {
459
+ for (const child of children.values()) {
460
+ try { if (child.child?.exitCode === null) child.child.kill('SIGKILL'); } catch { /* best effort */ }
461
+ }
462
+ if (leaseOwned) {
463
+ releaseLease();
464
+ removeUnixSocket();
465
+ }
466
+ });