@phyzess/kitto 0.2.1 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/README.md +36 -4
- package/bin/kitto.mjs +176 -2
- package/integration/dsh-archive-review.mjs +55 -0
- package/integration/dsh.mjs +3 -1
- package/integration/plugin.json +1 -1
- package/integration/scoped-dsh/native.mjs +33 -1
- package/integration/skills/kitto/SKILL.md +5 -4
- package/lib/codegraph.mjs +135 -0
- package/lib/codex-mcp.mjs +738 -0
- package/lib/dsh-profile.mjs +111 -0
- package/lib/environment-setup.mjs +19 -3
- package/lib/host-config.mjs +29 -4
- package/lib/hosts.mjs +288 -0
- package/lib/kitto.mjs +475 -59
- package/lib/mcp-credentials.mjs +289 -0
- package/lib/mcp-sync.mjs +500 -0
- package/lib/parity.mjs +64 -0
- package/lib/pi_config.py +218 -9
- package/lib/scope-dsh.mjs +10 -31
- package/lib/scope-setup.mjs +35 -13
- package/lib/scopes.mjs +45 -10
- package/lib/setup-wizard.mjs +38 -13
- package/lib/versions.mjs +8 -2
- package/lib/worktree-audit.mjs +189 -0
- package/lib/worktree-lifecycle.mjs +451 -0
- package/package.json +3 -3
- package/sync.sh +94 -25
|
@@ -0,0 +1,738 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { existsSync } from 'node:fs';
|
|
4
|
+
import { copyFile, mkdir, mkdtemp, readFile, rm } from 'node:fs/promises';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import {
|
|
8
|
+
bearerCredentialReference, literalSecretsIn, transportCredentialProblem, unresolvedPlaceholdersIn,
|
|
9
|
+
} from './mcp-credentials.mjs';
|
|
10
|
+
|
|
11
|
+
// Pi MCP definitions are the source of truth. Local and private overlays are
|
|
12
|
+
// machine-specific and are read only when the caller opts in; credential
|
|
13
|
+
// values never travel to Codex, only the name of an environment variable that
|
|
14
|
+
// `codex mcp add --bearer-token-env-var` resolves at connection time.
|
|
15
|
+
const platformDirectories = { darwin: 'macos', linux: 'linux' };
|
|
16
|
+
// The names `codex mcp add` accepts (letters, numbers, '-', '_', ':', '@', '/',
|
|
17
|
+
// '.'). Anything else is reported instead of being passed through.
|
|
18
|
+
const acceptedName = /^[A-Za-z0-9_:@/.-]+$/;
|
|
19
|
+
|
|
20
|
+
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
21
|
+
const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
|
|
22
|
+
const empty = value => value === undefined || value === null
|
|
23
|
+
|| (isObject(value) && Object.keys(value).length === 0)
|
|
24
|
+
|| (Array.isArray(value) && value.length === 0);
|
|
25
|
+
|
|
26
|
+
function deepMerge(base, over) {
|
|
27
|
+
if (!isObject(base) || !isObject(over)) return over;
|
|
28
|
+
const merged = { ...base };
|
|
29
|
+
for (const [key, value] of Object.entries(over)) {
|
|
30
|
+
merged[key] = hasOwn(merged, key) ? deepMerge(merged[key], value) : value;
|
|
31
|
+
}
|
|
32
|
+
return merged;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function canonicalJson(value) {
|
|
36
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
|
|
37
|
+
if (isObject(value)) {
|
|
38
|
+
return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(',')}}`;
|
|
39
|
+
}
|
|
40
|
+
return JSON.stringify(value);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function hasTemplate(value) {
|
|
44
|
+
if (typeof value === 'string') return value.includes('${');
|
|
45
|
+
if (Array.isArray(value)) return value.some(hasTemplate);
|
|
46
|
+
if (isObject(value)) return Object.values(value).some(hasTemplate);
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A stable fingerprint for the transport Kitto is allowed to own. */
|
|
51
|
+
export function transportHash(transport) {
|
|
52
|
+
return createHash('sha256').update(canonicalJson(transport)).digest('hex');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Map one Pi MCP entry to the subset `codex mcp add` can represent.
|
|
57
|
+
*
|
|
58
|
+
* The only credential form Codex can store without a literal is an HTTP
|
|
59
|
+
* `Authorization: Bearer ${VAR}` header, which becomes
|
|
60
|
+
* `--bearer-token-env-var VAR`. Every other env/header form is skipped whole:
|
|
61
|
+
* `codex mcp add --env` would write the value itself.
|
|
62
|
+
*/
|
|
63
|
+
export function sourceTransport(entry) {
|
|
64
|
+
if (!isObject(entry)) return { skip: 'server definition is not an object' };
|
|
65
|
+
const [secret] = literalSecretsIn(entry);
|
|
66
|
+
if (secret) return { skip: `contains a literal secret (${secret.label}) at ${secret.path}` };
|
|
67
|
+
const [placeholder] = unresolvedPlaceholdersIn(entry);
|
|
68
|
+
if (placeholder) return { skip: `still contains an unresolved YOUR_* placeholder at ${placeholder.path}` };
|
|
69
|
+
const transportProblem = transportCredentialProblem(entry);
|
|
70
|
+
if (transportProblem) return { skip: `${transportProblem}; only reference credentials are synced` };
|
|
71
|
+
// Pi fields that change auth, tool exposure or timing cannot be represented by
|
|
72
|
+
// `codex mcp add`; skipping is safer than silently dropping them.
|
|
73
|
+
for (const field of ['oauth', 'scopes', 'tools', 'toolFilter', 'enabledTools', 'disabledTools',
|
|
74
|
+
'enabled_tools', 'disabled_tools', 'startup_timeout_sec', 'tool_timeout_sec', 'timeout']) {
|
|
75
|
+
if (!empty(entry[field])) return { skip: `${field} is not synced in v1` };
|
|
76
|
+
}
|
|
77
|
+
const command = entry.command, url = entry.url;
|
|
78
|
+
const hasCommand = typeof command === 'string' && command !== '';
|
|
79
|
+
const hasUrl = typeof url === 'string' && url !== '';
|
|
80
|
+
if (hasCommand && hasUrl) return { skip: 'defines both command and url' };
|
|
81
|
+
if (hasUrl) {
|
|
82
|
+
if (!empty(entry.env_http_headers)) return { skip: 'env_http_headers are not synced in v1' };
|
|
83
|
+
if (!empty(entry.bearer_token_env_var) || !empty(entry.http_headers_helper)) {
|
|
84
|
+
return { skip: 'header credentials are not synced in v1' };
|
|
85
|
+
}
|
|
86
|
+
if (!empty(entry.env)) return { skip: 'env is not synced in v1' };
|
|
87
|
+
if (hasTemplate(url)) return { skip: 'url contains a credential template' };
|
|
88
|
+
let bearerTokenEnvVar;
|
|
89
|
+
if (!empty(entry.headers)) {
|
|
90
|
+
if (!isObject(entry.headers)) return { skip: 'headers is not an object of strings' };
|
|
91
|
+
const names = Object.keys(entry.headers);
|
|
92
|
+
const [header] = names;
|
|
93
|
+
const value = header === undefined ? undefined : entry.headers[header];
|
|
94
|
+
const reference = names.length === 1 && header.toLowerCase() === 'authorization'
|
|
95
|
+
? bearerCredentialReference(value) : null;
|
|
96
|
+
if (!reference) {
|
|
97
|
+
return { skip: 'headers are not synced in v1: only Authorization: Bearer ${VAR} is supported' };
|
|
98
|
+
}
|
|
99
|
+
bearerTokenEnvVar = reference;
|
|
100
|
+
}
|
|
101
|
+
return { transport: { type: 'http', url, ...(bearerTokenEnvVar ? { bearerTokenEnvVar } : {}) } };
|
|
102
|
+
}
|
|
103
|
+
if (!hasCommand) return { skip: 'has neither a command nor a url' };
|
|
104
|
+
if (command.includes('${')) return { skip: 'command contains a credential template' };
|
|
105
|
+
const args = entry.args ?? [];
|
|
106
|
+
if (!Array.isArray(args) || args.some(value => typeof value !== 'string')) {
|
|
107
|
+
return { skip: 'args is not an array of strings' };
|
|
108
|
+
}
|
|
109
|
+
if (hasTemplate(args)) return { skip: 'args contain a credential template' };
|
|
110
|
+
if (!empty(entry.headers)) return { skip: 'headers are not synced in v1 for stdio servers' };
|
|
111
|
+
if (!empty(entry.env)) return { skip: 'env is not synced in v1: codex mcp add --env would store a literal' };
|
|
112
|
+
if (!empty(entry.env_vars)) return { skip: 'env_vars are not synced in v1' };
|
|
113
|
+
if (!empty(entry.bearer_token_env_var)) return { skip: 'bearer_token_env_var is not synced in v1' };
|
|
114
|
+
if (!empty(entry.cwd)) return { skip: 'cwd is not supported by codex mcp add' };
|
|
115
|
+
return { transport: { type: 'stdio', command, args } };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function optionalJson(path) {
|
|
119
|
+
let text;
|
|
120
|
+
try {
|
|
121
|
+
text = await readFile(path, 'utf8');
|
|
122
|
+
} catch (error) {
|
|
123
|
+
if (error.code === 'ENOENT') return null;
|
|
124
|
+
throw new Error(`Cannot read ${path}: ${error.message}`);
|
|
125
|
+
}
|
|
126
|
+
try {
|
|
127
|
+
return JSON.parse(text);
|
|
128
|
+
} catch (error) {
|
|
129
|
+
throw new Error(`Invalid JSON in ${path}: ${error.message}`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Enabled servers from the repository and platform Pi MCP files, plus the
|
|
135
|
+
* machine-local and private files when `includePrivate` opts in (in the same
|
|
136
|
+
* base < platform < local < private order Pi's own merge uses).
|
|
137
|
+
*/
|
|
138
|
+
export async function sourceServers(source, platform = process.platform, { includePrivate = false } = {}) {
|
|
139
|
+
const basePath = join(source, 'config/pi/mcp.json');
|
|
140
|
+
const base = await optionalJson(basePath);
|
|
141
|
+
if (base === null) {
|
|
142
|
+
throw new Error(`Codex MCP sync needs ${basePath}, but the Pi MCP source is missing.`);
|
|
143
|
+
}
|
|
144
|
+
const platformName = platformDirectories[platform];
|
|
145
|
+
const sources = [[basePath, base]];
|
|
146
|
+
if (platformName) {
|
|
147
|
+
const overlayPath = join(source, `config/pi/platform/${platformName}/mcp.json`);
|
|
148
|
+
sources.push([overlayPath, await optionalJson(overlayPath)]);
|
|
149
|
+
}
|
|
150
|
+
if (includePrivate) {
|
|
151
|
+
for (const path of [join(source, 'config/pi/local/mcp.json'), join(source, 'config/pi/mcp.private.json')]) {
|
|
152
|
+
sources.push([path, await optionalJson(path)]);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
const merged = new Map();
|
|
156
|
+
for (const [label, config] of sources) {
|
|
157
|
+
if (config == null) continue;
|
|
158
|
+
if (!isObject(config) || (config.mcpServers !== undefined && !isObject(config.mcpServers))) {
|
|
159
|
+
throw new Error(`Invalid MCP configuration in ${label}: mcpServers must be an object.`);
|
|
160
|
+
}
|
|
161
|
+
for (const [name, entry] of Object.entries(config.mcpServers ?? {})) {
|
|
162
|
+
if (name.startsWith('_') || !isObject(entry)) continue;
|
|
163
|
+
merged.set(name, deepMerge(merged.get(name) ?? {}, entry));
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
const servers = [];
|
|
167
|
+
for (const [name, entry] of merged) {
|
|
168
|
+
if (entry.enabled === false) continue;
|
|
169
|
+
if (!acceptedName.test(name)) {
|
|
170
|
+
servers.push({ name, skip: 'name contains characters codex mcp add rejects' });
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
const mapped = sourceTransport(entry);
|
|
174
|
+
if (mapped.skip) servers.push({ name, skip: mapped.skip });
|
|
175
|
+
else servers.push({ name, transport: mapped.transport, hash: transportHash(mapped.transport) });
|
|
176
|
+
}
|
|
177
|
+
return servers;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Normalize the transport fields returned by `codex mcp list/get --json`. */
|
|
181
|
+
export function liveTransport(entry) {
|
|
182
|
+
const transport = isObject(entry) ? entry.transport : null;
|
|
183
|
+
if (!isObject(transport)) return null;
|
|
184
|
+
if (transport.type === 'stdio' && typeof transport.command === 'string' && transport.command !== '') {
|
|
185
|
+
const args = transport.args ?? [];
|
|
186
|
+
if (!Array.isArray(args) || args.some(value => typeof value !== 'string')) return null;
|
|
187
|
+
return { type: 'stdio', command: transport.command, args };
|
|
188
|
+
}
|
|
189
|
+
if ((transport.type === 'streamable_http' || transport.type === 'http')
|
|
190
|
+
&& typeof transport.url === 'string' && transport.url !== '') {
|
|
191
|
+
const bearer = transport.bearer_token_env_var;
|
|
192
|
+
return {
|
|
193
|
+
type: 'http',
|
|
194
|
+
url: transport.url,
|
|
195
|
+
...(typeof bearer === 'string' && bearer !== '' ? { bearerTokenEnvVar: bearer } : {}),
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Settings that `codex mcp add` would silently drop. If any are present, the
|
|
203
|
+
* live server has been adjusted outside Kitto and must be preserved.
|
|
204
|
+
*/
|
|
205
|
+
export function liveExtras(entry) {
|
|
206
|
+
if (!isObject(entry)) return ['unknown definition'];
|
|
207
|
+
const extras = [];
|
|
208
|
+
if (entry.enabled === false) extras.push('enabled=false');
|
|
209
|
+
if (!empty(entry.enabled_tools)) extras.push('enabled_tools');
|
|
210
|
+
if (!empty(entry.disabled_tools)) extras.push('disabled_tools');
|
|
211
|
+
if (!empty(entry.startup_timeout_sec)) extras.push('startup_timeout_sec');
|
|
212
|
+
if (!empty(entry.tool_timeout_sec)) extras.push('tool_timeout_sec');
|
|
213
|
+
const transport = entry.transport;
|
|
214
|
+
if (!isObject(transport)) return extras;
|
|
215
|
+
if (transport.type === 'stdio') {
|
|
216
|
+
if (!empty(transport.env)) extras.push('env');
|
|
217
|
+
if (!empty(transport.env_vars)) extras.push('env_vars');
|
|
218
|
+
if (!empty(transport.cwd)) extras.push('cwd');
|
|
219
|
+
} else {
|
|
220
|
+
if (!empty(transport.http_headers)) extras.push('http_headers');
|
|
221
|
+
if (!empty(transport.env_http_headers)) extras.push('env_http_headers');
|
|
222
|
+
if (!empty(transport.http_headers_helper)) extras.push('http_headers_helper');
|
|
223
|
+
}
|
|
224
|
+
return extras;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export function formatOperation(operation) {
|
|
228
|
+
const reason = operation.reason ? `: ${operation.reason}` : '';
|
|
229
|
+
switch (operation.action) {
|
|
230
|
+
case 'add': return `mcp add: ${operation.name} (codex)`;
|
|
231
|
+
case 'update': return `mcp update: ${operation.name} (codex)`;
|
|
232
|
+
case 'same': return `mcp same: ${operation.name} (codex)`;
|
|
233
|
+
case 'skip': return `mcp skip: ${operation.name} (codex)${reason}`;
|
|
234
|
+
case 'conflict': return `mcp conflict: ${operation.name} (codex)${reason}; preserved`;
|
|
235
|
+
case 'remove': return `mcp remove: ${operation.name} (codex)`;
|
|
236
|
+
case 'adopt': return `mcp adopt: ${operation.name} (codex)`;
|
|
237
|
+
case 'forget': return `mcp forget: ${operation.name} (codex)`;
|
|
238
|
+
case 'forgetPending': return `mcp forget pending: ${operation.name} (codex)`;
|
|
239
|
+
default: return `mcp ${operation.action}: ${operation.name} (codex)`;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Pure plan for the source servers against the live Codex inventory.
|
|
245
|
+
* `details` holds `codex mcp get --json` results for servers Kitto owns.
|
|
246
|
+
*/
|
|
247
|
+
export function buildMcpPlan({
|
|
248
|
+
servers = [], owned = {}, pending = {}, live = [], details = new Map(), liveVerified = false,
|
|
249
|
+
}) {
|
|
250
|
+
const sources = new Map(servers.map(server => [server.name, server]));
|
|
251
|
+
const current = new Map(live.map(entry => [entry.name, entry]));
|
|
252
|
+
const operations = [];
|
|
253
|
+
const added = new Set();
|
|
254
|
+
for (const server of servers) {
|
|
255
|
+
if (server.skip) {
|
|
256
|
+
operations.push({ name: server.name, action: 'skip', reason: server.skip });
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
const liveEntry = current.get(server.name);
|
|
260
|
+
if (!liveEntry) {
|
|
261
|
+
operations.push({ name: server.name, action: 'add', transport: server.transport, hash: server.hash });
|
|
262
|
+
added.add(server.name);
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
const detail = details.get(server.name) ?? liveEntry;
|
|
266
|
+
const transport = liveTransport(detail);
|
|
267
|
+
const liveHash = transport ? transportHash(transport) : null;
|
|
268
|
+
const extras = liveExtras(detail);
|
|
269
|
+
if (transport && extras.length === 0 && hasOwn(pending, server.name) && pending[server.name] === liveHash) {
|
|
270
|
+
operations.push({ name: server.name, action: 'adopt', hash: liveHash,
|
|
271
|
+
reason: hasOwn(owned, server.name) ? 'finish an interrupted update' : 'finish an interrupted add' });
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
if (!hasOwn(owned, server.name)) {
|
|
275
|
+
operations.push({ name: server.name, action: 'conflict',
|
|
276
|
+
reason: 'same-name MCP server is not owned by Kitto' });
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
if (!transport) {
|
|
280
|
+
operations.push({ name: server.name, action: 'conflict', reason: 'unrecognized live transport' });
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
if (liveHash !== owned[server.name]) {
|
|
284
|
+
operations.push({ name: server.name, action: 'conflict',
|
|
285
|
+
reason: 'live server differs from the recorded ownership fingerprint' });
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
if (extras.length) {
|
|
289
|
+
operations.push({ name: server.name, action: 'conflict',
|
|
290
|
+
reason: `live server has additional settings (${extras.join(', ')})` });
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
if (liveHash === server.hash) {
|
|
294
|
+
operations.push({ name: server.name, action: 'same' });
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
operations.push({ name: server.name, action: 'update', transport: server.transport, hash: server.hash });
|
|
298
|
+
}
|
|
299
|
+
// Removed source servers: delete live copies only when they still match a
|
|
300
|
+
// fingerprint Kitto recorded.
|
|
301
|
+
for (const name of Object.keys(owned)) {
|
|
302
|
+
if (sources.has(name)) continue;
|
|
303
|
+
const liveEntry = current.get(name);
|
|
304
|
+
if (!liveEntry) continue;
|
|
305
|
+
const detail = details.get(name) ?? liveEntry;
|
|
306
|
+
const transport = liveTransport(detail);
|
|
307
|
+
if (!transport) {
|
|
308
|
+
operations.push({ name, action: 'conflict', reason: 'unrecognized live transport' });
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
const fingerprints = [owned[name], pending[name]].filter(value => value);
|
|
312
|
+
if (!fingerprints.includes(transportHash(transport))) {
|
|
313
|
+
operations.push({ name, action: 'conflict',
|
|
314
|
+
reason: 'source removed the server, but the live server changed outside Kitto' });
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
const extras = liveExtras(detail);
|
|
318
|
+
if (extras.length) {
|
|
319
|
+
operations.push({ name, action: 'conflict',
|
|
320
|
+
reason: `source removed the server, but the live server has additional settings (${extras.join(', ')})` });
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
operations.push({ name, action: 'remove', hash: transportHash(transport) });
|
|
324
|
+
}
|
|
325
|
+
// A verified empty result means the owned server was removed outside Kitto.
|
|
326
|
+
// Drop the stale fingerprint so a later same-name server is not misjudged.
|
|
327
|
+
for (const name of Object.keys(owned)) {
|
|
328
|
+
if (current.has(name) || added.has(name) || !liveVerified) continue;
|
|
329
|
+
operations.push({ name, action: 'forget', reason: 'recorded server is missing from live Codex' });
|
|
330
|
+
}
|
|
331
|
+
// Pending-only records (an add that was written but never promoted) still need
|
|
332
|
+
// reconciliation, especially after the source entry disappears.
|
|
333
|
+
for (const name of Object.keys(pending)) {
|
|
334
|
+
if (hasOwn(owned, name)) continue;
|
|
335
|
+
const source = sources.get(name);
|
|
336
|
+
if (source && !source.skip) continue; // the source loop handles add/adopt/conflict
|
|
337
|
+
const liveEntry = current.get(name);
|
|
338
|
+
if (!liveEntry) {
|
|
339
|
+
if (liveVerified) {
|
|
340
|
+
operations.push({ name, action: 'forgetPending', reason: 'pending server is missing from live Codex' });
|
|
341
|
+
}
|
|
342
|
+
continue;
|
|
343
|
+
}
|
|
344
|
+
const detail = details.get(name) ?? liveEntry;
|
|
345
|
+
const transport = liveTransport(detail);
|
|
346
|
+
const liveHash = transport ? transportHash(transport) : null;
|
|
347
|
+
const matches = transport && liveExtras(detail).length === 0 && pending[name] === liveHash;
|
|
348
|
+
if (!matches) {
|
|
349
|
+
if (liveVerified) {
|
|
350
|
+
operations.push({ name, action: 'forgetPending', reason: 'pending server was changed outside Kitto' });
|
|
351
|
+
}
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
if (!source) {
|
|
355
|
+
operations.push({ name, action: 'remove', hash: liveHash, reason: 'source removed an interrupted add' });
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
operations.push({ name, action: 'adopt', hash: liveHash, reason: 'finish an interrupted add' });
|
|
359
|
+
}
|
|
360
|
+
return operations;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** Preview/removal plan for detaching Kitto from Codex. */
|
|
364
|
+
export function buildRemovalPlan({ owned = {}, pending = {}, live = [], details = new Map() }) {
|
|
365
|
+
const current = new Map(live.map(entry => [entry.name, entry]));
|
|
366
|
+
const operations = [];
|
|
367
|
+
const stale = [];
|
|
368
|
+
const stalePending = [];
|
|
369
|
+
for (const name of new Set([...Object.keys(owned), ...Object.keys(pending)])) {
|
|
370
|
+
const liveEntry = current.get(name);
|
|
371
|
+
if (!liveEntry) {
|
|
372
|
+
if (hasOwn(owned, name)) stale.push(name);
|
|
373
|
+
if (hasOwn(pending, name)) stalePending.push(name);
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
const detail = details.get(name) ?? liveEntry;
|
|
377
|
+
const transport = liveTransport(detail);
|
|
378
|
+
if (!transport) {
|
|
379
|
+
operations.push({ name, action: 'conflict', reason: 'unrecognized live transport' });
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
const liveHash = transportHash(transport);
|
|
383
|
+
const fingerprints = [owned[name], pending[name]].filter(value => value);
|
|
384
|
+
if (!fingerprints.includes(liveHash)) {
|
|
385
|
+
operations.push({ name, action: 'conflict',
|
|
386
|
+
reason: 'live server differs from the recorded ownership fingerprint' });
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
389
|
+
const extras = liveExtras(detail);
|
|
390
|
+
if (extras.length) {
|
|
391
|
+
operations.push({ name, action: 'conflict',
|
|
392
|
+
reason: `live server has additional settings (${extras.join(', ')})` });
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
operations.push({ name, action: 'remove', hash: liveHash });
|
|
396
|
+
}
|
|
397
|
+
return { operations, stale, stalePending };
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** Run `codex` and return stdout; spawn failures and non-zero exits throw. */
|
|
401
|
+
export function defaultCodexRun(args, { env = process.env, timeout = 30_000, cwd } = {}) {
|
|
402
|
+
const result = spawnSync('codex', args, { encoding: 'utf8', env, timeout, cwd });
|
|
403
|
+
if (result.error || result.status !== 0) {
|
|
404
|
+
const detail = result.error?.message || result.stderr?.trim() || `exit ${result.status}`;
|
|
405
|
+
// Never echo argv: a caller that bypassed the source checks could have put a
|
|
406
|
+
// credential in a URL or argument, and this error is printed on failure.
|
|
407
|
+
throw new Error(`codex ${args.slice(0, 2).join(' ')} failed: ${detail}`);
|
|
408
|
+
}
|
|
409
|
+
return result.stdout.trim();
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function parseResponse(text, label) {
|
|
413
|
+
try {
|
|
414
|
+
return JSON.parse(text);
|
|
415
|
+
} catch (error) {
|
|
416
|
+
throw new Error(`${label} returned invalid JSON: ${error.message}`);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
export function listCodexMcp({ run = defaultCodexRun, env = process.env, home } = {}) {
|
|
421
|
+
// Invoking `codex` also creates helper files under CODEX_HOME; a missing home
|
|
422
|
+
// means there is no Codex configuration to reconcile yet.
|
|
423
|
+
const target = home ?? env?.CODEX_HOME;
|
|
424
|
+
if (target && !existsSync(target)) return [];
|
|
425
|
+
const parsed = parseResponse(run(['mcp', 'list', '--json'], { env }), 'codex mcp list --json');
|
|
426
|
+
if (!Array.isArray(parsed)) throw new Error('codex mcp list --json did not return an array.');
|
|
427
|
+
return parsed;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export function getCodexMcp(name, { run = defaultCodexRun, env = process.env } = {}) {
|
|
431
|
+
const parsed = parseResponse(run(['mcp', 'get', name, '--json'], { env }), `codex mcp get ${name} --json`);
|
|
432
|
+
if (!isObject(parsed)) throw new Error(`codex mcp get ${name} --json did not return an object.`);
|
|
433
|
+
return parsed;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
function codexEnvironment(state) {
|
|
437
|
+
return { ...process.env, CODEX_HOME: state.codexHome };
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function liveDetails({ owned, pending = {}, live, run, env }) {
|
|
441
|
+
const tracked = new Set([...Object.keys(owned), ...Object.keys(pending)]);
|
|
442
|
+
const details = new Map();
|
|
443
|
+
for (const entry of live) {
|
|
444
|
+
if (tracked.has(entry?.name)) details.set(entry.name, getCodexMcp(entry.name, { run, env }));
|
|
445
|
+
}
|
|
446
|
+
return details;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function liveVerifiedFor(home, env) {
|
|
450
|
+
const target = home ?? env?.CODEX_HOME;
|
|
451
|
+
return target ? existsSync(target) : false;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* Read the live inventory. Read-only calls copy config.toml into a scratch
|
|
456
|
+
* CODEX_HOME because every Codex invocation creates helper files under it.
|
|
457
|
+
*/
|
|
458
|
+
async function withLive({ run, env, home, list, readOnly }, callback) {
|
|
459
|
+
if (list) return callback({ live: await list(), env, verified: true, home });
|
|
460
|
+
if (readOnly && home && existsSync(home)) {
|
|
461
|
+
const scratch = await mkdtemp(join(tmpdir(), 'kitto-codex-mcp-'));
|
|
462
|
+
try {
|
|
463
|
+
const config = join(home, 'config.toml');
|
|
464
|
+
if (existsSync(config)) await copyFile(config, join(scratch, 'config.toml'));
|
|
465
|
+
const probeEnv = { ...env, CODEX_HOME: scratch };
|
|
466
|
+
const live = listCodexMcp({ run, env: probeEnv, home: scratch });
|
|
467
|
+
return await callback({ live, env: probeEnv, verified: true, home: scratch });
|
|
468
|
+
} finally {
|
|
469
|
+
await rm(scratch, { recursive: true, force: true });
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
const live = listCodexMcp({ run, env, home });
|
|
473
|
+
return callback({ live, env, verified: liveVerifiedFor(home, env), home });
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
async function collectPlan(state, { run, env, home, platform, readSource, list, readOnly = false }) {
|
|
477
|
+
const owned = state.mcp?.codex ?? {};
|
|
478
|
+
const pending = state.mcp?.codexPending ?? {};
|
|
479
|
+
const servers = await readSource(state.source, platform, { includePrivate: state.includePrivate === true });
|
|
480
|
+
return withLive({ run, env, home, list, readOnly }, ({ live, env: liveEnv, verified }) => ({
|
|
481
|
+
servers, owned, pending, live, liveVerified: verified,
|
|
482
|
+
details: liveDetails({ owned, pending, live, run, env: liveEnv }),
|
|
483
|
+
}));
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
function addArguments(name, transport) {
|
|
487
|
+
if (transport.type === 'stdio') return ['mcp', 'add', name, '--', transport.command, ...transport.args];
|
|
488
|
+
return ['mcp', 'add', name, '--url', transport.url,
|
|
489
|
+
...(transport.bearerTokenEnvVar ? ['--bearer-token-env-var', transport.bearerTokenEnvVar] : [])];
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** Print the MCP part of the deployment plan without writing anything. */
|
|
493
|
+
export async function planCodexMcp(state, {
|
|
494
|
+
run = defaultCodexRun, env = codexEnvironment(state), home = state.codexHome,
|
|
495
|
+
platform = process.platform, log = console.log, readSource = sourceServers, list, readOnly = true,
|
|
496
|
+
} = {}) {
|
|
497
|
+
const context = await collectPlan(state, { run, env, home, platform, readSource, list, readOnly });
|
|
498
|
+
const operations = buildMcpPlan(context);
|
|
499
|
+
for (const operation of operations) log(formatOperation(operation));
|
|
500
|
+
return operations;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function verifyLive(name, recorded, run, env) {
|
|
504
|
+
const live = listCodexMcp({ run, env });
|
|
505
|
+
const entry = live.find(item => item.name === name);
|
|
506
|
+
if (!entry) return { entry: null, problem: 'live server disappeared' };
|
|
507
|
+
const detail = getCodexMcp(name, { run, env });
|
|
508
|
+
const transport = liveTransport(detail);
|
|
509
|
+
if (!transport || transportHash(transport) !== recorded) {
|
|
510
|
+
return { entry, problem: 'live server differs from the recorded ownership fingerprint' };
|
|
511
|
+
}
|
|
512
|
+
const extras = liveExtras(detail);
|
|
513
|
+
if (extras.length) return { entry, problem: `live server has additional settings (${extras.join(', ')})` };
|
|
514
|
+
return { entry, transport };
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** Persist provisional ownership before touching live Codex. */
|
|
518
|
+
async function savePending(state, name, hash, save) {
|
|
519
|
+
state.mcp ||= {};
|
|
520
|
+
state.mcp.codex ||= {};
|
|
521
|
+
state.mcp.codexPending ||= {};
|
|
522
|
+
state.mcp.codexPending[name] = hash;
|
|
523
|
+
await save();
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
async function promotePending(state, name, hash) {
|
|
527
|
+
state.mcp.codex[name] = hash;
|
|
528
|
+
if (!state.mcp.codexPending) return;
|
|
529
|
+
delete state.mcp.codexPending[name];
|
|
530
|
+
if (!Object.keys(state.mcp.codexPending).length) delete state.mcp.codexPending;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function forgetPending(state, name) {
|
|
534
|
+
if (!state.mcp?.codexPending) return false;
|
|
535
|
+
if (!hasOwn(state.mcp.codexPending, name)) return false;
|
|
536
|
+
delete state.mcp.codexPending[name];
|
|
537
|
+
if (!Object.keys(state.mcp.codexPending).length) delete state.mcp.codexPending;
|
|
538
|
+
return true;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Apply the plan. Ownership is recorded as pending before the native write and
|
|
543
|
+
* promoted only after `codex mcp list` confirms it. Each step is flushed via
|
|
544
|
+
* `save`, so an interrupted run is retried by adopting the pending record.
|
|
545
|
+
*/
|
|
546
|
+
export async function applyCodexMcp(state, {
|
|
547
|
+
run = defaultCodexRun, env = codexEnvironment(state), home = state.codexHome,
|
|
548
|
+
platform = process.platform, save = async () => {}, log = () => {},
|
|
549
|
+
warn = console.warn, readSource = sourceServers, list,
|
|
550
|
+
} = {}) {
|
|
551
|
+
const context = await collectPlan(state, { run, env, home, platform, readSource, list });
|
|
552
|
+
const operations = buildMcpPlan(context);
|
|
553
|
+
state.mcp ||= {};
|
|
554
|
+
state.mcp.codex ||= {};
|
|
555
|
+
for (const operation of operations) {
|
|
556
|
+
if (operation.action === 'skip') {
|
|
557
|
+
// A native sync run has no separate plan output, so surface why a server
|
|
558
|
+
// (for example one whose credentials Codex cannot express) was left out.
|
|
559
|
+
warn(formatOperation(operation));
|
|
560
|
+
continue;
|
|
561
|
+
}
|
|
562
|
+
if (operation.action === 'add' || operation.action === 'update') {
|
|
563
|
+
if (operation.action === 'add') {
|
|
564
|
+
const live = list ? await list() : listCodexMcp({ run, env, home });
|
|
565
|
+
if (live.some(item => item.name === operation.name)) {
|
|
566
|
+
warn(`mcp conflict: ${operation.name} (codex): live server appeared during sync; preserved`);
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
} else {
|
|
570
|
+
const check = verifyLive(operation.name, state.mcp.codex[operation.name], run, env);
|
|
571
|
+
if (check.problem) {
|
|
572
|
+
warn(`mcp conflict: ${operation.name} (codex): ${check.problem}; preserved`);
|
|
573
|
+
continue;
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
// Record the intended fingerprint first. If the process dies between the
|
|
577
|
+
// native write and the promotion below, the next run adopts the server.
|
|
578
|
+
await savePending(state, operation.name, operation.hash, save);
|
|
579
|
+
if (home) await mkdir(home, { recursive: true });
|
|
580
|
+
try {
|
|
581
|
+
run(addArguments(operation.name, operation.transport), { env });
|
|
582
|
+
} catch (error) {
|
|
583
|
+
// `--url` may write config.toml before OAuth discovery times out. Adopt
|
|
584
|
+
// only an exact transport match so a foreign user server is not claimed.
|
|
585
|
+
let detail = null;
|
|
586
|
+
try {
|
|
587
|
+
const live = list ? await list() : listCodexMcp({ run, env, home });
|
|
588
|
+
if (live.some(item => item.name === operation.name)) {
|
|
589
|
+
detail = getCodexMcp(operation.name, { run, env });
|
|
590
|
+
}
|
|
591
|
+
} catch { /* keep the original native error */ }
|
|
592
|
+
const transport = detail ? liveTransport(detail) : null;
|
|
593
|
+
if (!transport || transportHash(transport) !== operation.hash || liveExtras(detail).length) throw error;
|
|
594
|
+
warn(`mcp warning: ${operation.name} (codex): native ${operation.action} failed after writing the server (${error.message}); adopted. Run \`codex mcp login ${operation.name}\` if it needs authentication.`);
|
|
595
|
+
await promotePending(state, operation.name, operation.hash);
|
|
596
|
+
await save();
|
|
597
|
+
log(`mcp adopt: ${operation.name} (codex)`);
|
|
598
|
+
continue;
|
|
599
|
+
}
|
|
600
|
+
const live = list ? await list() : listCodexMcp({ run, env, home });
|
|
601
|
+
const entry = live.find(item => item.name === operation.name);
|
|
602
|
+
const transport = entry ? liveTransport(entry) : null;
|
|
603
|
+
if (!transport || transportHash(transport) !== operation.hash) {
|
|
604
|
+
throw new Error(`codex mcp add ${operation.name} did not persist the requested transport.`);
|
|
605
|
+
}
|
|
606
|
+
await promotePending(state, operation.name, operation.hash);
|
|
607
|
+
await save();
|
|
608
|
+
log(`mcp ${operation.action}: ${operation.name} (codex)`);
|
|
609
|
+
continue;
|
|
610
|
+
}
|
|
611
|
+
if (operation.action === 'adopt') {
|
|
612
|
+
await promotePending(state, operation.name, operation.hash);
|
|
613
|
+
await save();
|
|
614
|
+
log(`mcp adopt: ${operation.name} (codex)`);
|
|
615
|
+
continue;
|
|
616
|
+
}
|
|
617
|
+
if (operation.action === 'forget') {
|
|
618
|
+
delete state.mcp.codex[operation.name];
|
|
619
|
+
forgetPending(state, operation.name);
|
|
620
|
+
await save();
|
|
621
|
+
log(`mcp forget: ${operation.name} (codex)`);
|
|
622
|
+
continue;
|
|
623
|
+
}
|
|
624
|
+
if (operation.action === 'forgetPending') {
|
|
625
|
+
if (forgetPending(state, operation.name)) {
|
|
626
|
+
await save();
|
|
627
|
+
log(`mcp forget pending: ${operation.name} (codex)`);
|
|
628
|
+
}
|
|
629
|
+
continue;
|
|
630
|
+
}
|
|
631
|
+
if (operation.action === 'remove') {
|
|
632
|
+
const recorded = state.mcp.codex[operation.name] ?? state.mcp.codexPending?.[operation.name];
|
|
633
|
+
const check = verifyLive(operation.name, recorded, run, env);
|
|
634
|
+
if (check.problem) {
|
|
635
|
+
warn(`mcp conflict: ${operation.name} (codex): ${check.problem}; preserved`);
|
|
636
|
+
continue;
|
|
637
|
+
}
|
|
638
|
+
run(['mcp', 'remove', operation.name], { env });
|
|
639
|
+
const live = list ? await list() : listCodexMcp({ run, env, home });
|
|
640
|
+
if (live.some(item => item.name === operation.name)) {
|
|
641
|
+
throw new Error(`codex mcp remove ${operation.name} did not remove the server.`);
|
|
642
|
+
}
|
|
643
|
+
delete state.mcp.codex[operation.name];
|
|
644
|
+
forgetPending(state, operation.name);
|
|
645
|
+
await save();
|
|
646
|
+
log(`mcp remove: ${operation.name} (codex)`);
|
|
647
|
+
continue;
|
|
648
|
+
}
|
|
649
|
+
if (operation.action === 'conflict') {
|
|
650
|
+
warn(`mcp conflict: ${operation.name} (codex): ${operation.reason}; preserved`);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
// Clean up pending records that no longer describe a live server (for example
|
|
654
|
+
// after a failed add or an external edit).
|
|
655
|
+
if (state.mcp.codexPending && Object.keys(state.mcp.codexPending).length) {
|
|
656
|
+
let changed = false;
|
|
657
|
+
const live = list ? await list() : listCodexMcp({ run, env, home });
|
|
658
|
+
for (const [name, hash] of Object.entries(state.mcp.codexPending)) {
|
|
659
|
+
const entry = live.find(item => item.name === name);
|
|
660
|
+
let stale = !entry;
|
|
661
|
+
if (entry) {
|
|
662
|
+
try {
|
|
663
|
+
const detail = getCodexMcp(name, { run, env });
|
|
664
|
+
const transport = liveTransport(detail);
|
|
665
|
+
stale = !transport || transportHash(transport) !== hash || liveExtras(detail).length > 0;
|
|
666
|
+
} catch {
|
|
667
|
+
stale = true;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
if (stale) {
|
|
671
|
+
delete state.mcp.codexPending[name];
|
|
672
|
+
changed = true;
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
if (changed) await save();
|
|
676
|
+
if (!Object.keys(state.mcp.codexPending).length) {
|
|
677
|
+
delete state.mcp.codexPending;
|
|
678
|
+
await save();
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
return operations;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/** Preview or remove every Codex MCP server that Kitto still owns. */
|
|
685
|
+
export async function removeCodexMcp(state, {
|
|
686
|
+
apply = false, run = defaultCodexRun, env = codexEnvironment(state), home = state.codexHome,
|
|
687
|
+
save = async () => {}, log = console.log, warn = console.warn, list,
|
|
688
|
+
} = {}) {
|
|
689
|
+
const owned = state.mcp?.codex ?? {};
|
|
690
|
+
const pending = state.mcp?.codexPending ?? {};
|
|
691
|
+
if (!Object.keys(owned).length && !Object.keys(pending).length) {
|
|
692
|
+
return { operations: [], stale: [], stalePending: [] };
|
|
693
|
+
}
|
|
694
|
+
return withLive({ run, env, home, list, readOnly: !apply }, async ({ live, env: liveEnv }) => {
|
|
695
|
+
const details = liveDetails({ owned, pending, live, run, env: liveEnv });
|
|
696
|
+
const plan = buildRemovalPlan({ owned, pending, live, details });
|
|
697
|
+
if (!apply) {
|
|
698
|
+
for (const operation of plan.operations) log(formatOperation(operation));
|
|
699
|
+
return plan;
|
|
700
|
+
}
|
|
701
|
+
state.mcp ||= {};
|
|
702
|
+
state.mcp.codex ||= {};
|
|
703
|
+
state.mcp.codexPending ||= {};
|
|
704
|
+
for (const operation of plan.operations) {
|
|
705
|
+
if (operation.action === 'conflict') {
|
|
706
|
+
warn(`mcp conflict: ${operation.name} (codex): ${operation.reason}; preserved`);
|
|
707
|
+
continue;
|
|
708
|
+
}
|
|
709
|
+
if (operation.action !== 'remove') continue;
|
|
710
|
+
const recorded = state.mcp.codex[operation.name] ?? state.mcp.codexPending[operation.name];
|
|
711
|
+
const check = verifyLive(operation.name, recorded, run, liveEnv);
|
|
712
|
+
if (check.problem) {
|
|
713
|
+
warn(`mcp conflict: ${operation.name} (codex): ${check.problem}; preserved`);
|
|
714
|
+
continue;
|
|
715
|
+
}
|
|
716
|
+
run(['mcp', 'remove', operation.name], { env: liveEnv });
|
|
717
|
+
const liveAfter = list ? await list() : listCodexMcp({ run, env: liveEnv, home });
|
|
718
|
+
if (liveAfter.some(item => item.name === operation.name)) {
|
|
719
|
+
throw new Error(`codex mcp remove ${operation.name} did not remove the server.`);
|
|
720
|
+
}
|
|
721
|
+
delete state.mcp.codex[operation.name];
|
|
722
|
+
delete state.mcp.codexPending[operation.name];
|
|
723
|
+
await save();
|
|
724
|
+
log(`mcp remove: ${operation.name} (codex)`);
|
|
725
|
+
}
|
|
726
|
+
let changed = false;
|
|
727
|
+
for (const name of [...plan.stale, ...plan.stalePending]) {
|
|
728
|
+
if (hasOwn(state.mcp.codex, name)) { delete state.mcp.codex[name]; changed = true; }
|
|
729
|
+
if (hasOwn(state.mcp.codexPending, name)) { delete state.mcp.codexPending[name]; changed = true; }
|
|
730
|
+
}
|
|
731
|
+
if (changed) await save();
|
|
732
|
+
if (!Object.keys(state.mcp.codexPending).length) {
|
|
733
|
+
delete state.mcp.codexPending;
|
|
734
|
+
await save();
|
|
735
|
+
}
|
|
736
|
+
return plan;
|
|
737
|
+
});
|
|
738
|
+
}
|