@luanpdd/kit-mcp 1.34.0 → 1.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +2 -2
  3. package/bin/mcp.js +6 -6
  4. package/bin/ui.js +74 -74
  5. package/gates/ai-prompt-stability.md +120 -120
  6. package/gates/budget-description.md +68 -68
  7. package/gates/confidence.md +29 -29
  8. package/gates/dependency-check.md +33 -33
  9. package/gates/dept-cycle-prevention.md +179 -179
  10. package/gates/golden-signals-coverage.md +133 -133
  11. package/gates/legacy-refactor-safety.md +178 -178
  12. package/gates/multi-tenant-rls-coverage.md +102 -102
  13. package/gates/no-personal-uuid.md +72 -72
  14. package/gates/obs-agents-mcp-supabase.md +86 -86
  15. package/gates/obs-skills-frontmatter.md +76 -76
  16. package/gates/observability-coverage.md +151 -151
  17. package/gates/omm-no-regression.md +83 -83
  18. package/gates/postmortem-template-required.md +127 -127
  19. package/gates/prr-checklist-coverage.md +128 -128
  20. package/gates/regression.md +32 -32
  21. package/gates/release-pipeline-policy.md +132 -132
  22. package/gates/secrets-scan.md +33 -33
  23. package/gates/service-role-not-in-user-facing.md +113 -113
  24. package/gates/skill-must-include.md +71 -71
  25. package/gates/sync-idempotent.md +62 -62
  26. package/gates/verify-phase-goal.md +34 -34
  27. package/kit/agents/designer-ui.md +216 -216
  28. package/kit/agents/workflow-generator.md +537 -0
  29. package/kit/commands/adicionar-backlog.md +1 -1
  30. package/kit/commands/adicionar-fase.md +1 -1
  31. package/kit/commands/adicionar-tarefa.md +1 -1
  32. package/kit/commands/auditar-observabilidade.md +103 -103
  33. package/kit/commands/auditar-toil.md +129 -129
  34. package/kit/commands/caracterizar-prompt.md +195 -195
  35. package/kit/commands/criar-workflow.md +158 -0
  36. package/kit/commands/definir-perfil.md +1 -1
  37. package/kit/commands/definir-slo.md +108 -108
  38. package/kit/commands/fio.md +1 -1
  39. package/kit/commands/golden-signals.md +142 -142
  40. package/kit/commands/instrumentar-fase.md +200 -200
  41. package/kit/commands/investigar-producao.md +162 -162
  42. package/kit/commands/observabilidade.md +118 -118
  43. package/kit/commands/postmortem.md +179 -179
  44. package/kit/commands/prr.md +205 -205
  45. package/kit/commands/publicar-rapido.md +207 -207
  46. package/kit/commands/risk-budget.md +220 -220
  47. package/kit/commands/sre.md +230 -230
  48. package/kit/file-manifest.json +5 -2
  49. package/kit/framework/references/output-style.md +22 -22
  50. package/kit/hooks/post-apply-migration.js +199 -199
  51. package/kit/hooks/sidecar-tool-publisher.js +210 -210
  52. package/kit/skills/_shared-dados-distribuidos/glossary.md +224 -224
  53. package/kit/skills/_shared-legacy/glossary.md +389 -389
  54. package/kit/skills/_shared-multi-tenant/glossary.md +186 -186
  55. package/kit/skills/_shared-observability/glossary.md +396 -396
  56. package/kit/skills/_shared-sre/glossary.md +712 -712
  57. package/kit/skills/_shared-supabase/glossary.md +234 -234
  58. package/kit/skills/blameless-postmortems/SKILL.md +340 -340
  59. package/kit/skills/burn-rate-alerting/SKILL.md +258 -258
  60. package/kit/skills/cascading-failures/SKILL.md +311 -311
  61. package/kit/skills/core-analysis-loop/SKILL.md +352 -352
  62. package/kit/skills/distributed-tracing/SKILL.md +362 -362
  63. package/kit/skills/dynamic-workflow-authoring/SKILL.md +327 -0
  64. package/kit/skills/eliminating-toil/SKILL.md +243 -243
  65. package/kit/skills/event-based-slos/SKILL.md +296 -296
  66. package/kit/skills/four-golden-signals/SKILL.md +314 -314
  67. package/kit/skills/hermetic-builds/SKILL.md +323 -323
  68. package/kit/skills/legacy-monster-methods/SKILL.md +444 -444
  69. package/kit/skills/llm-as-dependency/SKILL.md +436 -436
  70. package/kit/skills/load-shedding-graceful-degradation/SKILL.md +396 -396
  71. package/kit/skills/observability-driven-development/SKILL.md +315 -315
  72. package/kit/skills/observability-maturity-model/SKILL.md +222 -222
  73. package/kit/skills/opentelemetry-standard/SKILL.md +351 -351
  74. package/kit/skills/production-readiness-review/SKILL.md +305 -305
  75. package/kit/skills/release-engineering/SKILL.md +367 -367
  76. package/kit/skills/retry-strategies/SKILL.md +372 -372
  77. package/kit/skills/sre-risk-management/SKILL.md +221 -221
  78. package/kit/skills/structured-events/SKILL.md +265 -265
  79. package/kit/skills/supabase-cron-queues/SKILL.md +275 -275
  80. package/kit/skills/supabase-database-functions/SKILL.md +332 -332
  81. package/kit/skills/supabase-declarative-schema/SKILL.md +183 -183
  82. package/kit/skills/supabase-pgvector-rag/SKILL.md +253 -253
  83. package/kit/skills/supabase-postgres-style/SKILL.md +138 -138
  84. package/kit/skills/supabase-storage/SKILL.md +234 -234
  85. package/kit/skills/telemetry-pipelines/SKILL.md +259 -259
  86. package/kit/skills/telemetry-sampling/SKILL.md +256 -256
  87. package/kit/skills/ui-anti-padroes-ia/SKILL.md +261 -261
  88. package/kit/skills/ui-contexto-produto/SKILL.md +248 -248
  89. package/kit/skills/ui-cor-estrategia/SKILL.md +213 -213
  90. package/kit/skills/ui-critica-auditoria/SKILL.md +260 -260
  91. package/kit/skills/ui-motion-funcional/SKILL.md +264 -264
  92. package/kit/skills/ui-ritmo-espacial/SKILL.md +259 -259
  93. package/kit/skills/ui-tipografia/SKILL.md +211 -211
  94. package/package.json +1 -1
  95. package/src/cli/index.js +1114 -1114
  96. package/src/cli/render.js +194 -194
  97. package/src/cli/upgrade-check.js +135 -135
  98. package/src/core/error-redaction.js +76 -76
  99. package/src/core/failures.js +153 -153
  100. package/src/core/gate-runner.js +205 -205
  101. package/src/core/gates.js +82 -82
  102. package/src/core/logger.js +170 -170
  103. package/src/core/manifest-verify.js +174 -174
  104. package/src/core/metrics.js +268 -268
  105. package/src/core/notify.js +60 -60
  106. package/src/core/path-safety.js +141 -141
  107. package/src/core/replays.js +120 -120
  108. package/src/core/ui.js +185 -185
  109. package/src/mcp-server/install.js +149 -149
  110. package/src/mcp-server/roots.js +124 -124
  111. package/src/ui/auto-spawn.js +113 -113
  112. package/src/ui/browser.js +78 -78
  113. package/src/ui/client.js +130 -130
  114. package/src/ui/events.js +65 -65
  115. package/src/ui/lockfile.js +191 -191
  116. package/src/ui/port.js +67 -67
  117. package/src/ui/server.js +547 -547
  118. package/src/ui/wrapper.js +129 -129
