@bonesofspring/ai-rules 0.2.52 → 0.2.53

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 (134) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +27 -3
  3. package/bin/cli.js +551 -60
  4. package/bin/lib/engine-scripts.js +10 -0
  5. package/bin/lib/mcp/clients.js +168 -0
  6. package/bin/lib/mcp/credentials.js +298 -0
  7. package/bin/lib/mcp/doctor.js +394 -0
  8. package/bin/lib/mcp/prompt.js +115 -0
  9. package/bin/lib/mcp/registry.js +170 -0
  10. package/bin/lib/mcp/run.js +123 -0
  11. package/bin/lib/merged-config.js +45 -0
  12. package/bin/lib/seed-ai-local-team.js +5 -0
  13. package/bin/lib/tool-installs.js +27 -0
  14. package/docs/MCP-SETUP.md +62 -0
  15. package/docs/PRESET-CONTRIBUTION.md +3 -1
  16. package/docs/TEAM-DB.md +173 -0
  17. package/docs/openapi/team-db.v1.json +5085 -0
  18. package/mcp/gitlab.mjs +123 -0
  19. package/mcp/lib/envfile.mjs +126 -0
  20. package/mcp/lib/yandex.mjs +384 -0
  21. package/mcp/yandex-mcp-proxy.mjs +155 -0
  22. package/mcp/yandex-token-refresh.mjs +65 -0
  23. package/package.json +14 -1
  24. package/presets/_shared/ai-local/scripts/manifest.mjs +99 -0
  25. package/presets/_shared/ai-local/scripts/team-db-api.mjs +1275 -0
  26. package/presets/_shared/ai-local/scripts/team-db-dashboard.mjs +1067 -0
  27. package/presets/_shared/ai-local/scripts/team-db-openapi.mjs +1301 -0
  28. package/presets/_shared/ai-local/scripts/team-db-project.mjs +1506 -0
  29. package/presets/_shared/ai-local/scripts/team-db-schema.mjs +831 -0
  30. package/presets/_shared/ai-local/scripts/team-db.mjs +251 -0
  31. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +109 -0
  32. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +109 -0
  33. package/presets/claude/android-kotlin/team/README.md +10 -0
  34. package/presets/claude/go/hooks/chain-team-phases.sh +109 -0
  35. package/presets/claude/go/team/README.md +10 -0
  36. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +109 -0
  37. package/presets/claude/ios-swift/team/README.md +10 -0
  38. package/presets/claude/java/hooks/chain-team-phases.sh +109 -0
  39. package/presets/claude/java/team/README.md +10 -0
  40. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +109 -0
  41. package/presets/claude/mcp-ts/team/README.md +10 -0
  42. package/presets/claude/next/hooks/chain-team-phases.sh +109 -0
  43. package/presets/claude/next/team/README.md +10 -0
  44. package/presets/claude/nuxt/hooks/chain-team-phases.sh +109 -0
  45. package/presets/claude/nuxt/team/README.md +10 -0
  46. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +109 -0
  47. package/presets/claude/php-hexagonal/team/README.md +10 -0
  48. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +109 -0
  49. package/presets/claude/php-laravel/team/README.md +10 -0
  50. package/presets/claude/svelte/hooks/chain-team-phases.sh +109 -0
  51. package/presets/claude/svelte/team/README.md +10 -0
  52. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +109 -0
  53. package/presets/cursor/android-kotlin/team/README.md +10 -0
  54. package/presets/cursor/go/hooks/chain-team-phases.sh +109 -0
  55. package/presets/cursor/go/team/README.md +10 -0
  56. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +109 -0
  57. package/presets/cursor/ios-swift/team/README.md +10 -0
  58. package/presets/cursor/java/hooks/chain-team-phases.sh +109 -0
  59. package/presets/cursor/java/team/README.md +10 -0
  60. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +109 -0
  61. package/presets/cursor/mcp-ts/team/README.md +10 -0
  62. package/presets/cursor/next/MCP.md +7 -0
  63. package/presets/cursor/next/hooks/chain-team-phases.sh +109 -0
  64. package/presets/cursor/next/team/README.md +10 -0
  65. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +109 -0
  66. package/presets/cursor/nuxt/team/README.md +10 -0
  67. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +109 -0
  68. package/presets/cursor/php-hexagonal/team/README.md +10 -0
  69. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +109 -0
  70. package/presets/cursor/php-laravel/team/README.md +10 -0
  71. package/presets/cursor/svelte/hooks/chain-team-phases.sh +109 -0
  72. package/presets/cursor/svelte/team/README.md +10 -0
  73. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  74. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +109 -0
  75. package/presets/mavis/android-kotlin/team/README.md +10 -0
  76. package/presets/mavis/go/adapter-map.json +1 -1
  77. package/presets/mavis/go/hooks/chain-team-phases.sh +109 -0
  78. package/presets/mavis/go/team/README.md +10 -0
  79. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  80. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +109 -0
  81. package/presets/mavis/ios-swift/team/README.md +10 -0
  82. package/presets/mavis/java/adapter-map.json +1 -1
  83. package/presets/mavis/java/hooks/chain-team-phases.sh +109 -0
  84. package/presets/mavis/java/team/README.md +10 -0
  85. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  86. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +109 -0
  87. package/presets/mavis/mcp-ts/team/README.md +10 -0
  88. package/presets/mavis/next/MCP.md +7 -0
  89. package/presets/mavis/next/adapter-map.json +1 -1
  90. package/presets/mavis/next/hooks/chain-team-phases.sh +109 -0
  91. package/presets/mavis/next/team/README.md +10 -0
  92. package/presets/mavis/nuxt/adapter-map.json +1 -1
  93. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +109 -0
  94. package/presets/mavis/nuxt/team/README.md +10 -0
  95. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  96. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +109 -0
  97. package/presets/mavis/php-hexagonal/team/README.md +10 -0
  98. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  99. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +109 -0
  100. package/presets/mavis/php-laravel/team/README.md +10 -0
  101. package/presets/mavis/svelte/adapter-map.json +1 -1
  102. package/presets/mavis/svelte/hooks/chain-team-phases.sh +109 -0
  103. package/presets/mavis/svelte/team/README.md +10 -0
  104. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  105. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +109 -0
  106. package/presets/opencode/android-kotlin/team/README.md +10 -0
  107. package/presets/opencode/go/adapter-map.json +1 -1
  108. package/presets/opencode/go/hooks/chain-team-phases.sh +109 -0
  109. package/presets/opencode/go/team/README.md +10 -0
  110. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  111. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +109 -0
  112. package/presets/opencode/ios-swift/team/README.md +10 -0
  113. package/presets/opencode/java/adapter-map.json +1 -1
  114. package/presets/opencode/java/hooks/chain-team-phases.sh +109 -0
  115. package/presets/opencode/java/team/README.md +10 -0
  116. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  117. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +109 -0
  118. package/presets/opencode/mcp-ts/team/README.md +10 -0
  119. package/presets/opencode/next/MCP.md +7 -0
  120. package/presets/opencode/next/adapter-map.json +1 -1
  121. package/presets/opencode/next/hooks/chain-team-phases.sh +109 -0
  122. package/presets/opencode/next/team/README.md +10 -0
  123. package/presets/opencode/nuxt/adapter-map.json +1 -1
  124. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +109 -0
  125. package/presets/opencode/nuxt/team/README.md +10 -0
  126. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  127. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +109 -0
  128. package/presets/opencode/php-hexagonal/team/README.md +10 -0
  129. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  130. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +109 -0
  131. package/presets/opencode/php-laravel/team/README.md +10 -0
  132. package/presets/opencode/svelte/adapter-map.json +1 -1
  133. package/presets/opencode/svelte/hooks/chain-team-phases.sh +109 -0
  134. package/presets/opencode/svelte/team/README.md +10 -0