@@ -1,124 +1,124 @@
1
- // src/mcp-server/roots.js — MCP `roots` capability consumer.
2
- //
3
- // Phase 166 (v1.29). The MCP spec lets clients (hosts like Claude Code,
4
- // Cursor) declare workspace roots via `roots/list`. Servers can query this
5
- // to learn the project directory without guessing from `process.cwd()`.
6
- //
7
- // Flow:
8
- // 1. Server declares capability `roots: { listChanged: true }` on init.
9
- // 2. After `initialized` notification, server sends `roots/list` request.
10
- // 3. Cache the response in memory.
11
- // 4. Listen for `notifications/roots/list_changed` to refresh cache.
12
- //
13
- // Discipline:
14
- // - Failures are silent — fallback to process.cwd() if host doesn't support.
15
- // - Cache survives the session; not persisted to disk.
16
- // - No side effects (the auto-sync that USES the roots lives in another module).
17
-
18
- import { ListRootsRequestSchema, RootsListChangedNotificationSchema } from '@modelcontextprotocol/sdk/types.js';
19
- import { fileURLToPath } from 'node:url';
20
-
21
- // Module-level cache. Keyed by server instance via closure in attachRootsCapability.
22
- let cachedRoots = null;
23
- let supportLevel = 'unknown'; // 'supported' | 'unsupported' | 'unknown'
24
-
25
- /**
26
- * Convert a file:// URI to a local filesystem path. Returns null if invalid.
27
- * @param {string} uri
28
- */
29
- function uriToPath(uri) {
30
- if (typeof uri !== 'string') return null;
31
- if (!uri.startsWith('file://')) return null;
32
- try {
33
- return fileURLToPath(uri);
34
- } catch {
35
- return null;
36
- }
37
- }
38
-
39
- /**
40
- * Request roots/list from the connected client. Caches the result.
41
- * Returns array of {uri, name, path} entries, or [] on failure.
42
- * @param {import('@modelcontextprotocol/sdk/server/index.js').Server} server
43
- */
44
- export async function fetchRoots(server) {
45
- try {
46
- const result = await server.request(
47
- { method: 'roots/list' },
48
- // The SDK validates the response shape with this schema
49
- // eslint-disable-next-line no-undef
50
- // @ts-ignore — runtime-only import shape
51
- undefined,
52
- );
53
- // Defensive: SDK may return either {roots: [...]} or the bare array depending on version
54
- const roots = Array.isArray(result?.roots) ? result.roots
55
- : Array.isArray(result) ? result
56
- : [];
57
- const normalized = roots.map((r) => ({
58
- uri: r.uri,
59
- name: r.name,
60
- path: uriToPath(r.uri),
61
- })).filter((r) => r.path);
62
- cachedRoots = normalized;
63
- supportLevel = 'supported';
64
- return normalized;
65
- } catch (e) {
66
- // Client doesn't support roots, or returned an error.
67
- supportLevel = 'unsupported';
68
- cachedRoots = [];
69
- return [];
70
- }
71
- }
72
-
73
- /**
74
- * Attach roots capability handlers to the server. Must be called BEFORE
75
- * server.connect(). Sets up the list_changed listener so cache stays fresh.
76
- * @param {import('@modelcontextprotocol/sdk/server/index.js').Server} server
77
- */
78
- export function attachRootsCapability(server) {
79
- // Listen for client telling us roots changed — invalidate cache.
80
- server.setNotificationHandler(RootsListChangedNotificationSchema, async () => {
81
- // Re-fetch on next access via fetchRoots(). Mark cache stale.
82
- cachedRoots = null;
83
- // Eager refresh — best-effort.
84
- try { await fetchRoots(server); } catch { /* swallow */ }
85
- });
86
- }
87
-
88
- /**
89
- * Get the currently-cached roots, or trigger a fetch if not yet cached.
90
- * Returns array of {uri, name, path}.
91
- * @param {import('@modelcontextprotocol/sdk/server/index.js').Server} server
92
- */
93
- export async function getRoots(server) {
94
- if (cachedRoots !== null) return cachedRoots;
95
- return await fetchRoots(server);
96
- }
97
-
98
- /**
99
- * Get the primary project root path. Falls back to process.cwd() if no
100
- * roots were declared by the client. Synchronous accessor for use AFTER
101
- * fetchRoots() has been called at least once.
102
- */
103
- export function getPrimaryProjectRoot() {
104
- if (cachedRoots && cachedRoots.length > 0) {
105
- return cachedRoots[0].path;
106
- }
107
- return process.cwd();
108
- }
109
-
110
- /**
111
- * Diagnostic helper — exposes whether host declared roots support.
112
- * Values: 'supported' | 'unsupported' | 'unknown'.
113
- */
114
- export function getRootsSupportLevel() {
115
- return supportLevel;
116
- }
117
-
118
- /**
119
- * Reset state. Test helper only.
120
- */
121
- export function __resetForTests() {
122
- cachedRoots = null;
123
- supportLevel = 'unknown';
124
- }
1
+ // src/mcp-server/roots.js — MCP `roots` capability consumer.
2
+ //
3
+ // Phase 166 (v1.29). The MCP spec lets clients (hosts like Claude Code,
4
+ // Cursor) declare workspace roots via `roots/list`. Servers can query this
5
+ // to learn the project directory without guessing from `process.cwd()`.
6
+ //
7
+ // Flow:
8
+ // 1. Server declares capability `roots: { listChanged: true }` on init.
9
+ // 2. After `initialized` notification, server sends `roots/list` request.
10
+ // 3. Cache the response in memory.
11
+ // 4. Listen for `notifications/roots/list_changed` to refresh cache.
12
+ //
13
+ // Discipline:
14
+ // - Failures are silent — fallback to process.cwd() if host doesn't support.
15
+ // - Cache survives the session; not persisted to disk.
16
+ // - No side effects (the auto-sync that USES the roots lives in another module).
17
+
18
+ import { ListRootsRequestSchema, RootsListChangedNotificationSchema } from '@modelcontextprotocol/sdk/types.js';
19
+ import { fileURLToPath } from 'node:url';
20
+
21
+ // Module-level cache. Keyed by server instance via closure in attachRootsCapability.
22
+ let cachedRoots = null;
23
+ let supportLevel = 'unknown'; // 'supported' | 'unsupported' | 'unknown'
24
+
25
+ /**
26
+ * Convert a file:// URI to a local filesystem path. Returns null if invalid.
27
+ * @param {string} uri
28
+ */
29
+ function uriToPath(uri) {
30
+ if (typeof uri !== 'string') return null;
31
+ if (!uri.startsWith('file://')) return null;
32
+ try {
33
+ return fileURLToPath(uri);
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Request roots/list from the connected client. Caches the result.
41
+ * Returns array of {uri, name, path} entries, or [] on failure.
42
+ * @param {import('@modelcontextprotocol/sdk/server/index.js').Server} server
43
+ */
44
+ export async function fetchRoots(server) {
45
+ try {
46
+ const result = await server.request(
47
+ { method: 'roots/list' },
48
+ // The SDK validates the response shape with this schema
49
+ // eslint-disable-next-line no-undef
50
+ // @ts-ignore — runtime-only import shape
51
+ undefined,
52
+ );
53
+ // Defensive: SDK may return either {roots: [...]} or the bare array depending on version
54
+ const roots = Array.isArray(result?.roots) ? result.roots
55
+ : Array.isArray(result) ? result
56
+ : [];
57
+ const normalized = roots.map((r) => ({
58
+ uri: r.uri,
59
+ name: r.name,
60
+ path: uriToPath(r.uri),
61
+ })).filter((r) => r.path);
62
+ cachedRoots = normalized;
63
+ supportLevel = 'supported';
64
+ return normalized;
65
+ } catch (e) {
66
+ // Client doesn't support roots, or returned an error.
67
+ supportLevel = 'unsupported';
68
+ cachedRoots = [];
69
+ return [];
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Attach roots capability handlers to the server. Must be called BEFORE
75
+ * server.connect(). Sets up the list_changed listener so cache stays fresh.
76
+ * @param {import('@modelcontextprotocol/sdk/server/index.js').Server} server
77
+ */
78
+ export function attachRootsCapability(server) {
79
+ // Listen for client telling us roots changed — invalidate cache.
80
+ server.setNotificationHandler(RootsListChangedNotificationSchema, async () => {
81
+ // Re-fetch on next access via fetchRoots(). Mark cache stale.
82
+ cachedRoots = null;
83
+ // Eager refresh — best-effort.
84
+ try { await fetchRoots(server); } catch { /* swallow */ }
85
+ });
86
+ }
87
+
88
+ /**
89
+ * Get the currently-cached roots, or trigger a fetch if not yet cached.
90
+ * Returns array of {uri, name, path}.
91
+ * @param {import('@modelcontextprotocol/sdk/server/index.js').Server} server
92
+ */
93
+ export async function getRoots(server) {
94
+ if (cachedRoots !== null) return cachedRoots;
95
+ return await fetchRoots(server);
96
+ }
97
+
98
+ /**
99
+ * Get the primary project root path. Falls back to process.cwd() if no
100
+ * roots were declared by the client. Synchronous accessor for use AFTER
101
+ * fetchRoots() has been called at least once.
102
+ */
103
+ export function getPrimaryProjectRoot() {
104
+ if (cachedRoots && cachedRoots.length > 0) {
105
+ return cachedRoots[0].path;
106
+ }
107
+ return process.cwd();
108
+ }
109
+
110
+ /**
111
+ * Diagnostic helper — exposes whether host declared roots support.
112
+ * Values: 'supported' | 'unsupported' | 'unknown'.
113
+ */
114
+ export function getRootsSupportLevel() {
115
+ return supportLevel;
116
+ }
117
+
118
+ /**
119
+ * Reset state. Test helper only.
120
+ */
121
+ export function __resetForTests() {
122
+ cachedRoots = null;
123
+ supportLevel = 'unknown';
124
+ }
@@ -1,113 +1,113 @@
1
- // src/ui/auto-spawn.js
2
- // Spawn the sidecar in a detached subprocess and wait until it's healthy.
3
- // Used by MCP tool handlers when the caller passes `autoSpawn: true` and no
4
- // sidecar lockfile is present for the project.
5
- //
6
- // Discipline: stderr/file logging only. Audit gate enforced.
7
-
8
- import { spawn } from 'node:child_process';
9
- import http from 'node:http';
10
- import path from 'node:path';
11
- import process from 'node:process';
12
- import { fileURLToPath } from 'node:url';
13
-
14
- import { readLock } from './lockfile.js';
15
- import { openBrowser } from './browser.js';
16
-
17
- const HERE = path.dirname(fileURLToPath(import.meta.url));
18
- // src/ui → src → repo root → bin/ui.js
19
- const UI_BIN = path.resolve(HERE, '..', '..', 'bin', 'ui.js');
20
-
21
- const POLL_INTERVAL_MS = 100;
22
- const POLL_TIMEOUT_MS = 5000;
23
-
24
- // healthzOk returns true if GET /healthz on this port responds 200 within 1s.
25
- function healthzOk(port) {
26
- return new Promise((resolve) => {
27
- const req = http.request({
28
- method: 'GET',
29
- host: '127.0.0.1',
30
- port,
31
- path: '/healthz',
32
- agent: false,
33
- headers: { host: `127.0.0.1:${port}`, connection: 'close' },
34
- }, (res) => {
35
- res.resume();
36
- res.on('end', () => resolve(res.statusCode === 200));
37
- });
38
- req.on('error', () => resolve(false));
39
- req.setTimeout(800, () => { try { req.destroy(); } catch { /* noop */ } resolve(false); });
40
- req.end();
41
- });
42
- }
43
-
44
- async function waitForHealth(projectRoot, deadline) {
45
- // Poll for lockfile + healthz until deadline.
46
- while (Date.now() < deadline) {
47
- const lock = readLock(projectRoot);
48
- if (lock?.port) {
49
- // eslint-disable-next-line no-await-in-loop
50
- if (await healthzOk(lock.port)) return lock;
51
- }
52
- // eslint-disable-next-line no-await-in-loop
53
- await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
54
- }
55
- return null;
56
- }
57
-
58
- // ensureSidecar({projectRoot, openBrowser?}): if a sidecar is already running
59
- // for this projectRoot, returns immediately with its lock metadata. Otherwise
60
- // spawns bin/ui.js detached and waits for it to come online, then optionally
61
- // opens the browser. Resolves to:
62
- // { ready: true, port, spawned: bool, opened: bool } on success
63
- // { ready: false, reason } on timeout/spawn-fail
64
- export async function ensureSidecar({ projectRoot, openBrowserOnSpawn = true } = {}) {
65
- if (!projectRoot) return { ready: false, reason: 'no_project_root' };
66
-
67
- // Already running?
68
- const existing = readLock(projectRoot);
69
- if (existing?.port) {
70
- if (await healthzOk(existing.port)) {
71
- return { ready: true, port: existing.port, spawned: false, opened: false };
72
- }
73
- // Stale lockfile — let the spawn step reclaim it.
74
- }
75
-
76
- // Spawn detached. Inherits stderr only — stdout is closed so a buggy child
77
- // can never poison parent's stdout (e.g. when the parent is the MCP server
78
- // running on stdio).
79
- let child;
80
- try {
81
- child = spawn(process.execPath, [UI_BIN, '--project-root', projectRoot], {
82
- detached: true,
83
- stdio: ['ignore', 'ignore', 'inherit'],
84
- windowsHide: true,
85
- });
86
- child.unref();
87
- } catch (err) {
88
- return { ready: false, reason: `spawn_failed: ${err.message}` };
89
- }
90
-
91
- // Wait for it to come online.
92
- const deadline = Date.now() + POLL_TIMEOUT_MS;
93
- const lock = await waitForHealth(projectRoot, deadline);
94
- if (!lock) {
95
- return { ready: false, reason: 'healthz_timeout' };
96
- }
97
-
98
- let opened = false;
99
- if (openBrowserOnSpawn) {
100
- // SEC-14-02: propagate auth token via query param so browser can self-authenticate
101
- // without user interaction. EventSource cannot send custom headers; ?t= is the
102
- // canonical pattern. The browser scrubs ?t= from the address bar via
103
- // history.replaceState immediately on boot to avoid leak via screenshare.
104
- const tokenSuffix = lock.token ? `?t=${encodeURIComponent(lock.token)}` : '';
105
- const url = `http://127.0.0.1:${lock.port}/${tokenSuffix}`;
106
- const r = await openBrowser(url);
107
- opened = r.opened === true;
108
- }
109
-
110
- return { ready: true, port: lock.port, spawned: true, opened };
111
- }
112
-
113
- export const __test = { healthzOk, UI_BIN, POLL_INTERVAL_MS, POLL_TIMEOUT_MS };
1
+ // src/ui/auto-spawn.js
2
+ // Spawn the sidecar in a detached subprocess and wait until it's healthy.
3
+ // Used by MCP tool handlers when the caller passes `autoSpawn: true` and no
4
+ // sidecar lockfile is present for the project.
5
+ //
6
+ // Discipline: stderr/file logging only. Audit gate enforced.
7
+
8
+ import { spawn } from 'node:child_process';
9
+ import http from 'node:http';
10
+ import path from 'node:path';
11
+ import process from 'node:process';
12
+ import { fileURLToPath } from 'node:url';
13
+
14
+ import { readLock } from './lockfile.js';
15
+ import { openBrowser } from './browser.js';
16
+
17
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
18
+ // src/ui → src → repo root → bin/ui.js
19
+ const UI_BIN = path.resolve(HERE, '..', '..', 'bin', 'ui.js');
20
+
21
+ const POLL_INTERVAL_MS = 100;
22
+ const POLL_TIMEOUT_MS = 5000;
23
+
24
+ // healthzOk returns true if GET /healthz on this port responds 200 within 1s.
25
+ function healthzOk(port) {
26
+ return new Promise((resolve) => {
27
+ const req = http.request({
28
+ method: 'GET',
29
+ host: '127.0.0.1',
30
+ port,
31
+ path: '/healthz',
32
+ agent: false,
33
+ headers: { host: `127.0.0.1:${port}`, connection: 'close' },
34
+ }, (res) => {
35
+ res.resume();
36
+ res.on('end', () => resolve(res.statusCode === 200));
37
+ });
38
+ req.on('error', () => resolve(false));
39
+ req.setTimeout(800, () => { try { req.destroy(); } catch { /* noop */ } resolve(false); });
40
+ req.end();
41
+ });
42
+ }
43
+
44
+ async function waitForHealth(projectRoot, deadline) {
45
+ // Poll for lockfile + healthz until deadline.
46
+ while (Date.now() < deadline) {
47
+ const lock = readLock(projectRoot);
48
+ if (lock?.port) {
49
+ // eslint-disable-next-line no-await-in-loop
50
+ if (await healthzOk(lock.port)) return lock;
51
+ }
52
+ // eslint-disable-next-line no-await-in-loop
53
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
54
+ }
55
+ return null;
56
+ }
57
+
58
+ // ensureSidecar({projectRoot, openBrowser?}): if a sidecar is already running
59
+ // for this projectRoot, returns immediately with its lock metadata. Otherwise
60
+ // spawns bin/ui.js detached and waits for it to come online, then optionally
61
+ // opens the browser. Resolves to:
62
+ // { ready: true, port, spawned: bool, opened: bool } on success
63
+ // { ready: false, reason } on timeout/spawn-fail
64
+ export async function ensureSidecar({ projectRoot, openBrowserOnSpawn = true } = {}) {
65
+ if (!projectRoot) return { ready: false, reason: 'no_project_root' };
66
+
67
+ // Already running?
68
+ const existing = readLock(projectRoot);
69
+ if (existing?.port) {
70
+ if (await healthzOk(existing.port)) {
71
+ return { ready: true, port: existing.port, spawned: false, opened: false };
72
+ }
73
+ // Stale lockfile — let the spawn step reclaim it.
74
+ }
75
+
76
+ // Spawn detached. Inherits stderr only — stdout is closed so a buggy child
77
+ // can never poison parent's stdout (e.g. when the parent is the MCP server
78
+ // running on stdio).
79
+ let child;
80
+ try {
81
+ child = spawn(process.execPath, [UI_BIN, '--project-root', projectRoot], {
82
+ detached: true,
83
+ stdio: ['ignore', 'ignore', 'inherit'],
84
+ windowsHide: true,
85
+ });
86
+ child.unref();
87
+ } catch (err) {
88
+ return { ready: false, reason: `spawn_failed: ${err.message}` };
89
+ }
90
+
91
+ // Wait for it to come online.
92
+ const deadline = Date.now() + POLL_TIMEOUT_MS;
93
+ const lock = await waitForHealth(projectRoot, deadline);
94
+ if (!lock) {
95
+ return { ready: false, reason: 'healthz_timeout' };
96
+ }
97
+
98
+ let opened = false;
99
+ if (openBrowserOnSpawn) {
100
+ // SEC-14-02: propagate auth token via query param so browser can self-authenticate
101
+ // without user interaction. EventSource cannot send custom headers; ?t= is the
102
+ // canonical pattern. The browser scrubs ?t= from the address bar via
103
+ // history.replaceState immediately on boot to avoid leak via screenshare.
104
+ const tokenSuffix = lock.token ? `?t=${encodeURIComponent(lock.token)}` : '';
105
+ const url = `http://127.0.0.1:${lock.port}/${tokenSuffix}`;
106
+ const r = await openBrowser(url);
107
+ opened = r.opened === true;
108
+ }
109
+
110
+ return { ready: true, port: lock.port, spawned: true, opened };
111
+ }
112
+
113
+ export const __test = { healthzOk, UI_BIN, POLL_INTERVAL_MS, POLL_TIMEOUT_MS };
package/src/ui/browser.js CHANGED
@@ -1,78 +1,78 @@
1
- // src/ui/browser.js
2
- // Cross-platform browser opener. Wraps `open@11` with detection for environments
3
- // where launching a browser silently fails (CI, headless SSH, WSL, sandboxed
4
- // macOS Terminal). In those environments we DON'T attempt to launch — we just
5
- // print the URL to stderr so the user can copy it.
6
- //
7
- // Discipline: nothing on stdout. Audit gate enforced by Phase 11 CI.
8
-
9
- import process from 'node:process';
10
-
11
- let openModule = null;
12
-
13
- async function loadOpen() {
14
- if (openModule) return openModule;
15
- try {
16
- const mod = await import('open');
17
- openModule = mod.default || mod;
18
- return openModule;
19
- } catch (err) {
20
- return null;
21
- }
22
- }
23
-
24
- // isHeadless heuristics — designed to err on the side of NOT launching.
25
- // Returns a reason string when headless, or null when a browser launch is plausible.
26
- export function detectHeadless(env = process.env, plat = process.platform) {
27
- if (env.CI && env.CI !== 'false') return 'CI=' + env.CI;
28
- if (env.KIT_MCP_NO_OPEN === '1' || env.KIT_MCP_NO_OPEN === 'true') return 'KIT_MCP_NO_OPEN';
29
- if (env.TERM === 'dumb') return 'TERM=dumb';
30
- // Linux without a display server is headless. WSL is special: it forwards
31
- // to the Windows host browser via wslview, so we let `open` try.
32
- if (plat === 'linux' && !env.DISPLAY && !env.WAYLAND_DISPLAY) {
33
- if (env.WSL_DISTRO_NAME || env.WSLENV) return null; // WSL — let `open` try (it'll use wslview)
34
- return 'no_display';
35
- }
36
- // SSH session without local display — no good way to open in user's browser.
37
- if (env.SSH_CONNECTION && plat !== 'win32' && !env.DISPLAY && !env.WAYLAND_DISPLAY) {
38
- return 'ssh_no_display';
39
- }
40
- return null;
41
- }
42
-
43
- // openBrowser(url, opts):
44
- // { opened: true, via: 'open' } on success
45
- // { opened: false, reason: 'headless:<why>', url } when headless detected
46
- // { opened: false, reason: 'no_module' } if `open` package missing
47
- // { opened: false, reason: 'launch_failed:<msg>' } if open() throws
48
- //
49
- // Always calls process.stderr.write with the URL so the user can copy it manually.
50
- export async function openBrowser(url, { force = false } = {}) {
51
- process.stderr.write(`[kit-mcp ui] ${url}\n`);
52
-
53
- if (!force) {
54
- const headless = detectHeadless();
55
- if (headless) {
56
- process.stderr.write(`[kit-mcp ui] not opening browser (${headless}) — open the URL above manually\n`);
57
- return { opened: false, reason: `headless:${headless}`, url };
58
- }
59
- }
60
-
61
- const open = await loadOpen();
62
- if (!open) {
63
- process.stderr.write('[kit-mcp ui] `open` package not available — open the URL above manually\n');
64
- return { opened: false, reason: 'no_module' };
65
- }
66
-
67
- try {
68
- // open() returns a child process; we don't await its exit (it's the browser).
69
- // We just need to know that the spawn succeeded.
70
- await open(url);
71
- return { opened: true, via: 'open' };
72
- } catch (err) {
73
- process.stderr.write(`[kit-mcp ui] browser launch failed: ${err.message} — open the URL above manually\n`);
74
- return { opened: false, reason: `launch_failed:${err.message}` };
75
- }
76
- }
77
-
78
- export const __test = { loadOpen };
1
+ // src/ui/browser.js
2
+ // Cross-platform browser opener. Wraps `open@11` with detection for environments
3
+ // where launching a browser silently fails (CI, headless SSH, WSL, sandboxed
4
+ // macOS Terminal). In those environments we DON'T attempt to launch — we just
5
+ // print the URL to stderr so the user can copy it.
6
+ //
7
+ // Discipline: nothing on stdout. Audit gate enforced by Phase 11 CI.
8
+
9
+ import process from 'node:process';
10
+
11
+ let openModule = null;
12
+
13
+ async function loadOpen() {
14
+ if (openModule) return openModule;
15
+ try {
16
+ const mod = await import('open');
17
+ openModule = mod.default || mod;
18
+ return openModule;
19
+ } catch (err) {
20
+ return null;
21
+ }
22
+ }
23
+
24
+ // isHeadless heuristics — designed to err on the side of NOT launching.
25
+ // Returns a reason string when headless, or null when a browser launch is plausible.
26
+ export function detectHeadless(env = process.env, plat = process.platform) {
27
+ if (env.CI && env.CI !== 'false') return 'CI=' + env.CI;
28
+ if (env.KIT_MCP_NO_OPEN === '1' || env.KIT_MCP_NO_OPEN === 'true') return 'KIT_MCP_NO_OPEN';
29
+ if (env.TERM === 'dumb') return 'TERM=dumb';
30
+ // Linux without a display server is headless. WSL is special: it forwards
31
+ // to the Windows host browser via wslview, so we let `open` try.
32
+ if (plat === 'linux' && !env.DISPLAY && !env.WAYLAND_DISPLAY) {
33
+ if (env.WSL_DISTRO_NAME || env.WSLENV) return null; // WSL — let `open` try (it'll use wslview)
34
+ return 'no_display';
35
+ }
36
+ // SSH session without local display — no good way to open in user's browser.
37
+ if (env.SSH_CONNECTION && plat !== 'win32' && !env.DISPLAY && !env.WAYLAND_DISPLAY) {
38
+ return 'ssh_no_display';
39
+ }
40
+ return null;
41
+ }
42
+
43
+ // openBrowser(url, opts):
44
+ // { opened: true, via: 'open' } on success
45
+ // { opened: false, reason: 'headless:<why>', url } when headless detected
46
+ // { opened: false, reason: 'no_module' } if `open` package missing
47
+ // { opened: false, reason: 'launch_failed:<msg>' } if open() throws
48
+ //
49
+ // Always calls process.stderr.write with the URL so the user can copy it manually.
50
+ export async function openBrowser(url, { force = false } = {}) {
51
+ process.stderr.write(`[kit-mcp ui] ${url}\n`);
52
+
53
+ if (!force) {
54
+ const headless = detectHeadless();
55
+ if (headless) {
56
+ process.stderr.write(`[kit-mcp ui] not opening browser (${headless}) — open the URL above manually\n`);
57
+ return { opened: false, reason: `headless:${headless}`, url };
58
+ }
59
+ }
60
+
61
+ const open = await loadOpen();
62
+ if (!open) {
63
+ process.stderr.write('[kit-mcp ui] `open` package not available — open the URL above manually\n');
64
+ return { opened: false, reason: 'no_module' };
65
+ }
66
+
67
+ try {
68
+ // open() returns a child process; we don't await its exit (it's the browser).
69
+ // We just need to know that the spawn succeeded.
70
+ await open(url);
71
+ return { opened: true, via: 'open' };
72
+ } catch (err) {
73
+ process.stderr.write(`[kit-mcp ui] browser launch failed: ${err.message} — open the URL above manually\n`);
74
+ return { opened: false, reason: `launch_failed:${err.message}` };
75
+ }
76
+ }
77
+
78
+ export const __test = { loadOpen };