package/mcp/gitlab.mjs ADDED
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * GitLab MCP server (stdio wrapper around the pinned @zereight/mcp-gitlab package).
4
+ *
5
+ * Reads GitLab credentials through the shared order (shell env → the pack's
6
+ * `.ai-rules/mcp/credentials.env` → a legacy root `.env.gitlab`) and maps them to
7
+ * the child env `GITLAB_PERSONAL_ACCESS_TOKEN` / `GITLAB_API_URL`. stdio is
8
+ * forwarded verbatim; any token in the child's stderr is redacted before it
9
+ * reaches the terminal. Started by the client as
10
+ * `npx -y @bonesofspring/ai-rules@<version> mcp run gitlab`.
11
+ */
12
+ import { spawn } from 'node:child_process';
13
+ import { join } from 'node:path';
14
+ import run from '../bin/lib/mcp/run.js';
15
+ import { ConfigError, loadEnvStack, redactToken } from './lib/envfile.mjs';
16
+
17
+ const { resolveProjectRoot } = run;
18
+ const GITLAB_PACKAGE = '@zereight/mcp-gitlab@2.3.22';
19
+
20
+ export function loadGitlabConfig({ env = process.env, root = resolveProjectRoot() } = {}) {
21
+ let values;
22
+
23
+ try {
24
+ values = loadEnvStack({
25
+ files: [
26
+ { path: join(root, '.ai-rules', 'mcp', 'credentials.env'), label: '.ai-rules/mcp/credentials.env' },
27
+ { path: join(root, '.env.gitlab'), label: '.env.gitlab', legacy: true },
28
+ ],
29
+ env,
30
+ required: ['GITLAB_URL', 'GITLAB_TOKEN'],
31
+ legacyHint: 'ai-rules mcp setup gitlab',
32
+ });
33
+ } catch (error) {
34
+ if (error instanceof ConfigError) {
35
+ throw new ConfigError(`${error.message} Run: ai-rules mcp setup gitlab.`);
36
+ }
37
+ throw error;
38
+ }
39
+
40
+ return {
41
+ token: values.GITLAB_TOKEN,
42
+ url: values.GITLAB_URL.replace(/\/+$/, ''),
43
+ };
44
+ }
45
+
46
+ /** `--print-env` is a masked mapping: never echo URL userinfo either. */
47
+ export function printableUrl(value) {
48
+ try {
49
+ const parsed = new URL(value);
50
+ if (!parsed.username && !parsed.password) {
51
+ return value;
52
+ }
53
+ parsed.username = '';
54
+ parsed.password = '';
55
+ const text = parsed.toString();
56
+ return text.endsWith('/') ? text.slice(0, -1) : text;
57
+ } catch {
58
+ return value;
59
+ }
60
+ }
61
+
62
+ export function printEnv(config = loadGitlabConfig()) {
63
+ process.stdout.write('GITLAB_PERSONAL_ACCESS_TOKEN=***\n');
64
+ process.stdout.write(`GITLAB_API_URL=${printableUrl(config.url)}\n`);
65
+ }
66
+
67
+ function runChild({ token, url }) {
68
+ const child = spawn('npx', ['-y', GITLAB_PACKAGE], {
69
+ env: { ...process.env, GITLAB_PERSONAL_ACCESS_TOKEN: token, GITLAB_API_URL: url },
70
+ stdio: ['pipe', 'pipe', 'pipe'],
71
+ });
72
+
73
+ process.stdin.pipe(child.stdin);
74
+
75
+ child.stdout.on('data', (chunk) => {
76
+ process.stdout.write(chunk);
77
+ });
78
+
79
+ child.stderr.on('data', (chunk) => {
80
+ process.stderr.write(redactToken(String(chunk), token));
81
+ });
82
+
83
+ child.on('error', (error) => {
84
+ process.stderr.write(`gitlab-mcp: failed to start ${GITLAB_PACKAGE}: ${redactToken(error.message, token)}\n`);
85
+ process.exit(1);
86
+ });
87
+
88
+ child.on('exit', (code, signal) => {
89
+ if (signal) {
90
+ process.stderr.write(`gitlab-mcp: ${GITLAB_PACKAGE} terminated by ${signal}\n`);
91
+ process.exit(1);
92
+ }
93
+
94
+ process.exit(code ?? 0);
95
+ });
96
+
97
+ for (const signal of ['SIGINT', 'SIGTERM']) {
98
+ process.on(signal, () => {
99
+ if (!child.killed) {
100
+ child.kill(signal);
101
+ }
102
+ });
103
+ }
104
+ }
105
+
106
+ function main() {
107
+ const config = loadGitlabConfig();
108
+
109
+ if (process.argv.includes('--print-env')) {
110
+ printEnv(config);
111
+ return;
112
+ }
113
+
114
+ runChild(config);
115
+ }
116
+
117
+ try {
118
+ main();
119
+ } catch (error) {
120
+ const message = error instanceof Error ? error.message : String(error);
121
+ process.stderr.write(`${message}\n`);
122
+ process.exit(1);
123
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Env resolution for the packaged MCP runtime.
3
+ *
4
+ * Order, identical for both providers: shell env → the pack's own file
5
+ * (`.ai-rules/mcp/*.env`) → the legacy root file (`.env.gitlab` / `.env.yandex`,
6
+ * read-only). The legacy file is never written by this package.
7
+ */
8
+ import { existsSync, readFileSync } from 'node:fs';
9
+
10
+ export class ConfigError extends Error {
11
+ name = 'ConfigError';
12
+ }
13
+
14
+ export function parseEnvFile(text) {
15
+ const values = {};
16
+
17
+ for (const rawLine of text.split(/\r?\n/)) {
18
+ const line = rawLine.trim();
19
+ if (!line || line.startsWith('#')) {
20
+ continue;
21
+ }
22
+
23
+ const separator = line.indexOf('=');
24
+ if (separator === -1) {
25
+ continue;
26
+ }
27
+
28
+ const key = line.slice(0, separator).trim();
29
+ let value = line.slice(separator + 1).trim();
30
+
31
+ if (
32
+ (value.startsWith('"') && value.endsWith('"')) ||
33
+ (value.startsWith("'") && value.endsWith("'"))
34
+ ) {
35
+ value = value.slice(1, -1);
36
+ }
37
+
38
+ values[key] = value;
39
+ }
40
+
41
+ return values;
42
+ }
43
+
44
+ export function redactToken(text, token) {
45
+ if (!token) {
46
+ return text;
47
+ }
48
+
49
+ return text.split(token).join('***');
50
+ }
51
+
52
+ export function readEnvFile(file) {
53
+ return existsSync(file) ? parseEnvFile(readFileSync(file, 'utf8')) : {};
54
+ }
55
+
56
+ function defaultWarn(text) {
57
+ process.stderr.write(`warn ${text}\n`);
58
+ }
59
+
60
+ /**
61
+ * Resolve `keys` across the shell env and an ordered file stack.
62
+ *
63
+ * @param {object} options
64
+ * @param {Array<{path: string, label: string, legacy?: boolean}>} options.files
65
+ * @param {NodeJS.ProcessEnv} [options.env]
66
+ * @param {string[]} [options.required] keys that must resolve to a non-empty value
67
+ * @param {Record<string, string>} [options.defaults]
68
+ * @param {string} [options.fileLabel] primary file named in a ConfigError
69
+ * @param {string} [options.legacyHint] command that moves a legacy file's keys
70
+ * @param {(text: string) => void} [options.warn]
71
+ */
72
+ export function loadEnvStack({
73
+ files,
74
+ env = process.env,
75
+ required = [],
76
+ defaults = {},
77
+ fileLabel = files[0]?.label ?? 'the env file',
78
+ legacyHint,
79
+ warn = defaultWarn,
80
+ }) {
81
+ const parsed = files.map((file) => ({ ...file, values: readEnvFile(file.path) }));
82
+ const values = {};
83
+ const usedLegacy = new Set();
84
+
85
+ for (const key of new Set([...Object.keys(defaults), ...required])) {
86
+ const fromEnv = env[key];
87
+ if (typeof fromEnv === 'string' && fromEnv !== '') {
88
+ values[key] = fromEnv;
89
+ continue;
90
+ }
91
+
92
+ let resolved;
93
+ for (const file of parsed) {
94
+ const value = file.values[key];
95
+ if (typeof value === 'string' && value !== '') {
96
+ resolved = value;
97
+ if (file.legacy) {
98
+ usedLegacy.add(file.label);
99
+ }
100
+ break;
101
+ }
102
+ }
103
+
104
+ values[key] = resolved ?? defaults[key];
105
+ }
106
+
107
+ if (legacyHint) {
108
+ for (const label of usedLegacy) {
109
+ warn(`legacy ${label} still in use; run \`${legacyHint}\` to move it`);
110
+ }
111
+ }
112
+
113
+ const missing = required.filter((key) => !values[key]);
114
+
115
+ if (missing.length > 0) {
116
+ const names = missing.join(', ');
117
+ const noun = missing.length === 1 ? 'is' : 'are';
118
+ const pronoun = missing.length === 1 ? 'it' : 'them';
119
+
120
+ throw new ConfigError(
121
+ `${names} ${noun} not set. Add ${pronoun} to ${fileLabel} or export ${pronoun} in the shell.`,
122
+ );
123
+ }
124
+
125
+ return values;
126
+ }
@@ -0,0 +1,384 @@
1
+ /**
2
+ * Yandex Tracker / Wiki MCP support: IAM token lifecycle + upstream HTTP/SSE
3
+ * transport, shared by the stdio→HTTP proxy and the refresh command.
4
+ *
5
+ * No token is ever stored: the IAM token is fetched from `yc iam create-token`
6
+ * on demand and held in memory only. Config is non-secret and lives in
7
+ * `.ai-rules/mcp/config.env`; the legacy root `.env.yandex` is a read-only
8
+ * fallback for repos that have not migrated yet.
9
+ */
10
+ import { accessSync, constants, readFileSync } from 'node:fs';
11
+ import { homedir } from 'node:os';
12
+ import { spawn } from 'node:child_process';
13
+ import { delimiter, join } from 'node:path';
14
+ import run from '../../bin/lib/mcp/run.js';
15
+ import { ConfigError, loadEnvStack, redactToken } from './envfile.mjs';
16
+
17
+ const { resolveProjectRoot } = run;
18
+
19
+ function packageVersion() {
20
+ try {
21
+ return JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
22
+ } catch {
23
+ return '0.0.0';
24
+ }
25
+ }
26
+
27
+ const VERSION = packageVersion();
28
+
29
+ export const DEFAULT_NO_PROXY = 'yandex.net,yandex.ru,yandex.com,yandex.cloud,yandexcloud.net';
30
+ export const DEFAULT_YC_BIN = 'yc';
31
+
32
+ // Install locations of the Yandex Cloud CLI when it is not on PATH.
33
+ const YC_FALLBACK_BINS = [
34
+ join(homedir(), 'yandex-cloud', 'bin', 'yc'),
35
+ '/opt/homebrew/bin/yc',
36
+ '/usr/local/bin/yc',
37
+ ];
38
+ export const TOKEN_FLOOR = 20;
39
+ export const TOKEN_TIMEOUT_MS = 30_000;
40
+ export const REQUEST_TIMEOUT_MS = 120_000;
41
+
42
+ export const RELOGIN_MESSAGE =
43
+ `Yandex SSO session expired — re-login required. Run: npx -y @bonesofspring/ai-rules@${VERSION} mcp refresh yandex, then reconnect the MCP server.`;
44
+
45
+ const TARGETS = {
46
+ tracker: 'https://mcp.tracker.yandex.net/mcp',
47
+ wiki: 'https://mcp.wiki.yandex.net',
48
+ };
49
+
50
+ export class ReloginError extends Error {
51
+ name = 'ReloginError';
52
+ }
53
+
54
+ export class YcSpawnError extends Error {
55
+ name = 'YcSpawnError';
56
+ }
57
+
58
+ export class YcCommandError extends Error {
59
+ name = 'YcCommandError';
60
+ }
61
+
62
+ export class UnauthorizedError extends Error {
63
+ name = 'UnauthorizedError';
64
+ }
65
+
66
+ export class UpstreamError extends Error {
67
+ name = 'UpstreamError';
68
+ }
69
+
70
+ export function resolveTarget(target) {
71
+ const url = TARGETS[target];
72
+
73
+ if (!url) {
74
+ throw new ConfigError(`Unknown Yandex MCP target: ${target ?? '(none)'} (expected "tracker" or "wiki")`);
75
+ }
76
+
77
+ return url;
78
+ }
79
+
80
+ function isExecutable(path) {
81
+ try {
82
+ accessSync(path, constants.X_OK);
83
+ return true;
84
+ } catch {
85
+ return false;
86
+ }
87
+ }
88
+
89
+ function expandHome(path) {
90
+ return path.startsWith('~/') ? join(homedir(), path.slice(2)) : path;
91
+ }
92
+
93
+ /**
94
+ * GUI-launched MCP clients (OpenCode, Cursor) inherit the launchd PATH, which
95
+ * usually omits `~/yandex-cloud/bin`; resolve `yc` against PATH plus the known
96
+ * install locations so the server does not depend on how the client started.
97
+ */
98
+ export function resolveYcBin(ycBin = DEFAULT_YC_BIN) {
99
+ if (ycBin.includes('/')) {
100
+ return expandHome(ycBin);
101
+ }
102
+
103
+ const fromPath = (process.env.PATH ?? '')
104
+ .split(delimiter)
105
+ .filter(Boolean)
106
+ .map((dir) => join(dir, ycBin))
107
+ .find(isExecutable);
108
+
109
+ return fromPath ?? YC_FALLBACK_BINS.find(isExecutable) ?? ycBin;
110
+ }
111
+
112
+ /** True when `resolveYcBin` produced a path the OS can execute. */
113
+ export function ycAvailable(ycBin = DEFAULT_YC_BIN) {
114
+ const bin = resolveYcBin(ycBin);
115
+ return (bin.includes('/') || bin.includes('\\')) && isExecutable(bin);
116
+ }
117
+
118
+ export function loadYandexConfig({ env = process.env, root = resolveProjectRoot(), requireOrg = true } = {}) {
119
+ let values;
120
+ try {
121
+ values = loadEnvStack({
122
+ files: [
123
+ { path: join(root, '.ai-rules', 'mcp', 'config.env'), label: '.ai-rules/mcp/config.env' },
124
+ { path: join(root, '.env.yandex'), label: '.env.yandex', legacy: true },
125
+ ],
126
+ env,
127
+ required: requireOrg ? ['YANDEX_ORG_ID'] : [],
128
+ defaults: {
129
+ NO_PROXY: DEFAULT_NO_PROXY,
130
+ YC_BIN: DEFAULT_YC_BIN,
131
+ },
132
+ legacyHint: 'ai-rules mcp setup yandex',
133
+ });
134
+ } catch (error) {
135
+ if (error instanceof ConfigError) {
136
+ throw new ConfigError(`${error.message} Run: ai-rules mcp setup yandex.`);
137
+ }
138
+ throw error;
139
+ }
140
+
141
+ return {
142
+ orgId: values.YANDEX_ORG_ID,
143
+ noProxy: values.NO_PROXY,
144
+ ycBin: values.YC_BIN,
145
+ };
146
+ }
147
+
148
+ function isValidToken(token) {
149
+ return token.length >= TOKEN_FLOOR && token.startsWith('t1.');
150
+ }
151
+
152
+ /**
153
+ * Fetch a fresh IAM token from `yc iam create-token`.
154
+ *
155
+ * Non-interactive (`interactive: false`) is the proxy/doctor path: stdout/stderr
156
+ * are piped and a ~30s timeout maps a hung `yc` (expired SSO opens a browser) to a
157
+ * `ReloginError`. Interactive (`interactive: true`) is the refresh path: stdin
158
+ * and stderr are inherited so `yc` can open the browser and complete login,
159
+ * while stdout stays piped for token validation.
160
+ */
161
+ export async function fetchToken({
162
+ interactive = false,
163
+ ycBin = DEFAULT_YC_BIN,
164
+ noProxy = DEFAULT_NO_PROXY,
165
+ timeoutMs = TOKEN_TIMEOUT_MS,
166
+ } = {}) {
167
+ const bin = resolveYcBin(ycBin);
168
+ const stdio = interactive ? ['inherit', 'pipe', 'inherit'] : ['ignore', 'pipe', 'pipe'];
169
+ const child = spawn(bin, ['iam', 'create-token'], {
170
+ env: { ...process.env, NO_PROXY: noProxy },
171
+ stdio,
172
+ });
173
+
174
+ let stdout = '';
175
+
176
+ child.stdout.on('data', (chunk) => {
177
+ stdout += chunk;
178
+ });
179
+
180
+ const result = await new Promise((resolvePromise) => {
181
+ let timer;
182
+
183
+ if (!interactive) {
184
+ timer = setTimeout(() => {
185
+ child.kill('SIGKILL');
186
+ }, timeoutMs);
187
+ }
188
+
189
+ child.on('error', (error) => {
190
+ if (timer) {
191
+ clearTimeout(timer);
192
+ }
193
+
194
+ resolvePromise({ spawnError: error });
195
+ });
196
+
197
+ child.on('close', (code, signal) => {
198
+ if (timer) {
199
+ clearTimeout(timer);
200
+ }
201
+
202
+ resolvePromise({ code, signal });
203
+ });
204
+ });
205
+
206
+ if (result.spawnError) {
207
+ throw new YcSpawnError(
208
+ `Failed to start "${bin}": ${result.spawnError.message}. Install the Yandex Cloud CLI or set YC_BIN in .ai-rules/mcp/config.env.`,
209
+ );
210
+ }
211
+
212
+ if (result.signal) {
213
+ throw new ReloginError(`"${bin} iam create-token" was interrupted (${result.signal}).`);
214
+ }
215
+
216
+ if (result.code !== 0) {
217
+ throw new YcCommandError(`"${bin} iam create-token" exited with code ${result.code}.`);
218
+ }
219
+
220
+ const token = stdout.trim();
221
+
222
+ if (!isValidToken(token)) {
223
+ throw new ReloginError('yc iam create-token did not return a valid IAM token.');
224
+ }
225
+
226
+ return { token };
227
+ }
228
+
229
+ function readSessionId(response) {
230
+ return response.headers.get('Mcp-Session-Id') ?? response.headers.get('mcp-session-id') ?? undefined;
231
+ }
232
+
233
+ async function safeText(response) {
234
+ try {
235
+ return await response.text();
236
+ } catch {
237
+ return null;
238
+ }
239
+ }
240
+
241
+ function truncate(text, limit = 1000) {
242
+ return text.length > limit ? `${text.slice(0, limit)}…` : text;
243
+ }
244
+
245
+ async function readJsonMessage(response) {
246
+ const text = await safeText(response);
247
+
248
+ if (!text) {
249
+ return [];
250
+ }
251
+
252
+ try {
253
+ return [JSON.parse(text)];
254
+ } catch {
255
+ return [];
256
+ }
257
+ }
258
+
259
+ async function readSseMessages(response) {
260
+ const reader = response.body.getReader();
261
+ const decoder = new TextDecoder();
262
+ const messages = [];
263
+ let buffer = '';
264
+ let dataLines = [];
265
+
266
+ const flush = () => {
267
+ if (dataLines.length === 0) {
268
+ return;
269
+ }
270
+
271
+ const data = dataLines.join('\n');
272
+ dataLines = [];
273
+
274
+ try {
275
+ messages.push(JSON.parse(data));
276
+ } catch {
277
+ // Skip non-JSON SSE payloads (keep-alive comments, partial events).
278
+ }
279
+ };
280
+
281
+ while (true) {
282
+ const { done, value } = await reader.read();
283
+
284
+ if (done) {
285
+ break;
286
+ }
287
+
288
+ buffer += decoder.decode(value, { stream: true });
289
+
290
+ const lines = buffer.split(/\r?\n/);
291
+ buffer = lines.pop() ?? '';
292
+
293
+ for (const rawLine of lines) {
294
+ const line = rawLine.trim();
295
+
296
+ if (line === '') {
297
+ flush();
298
+ continue;
299
+ }
300
+
301
+ if (line.startsWith(':')) {
302
+ continue;
303
+ }
304
+
305
+ if (line.startsWith('data:')) {
306
+ dataLines.push(line.slice(5).trimStart());
307
+ }
308
+ }
309
+ }
310
+
311
+ if (buffer.trim() !== '') {
312
+ const line = buffer.trim();
313
+
314
+ if (line.startsWith('data:')) {
315
+ dataLines.push(line.slice(5).trimStart());
316
+ }
317
+ }
318
+
319
+ flush();
320
+
321
+ return messages;
322
+ }
323
+
324
+ /**
325
+ * Forward one JSON-RPC message to the upstream MCP endpoint. Returns the
326
+ * JSON-RPC message(s) to re-emit on stdout (empty for notifications/202/204)
327
+ * and the captured Mcp-Session-Id. Throws UnauthorizedError on 401 so the
328
+ * caller can invalidate + re-fetch the token once.
329
+ */
330
+ export async function postJsonRpc({ url, token, orgId, sessionId, protocolVersion, message }) {
331
+ const headers = {
332
+ 'Content-Type': 'application/json',
333
+ Accept: 'application/json, text/event-stream',
334
+ Authorization: `Bearer ${token}`,
335
+ 'X-Cloud-Org-ID': orgId,
336
+ };
337
+
338
+ if (sessionId) {
339
+ headers['Mcp-Session-Id'] = sessionId;
340
+ }
341
+
342
+ // MCP streamable-HTTP requires the protocol version header on initialize.
343
+ if (protocolVersion) {
344
+ headers['MCP-Protocol-Version'] = protocolVersion;
345
+ }
346
+
347
+ let response;
348
+
349
+ try {
350
+ response = await fetch(url, {
351
+ method: 'POST',
352
+ headers,
353
+ body: JSON.stringify(message),
354
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
355
+ });
356
+ } catch (error) {
357
+ const reason = error instanceof Error ? error.message : String(error);
358
+ throw new UpstreamError(`POST ${url} failed: ${redactToken(reason, token)}`);
359
+ }
360
+
361
+ if (response.status === 401) {
362
+ throw new UnauthorizedError('HTTP 401');
363
+ }
364
+
365
+ if (response.status === 202 || response.status === 204) {
366
+ return { sessionId: readSessionId(response), messages: [] };
367
+ }
368
+
369
+ if (!response.ok) {
370
+ const detail = await safeText(response);
371
+ throw new UpstreamError(
372
+ `POST ${url} → HTTP ${response.status}: ${truncate(redactToken(detail ?? '', token))}`,
373
+ );
374
+ }
375
+
376
+ const nextSessionId = readSessionId(response);
377
+ const contentType = response.headers.get('content-type') ?? '';
378
+
379
+ if (contentType.includes('text/event-stream')) {
380
+ return { sessionId: nextSessionId, messages: await readSseMessages(response) };
381
+ }
382
+
383
+ return { sessionId: nextSessionId, messages: await readJsonMessage(response) };
384
+ }