iskills 0.2.60 → 0.2.63

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 (131) hide show
  1. package/AGENT-CLI.md +63 -0
  2. package/README.md +24 -17
  3. package/README.zh-CN.md +24 -17
  4. package/bin/command-route.mjs +15 -0
  5. package/bin/iskills.js +14 -7
  6. package/dist/src/cli.js +4 -12
  7. package/dist/src/cli.js.map +1 -1
  8. package/dist/src/commands/agent/arguments.d.ts +10 -0
  9. package/dist/src/commands/agent/arguments.js +60 -0
  10. package/dist/src/commands/agent/arguments.js.map +1 -0
  11. package/dist/src/commands/agent/index.d.ts +1 -0
  12. package/dist/src/commands/agent/index.js +778 -0
  13. package/dist/src/commands/agent/index.js.map +1 -0
  14. package/dist/src/commands/browser-actions.js +42 -12
  15. package/dist/src/commands/browser-actions.js.map +1 -1
  16. package/dist/src/commands/create.js +3 -3
  17. package/dist/src/commands/create.js.map +1 -1
  18. package/dist/src/commands/index.d.ts +0 -3
  19. package/dist/src/commands/index.js +0 -33
  20. package/dist/src/commands/index.js.map +1 -1
  21. package/dist/src/commands/library.d.ts +1 -0
  22. package/dist/src/commands/library.js +82 -120
  23. package/dist/src/commands/library.js.map +1 -1
  24. package/dist/src/commands/mcp.d.ts +1 -3
  25. package/dist/src/commands/mcp.js +7 -240
  26. package/dist/src/commands/mcp.js.map +1 -1
  27. package/dist/src/domain/agent-collection-write.d.ts +2 -0
  28. package/dist/src/domain/agent-collection-write.js +204 -0
  29. package/dist/src/domain/agent-collection-write.js.map +1 -0
  30. package/dist/src/domain/agent-mcp-write.d.ts +23 -0
  31. package/dist/src/domain/agent-mcp-write.js +927 -0
  32. package/dist/src/domain/agent-mcp-write.js.map +1 -0
  33. package/dist/src/domain/agent-read.d.ts +38 -0
  34. package/dist/src/domain/agent-read.js +524 -0
  35. package/dist/src/domain/agent-read.js.map +1 -0
  36. package/dist/src/domain/agent-skill-write.d.ts +34 -0
  37. package/dist/src/domain/agent-skill-write.js +926 -0
  38. package/dist/src/domain/agent-skill-write.js.map +1 -0
  39. package/dist/src/domain/agent-write.d.ts +9 -0
  40. package/dist/src/domain/agent-write.js +127 -0
  41. package/dist/src/domain/agent-write.js.map +1 -0
  42. package/dist/src/domain/collection-write.d.ts +9 -2
  43. package/dist/src/domain/collection-write.js +175 -36
  44. package/dist/src/domain/collection-write.js.map +1 -1
  45. package/dist/src/domain/core.d.ts +12 -0
  46. package/dist/src/domain/core.js +57 -2
  47. package/dist/src/domain/core.js.map +1 -1
  48. package/dist/src/domain/cross-agent-install.js +3 -5
  49. package/dist/src/domain/cross-agent-install.js.map +1 -1
  50. package/dist/src/domain/errors.d.ts +1 -0
  51. package/dist/src/domain/errors.js +3 -0
  52. package/dist/src/domain/errors.js.map +1 -1
  53. package/dist/src/domain/git.d.ts +28 -2
  54. package/dist/src/domain/git.js +233 -84
  55. package/dist/src/domain/git.js.map +1 -1
  56. package/dist/src/domain/install-target.js +10 -1
  57. package/dist/src/domain/install-target.js.map +1 -1
  58. package/dist/src/domain/mcp/collection.d.ts +3 -0
  59. package/dist/src/domain/mcp/collection.js +26 -4
  60. package/dist/src/domain/mcp/collection.js.map +1 -1
  61. package/dist/src/domain/mcp/dialects/borrow.js +1 -5
  62. package/dist/src/domain/mcp/dialects/borrow.js.map +1 -1
  63. package/dist/src/domain/mcp/index.d.ts +1 -1
  64. package/dist/src/domain/mcp/index.js +1 -1
  65. package/dist/src/domain/mcp/index.js.map +1 -1
  66. package/dist/src/domain/mcp/io.js +1 -1
  67. package/dist/src/domain/mcp/io.js.map +1 -1
  68. package/dist/src/domain/mcp/location-write.d.ts +3 -0
  69. package/dist/src/domain/mcp/location-write.js +39 -0
  70. package/dist/src/domain/mcp/location-write.js.map +1 -0
  71. package/dist/src/domain/mcp/probe.d.ts +2 -0
  72. package/dist/src/domain/mcp/probe.js +2 -1
  73. package/dist/src/domain/mcp/probe.js.map +1 -1
  74. package/dist/src/domain/mcp/recipe.d.ts +1 -1
  75. package/dist/src/domain/mcp/recipe.js +6 -5
  76. package/dist/src/domain/mcp/recipe.js.map +1 -1
  77. package/dist/src/domain/mcp/secrets.js +12 -11
  78. package/dist/src/domain/mcp/secrets.js.map +1 -1
  79. package/dist/src/domain/mcp/types.d.ts +2 -0
  80. package/dist/src/domain/mcp/write.js +49 -35
  81. package/dist/src/domain/mcp/write.js.map +1 -1
  82. package/dist/src/domain/operation.d.ts +30 -0
  83. package/dist/src/domain/operation.js +107 -0
  84. package/dist/src/domain/operation.js.map +1 -0
  85. package/dist/src/domain/process.d.ts +3 -0
  86. package/dist/src/domain/process.js +81 -0
  87. package/dist/src/domain/process.js.map +1 -0
  88. package/dist/src/domain/tags.d.ts +11 -0
  89. package/dist/src/domain/tags.js +42 -0
  90. package/dist/src/domain/tags.js.map +1 -0
  91. package/dist/src/domain/user-config.js +9 -1
  92. package/dist/src/domain/user-config.js.map +1 -1
  93. package/dist/src/i18n/en.js +55 -29
  94. package/dist/src/i18n/en.js.map +1 -1
  95. package/dist/src/i18n/zh.d.ts +56 -30
  96. package/dist/src/i18n/zh.js +56 -30
  97. package/dist/src/i18n/zh.js.map +1 -1
  98. package/dist/src/ui/browser/browse-capabilities.js +7 -1
  99. package/dist/src/ui/browser/browse-capabilities.js.map +1 -1
  100. package/dist/src/ui/browser/browse-session.d.ts +2 -0
  101. package/dist/src/ui/browser/browse-session.js +4 -0
  102. package/dist/src/ui/browser/browse-session.js.map +1 -1
  103. package/dist/src/ui/browser/browser.js +41 -12
  104. package/dist/src/ui/browser/browser.js.map +1 -1
  105. package/dist/src/ui/browser/index.js +3 -1
  106. package/dist/src/ui/browser/index.js.map +1 -1
  107. package/dist/src/ui/browser/types.d.ts +6 -0
  108. package/dist/src/ui/footer/resolve-footer.js +3 -0
  109. package/dist/src/ui/footer/resolve-footer.js.map +1 -1
  110. package/dist/src/ui/footer/types.d.ts +1 -0
  111. package/dist/src/ui/import/review.d.ts +2 -1
  112. package/dist/src/ui/import/review.js +8 -3
  113. package/dist/src/ui/import/review.js.map +1 -1
  114. package/dist/src/ui/import/types.d.ts +1 -0
  115. package/dist/src/ui/mcp/browse-capabilities.d.ts +1 -0
  116. package/dist/src/ui/mcp/browse-capabilities.js +1 -0
  117. package/dist/src/ui/mcp/browse-capabilities.js.map +1 -1
  118. package/dist/src/ui/mcp/browser.d.ts +2 -1
  119. package/dist/src/ui/mcp/browser.js +33 -5
  120. package/dist/src/ui/mcp/browser.js.map +1 -1
  121. package/dist/src/ui/mcp/index.js +29 -2
  122. package/dist/src/ui/mcp/index.js.map +1 -1
  123. package/dist/src/ui/prompts/index.d.ts +1 -1
  124. package/dist/src/ui/prompts/index.js +1 -1
  125. package/dist/src/ui/prompts/index.js.map +1 -1
  126. package/dist/src/ui/prompts/present.d.ts +5 -1
  127. package/dist/src/ui/prompts/present.js +11 -2
  128. package/dist/src/ui/prompts/present.js.map +1 -1
  129. package/dist/src/ui/tui/hooks.js +4 -0
  130. package/dist/src/ui/tui/hooks.js.map +1 -1
  131. package/package.json +16 -13
@@ -0,0 +1,927 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { resolve } from 'node:path';
4
+ import { isDeepStrictEqual } from 'node:util';
5
+ import { readMcps, readMcpLocations, mcpSelector, publicLocation, } from './agent-read.js';
6
+ import { executeWrites, conflictItem, requireAuthorization, } from './agent-write.js';
7
+ import { metadataPatch } from './agent-skill-write.js';
8
+ import { OperationFailure, registerSecrets, } from './operation.js';
9
+ import { assertMcpName, recipeEndpoint, recipesSameEndpoint, stripSecretUrl, } from './mcp/identity.js';
10
+ import { writeCollectedMcpRecord, deleteCollectedMcpFile, } from './mcp/collection.js';
11
+ import { readMcpSecrets, writeMcpSecrets, deleteMcpSecrets, emptySecrets, } from './mcp/secrets.js';
12
+ import { parseMcpJsonSnippet } from './mcp/json-snippet.js';
13
+ import { agentMcpWritable, ownedFilePath, isMcpAgentId, writeOwnedServer, setLocationEnabled, } from './mcp/dialects/index.js';
14
+ import { writeMcpLocation } from './mcp/location-write.js';
15
+ import { renameTagInList, writeTagRenameBatch, normalizeNewTagName, } from './tags.js';
16
+ import { isPlaceholder } from './mcp/recipe.js';
17
+ function object(value, keys) {
18
+ if (!value || typeof value !== 'object' || Array.isArray(value))
19
+ throw new OperationFailure('usage.invalidArguments', 'A JSON object is required.');
20
+ const data = value;
21
+ if (Object.keys(data).some((key) => !keys.includes(key)))
22
+ throw new OperationFailure('usage.invalidArguments', 'The JSON contains unknown fields.');
23
+ return data;
24
+ }
25
+ export function validateRecipe(raw) {
26
+ const recipe = object(raw, [
27
+ 'transport',
28
+ 'command',
29
+ 'args',
30
+ 'cwd',
31
+ 'url',
32
+ 'envKeys',
33
+ 'headerKeys',
34
+ ]);
35
+ if (!['stdio', 'http', 'sse'].includes(String(recipe.transport)))
36
+ throw new OperationFailure('usage.invalidArguments', 'Invalid MCP transport.');
37
+ for (const key of ['envKeys', 'headerKeys'])
38
+ if (!Array.isArray(recipe[key]) ||
39
+ recipe[key].some((value) => typeof value !== 'string' || !value))
40
+ throw new OperationFailure('usage.invalidArguments', 'Secret key lists must be arrays of strings.');
41
+ for (const key of ['command', 'cwd', 'url'])
42
+ if (recipe[key] !== undefined && typeof recipe[key] !== 'string')
43
+ throw new OperationFailure('usage.invalidArguments', 'MCP string field has an invalid type.', { field: key });
44
+ if (recipe.args !== undefined &&
45
+ (!Array.isArray(recipe.args) ||
46
+ recipe.args.some((value) => typeof value !== 'string')))
47
+ throw new OperationFailure('usage.invalidArguments', 'Arguments must be strings.');
48
+ if (recipe.transport === 'stdio') {
49
+ if (!recipe.command || recipe.url !== undefined)
50
+ throw new OperationFailure('usage.invalidArguments', 'stdio requires command and does not accept url.');
51
+ }
52
+ else {
53
+ if (!recipe.url ||
54
+ ['command', 'args', 'cwd'].some((key) => recipe[key] !== undefined))
55
+ throw new OperationFailure('usage.invalidArguments', 'HTTP/SSE requires url and does not accept process fields.');
56
+ try {
57
+ if (!['https:', 'http:'].includes(new URL(recipe.url).protocol))
58
+ throw new Error();
59
+ }
60
+ catch {
61
+ throw new OperationFailure('usage.invalidArguments', 'A valid HTTP URL is required.');
62
+ }
63
+ }
64
+ return recipe;
65
+ }
66
+ function validateSecrets(raw) {
67
+ if (raw === undefined)
68
+ return emptySecrets();
69
+ const data = object(raw, ['env', 'headers', 'url']);
70
+ const out = emptySecrets();
71
+ for (const slot of ['env', 'headers']) {
72
+ if (data[slot] === undefined)
73
+ continue;
74
+ if (!data[slot] ||
75
+ typeof data[slot] !== 'object' ||
76
+ Array.isArray(data[slot]))
77
+ throw new OperationFailure('usage.invalidArguments', 'Secrets must be string maps.');
78
+ for (const [key, value] of Object.entries(data[slot])) {
79
+ if (typeof value !== 'string')
80
+ throw new OperationFailure('usage.invalidArguments', 'Secret values must be strings.');
81
+ out[slot][key] = value;
82
+ }
83
+ }
84
+ if (data.url !== undefined) {
85
+ if (typeof data.url !== 'string')
86
+ throw new OperationFailure('usage.invalidArguments', 'Secret URL must be a string.');
87
+ out.url = data.url;
88
+ }
89
+ return out;
90
+ }
91
+ async function inputText(path, project) {
92
+ if (path !== '-')
93
+ return readFile(resolve(project, path), 'utf8');
94
+ const chunks = [];
95
+ for await (const chunk of process.stdin)
96
+ chunks.push(Buffer.from(chunk));
97
+ return Buffer.concat(chunks).toString('utf8');
98
+ }
99
+ async function jsonInput(path, project) {
100
+ if (typeof path !== 'string')
101
+ throw new OperationFailure('usage.invalidArguments', '--input is required.');
102
+ try {
103
+ return JSON.parse(await inputText(path, project));
104
+ }
105
+ catch (error) {
106
+ if (error instanceof SyntaxError)
107
+ throw new OperationFailure('usage.invalidArguments', 'Input JSON is invalid.');
108
+ throw error;
109
+ }
110
+ }
111
+ export function fillMissing(base, incoming) {
112
+ const next = {
113
+ env: { ...base.env },
114
+ headers: { ...base.headers },
115
+ ...(base.url ? { url: base.url } : {}),
116
+ };
117
+ for (const slot of ['env', 'headers'])
118
+ for (const [key, value] of Object.entries(incoming[slot])) {
119
+ const existing = Object.keys(next[slot]).find((name) => slot === 'headers'
120
+ ? name.toLowerCase() === key.toLowerCase()
121
+ : name === key);
122
+ if (!existing ||
123
+ !next[slot][existing] ||
124
+ isPlaceholder(next[slot][existing])) {
125
+ if (existing)
126
+ delete next[slot][existing];
127
+ next[slot][key] = value;
128
+ }
129
+ }
130
+ if (!next.url && incoming.url)
131
+ next.url = incoming.url;
132
+ return next;
133
+ }
134
+ export function checkSecrets(recipe, secrets, name) {
135
+ const missingKeys = [
136
+ ...recipe.envKeys
137
+ .filter((key) => !secrets.env[key] || isPlaceholder(secrets.env[key]))
138
+ .map((key) => ({ slot: 'env', key })),
139
+ ...recipe.headerKeys
140
+ .filter((key) => !Object.entries(secrets.headers).some(([stored, value]) => stored.toLowerCase() === key.toLowerCase() &&
141
+ value &&
142
+ !isPlaceholder(value)))
143
+ .map((key) => ({ slot: 'headers', key })),
144
+ ];
145
+ if (missingKeys.length)
146
+ throw new OperationFailure('mcp.missingSecrets', 'Required MCP secrets are missing.', { name, missingKeys }, 1);
147
+ }
148
+ function validateNames(names) {
149
+ for (const name of names)
150
+ try {
151
+ if (assertMcpName(name) !== name)
152
+ throw new Error();
153
+ }
154
+ catch {
155
+ throw new OperationFailure('usage.invalidArguments', 'Invalid MCP name.');
156
+ }
157
+ }
158
+ export async function selectMcpLocations(selectors, project, allowAbsent = false) {
159
+ if (!selectors.length)
160
+ throw new OperationFailure('usage.selectionRequired', 'At least one MCP location is required.');
161
+ const locations = await readMcpLocations(project, [], ['project', 'global']);
162
+ if (locations.issues.length)
163
+ throw new OperationFailure('execution.readFailed', 'MCP locations could not be read completely.', { issues: locations.issues }, 1);
164
+ return [...new Set(selectors)].map((selector) => {
165
+ let identity;
166
+ try {
167
+ identity = JSON.parse(Buffer.from(selector.slice(5), 'base64url').toString());
168
+ }
169
+ catch {
170
+ throw new OperationFailure('usage.invalidLocation', 'Invalid MCP selector.');
171
+ }
172
+ if (!selector.startsWith('mcp1-') ||
173
+ !Array.isArray(identity) ||
174
+ identity.length !== 6 ||
175
+ identity.some((part) => typeof part !== 'string') ||
176
+ identity[0] !== project ||
177
+ !isMcpAgentId(identity[1]) ||
178
+ !['project', 'global'].includes(identity[2]) ||
179
+ !['owned', 'borrowed'].includes(identity[3]) ||
180
+ !identity[4].startsWith('/') ||
181
+ !identity[5])
182
+ throw new OperationFailure('usage.invalidLocation', 'The MCP selector belongs to a different project or is invalid.');
183
+ const matches = locations.entries.filter((entry) => mcpSelector(entry, project) === selector);
184
+ if (matches.length > 1)
185
+ throw new OperationFailure('usage.ambiguousSelection', 'The MCP selector matches multiple entries.');
186
+ if (!matches.length) {
187
+ if (allowAbsent)
188
+ return { absent: true, selector };
189
+ throw new OperationFailure('usage.selectionNotFound', 'The selected MCP location no longer exists.', { selector });
190
+ }
191
+ return matches[0];
192
+ });
193
+ }
194
+ export async function executeMcpWrite(request) {
195
+ const { command, project, options, signal } = request;
196
+ const names = ['mcp.rename', 'mcp.tag.rename'].includes(command)
197
+ ? request.names
198
+ : [...new Set(request.names)];
199
+ const dryRun = options['dry-run'] === true;
200
+ if (['mcp.create', 'mcp.import'].includes(command))
201
+ return collectMcps(request);
202
+ if ([
203
+ 'mcp.add',
204
+ 'mcp.update',
205
+ 'mcp.enable',
206
+ 'mcp.disable',
207
+ 'mcp.uninstall',
208
+ ].includes(command))
209
+ return maintainMcpLocations(request);
210
+ if (command !== 'mcp.tag.rename')
211
+ validateNames(names);
212
+ const collection = await readMcps();
213
+ if (collection.issues.length)
214
+ throw new OperationFailure('execution.readFailed', 'The MCP collection contains unreadable entries.', { issues: collection.issues }, 1);
215
+ const lookup = (name) => {
216
+ const item = collection.items.find((mcp) => mcp.name === name);
217
+ if (!item)
218
+ throw new OperationFailure('usage.selectionNotFound', 'The MCP is not collected.', { name });
219
+ return item;
220
+ };
221
+ const plans = [];
222
+ if (command === 'mcp.tag.rename') {
223
+ if (names.length !== 2)
224
+ throw new OperationFailure('usage.invalidArguments', 'Two tag names are required.');
225
+ const [from, to] = names;
226
+ normalizeNewTagName(to);
227
+ const changes = collection.items.flatMap((before) => {
228
+ const tags = renameTagInList(before.tags, from, to);
229
+ return tags ? [{ before, after: { ...before, tags } }] : [];
230
+ });
231
+ plans.push({
232
+ item: {
233
+ name: from,
234
+ action: 'rename-tag',
235
+ status: changes.length ? 'planned' : 'unchanged',
236
+ reason: 'same-value',
237
+ affectedNames: changes.map((change) => change.before.name),
238
+ },
239
+ execute: () => writeTagRenameBatch(changes, writeCollectedMcpRecord),
240
+ });
241
+ }
242
+ else if (command === 'mcp.remove') {
243
+ if (!names.length)
244
+ throw new OperationFailure('usage.selectionRequired', 'Select at least one MCP.');
245
+ requireAuthorization(options.yes === true, dryRun, names);
246
+ for (const name of names) {
247
+ const present = collection.items.some((item) => item.name === name);
248
+ const secrets = await readMcpSecrets(name);
249
+ const item = {
250
+ name,
251
+ action: 'remove',
252
+ status: present || !isDeepStrictEqual(secrets, emptySecrets())
253
+ ? 'planned'
254
+ : 'unchanged',
255
+ reason: 'absent',
256
+ requiredFlags: ['--yes'],
257
+ stages: {
258
+ recipe: present ? 'planned' : 'unchanged',
259
+ secrets: 'planned',
260
+ },
261
+ };
262
+ plans.push({
263
+ item,
264
+ execute: async () => {
265
+ try {
266
+ await deleteCollectedMcpFile(name);
267
+ item.stages.recipe = present ? 'committed' : 'unchanged';
268
+ }
269
+ catch (error) {
270
+ item.stages.recipe = 'failed';
271
+ item.stages.secrets = 'not-run';
272
+ throw error;
273
+ }
274
+ try {
275
+ await deleteMcpSecrets(name);
276
+ item.stages.secrets = isDeepStrictEqual(secrets, emptySecrets())
277
+ ? 'unchanged'
278
+ : 'committed';
279
+ }
280
+ catch (error) {
281
+ item.stages.secrets = 'failed';
282
+ throw error;
283
+ }
284
+ },
285
+ });
286
+ }
287
+ }
288
+ else if (command === 'mcp.rename') {
289
+ if (names.length !== 2)
290
+ throw new OperationFailure('usage.invalidArguments', 'The old and new MCP names are required.');
291
+ const before = lookup(names[0]);
292
+ const name = names[1];
293
+ const secrets = await readMcpSecrets(before.name);
294
+ let item = {
295
+ name: before.name,
296
+ newName: name,
297
+ action: 'rename',
298
+ status: 'planned',
299
+ };
300
+ if (before.name === name)
301
+ item = { ...item, status: 'unchanged', reason: 'same-name' };
302
+ else if (collection.items.some((entry) => entry.name === name))
303
+ item = conflictItem(item, 'conflict.alreadyExists', { name });
304
+ const stages = {
305
+ recipe: item.status === 'unchanged' ? 'unchanged' : 'planned',
306
+ secrets: item.status === 'unchanged' ? 'unchanged' : 'planned',
307
+ };
308
+ item.stages = stages;
309
+ plans.push({
310
+ item,
311
+ execute: async () => {
312
+ try {
313
+ await writeCollectedMcpRecord({ ...before, name });
314
+ stages.recipe = 'committed';
315
+ }
316
+ catch (error) {
317
+ stages.recipe = 'failed';
318
+ stages.secrets = 'not-run';
319
+ throw error;
320
+ }
321
+ try {
322
+ await writeMcpSecrets(name, secrets);
323
+ await deleteMcpSecrets(before.name);
324
+ stages.secrets = 'committed';
325
+ await deleteCollectedMcpFile(before.name);
326
+ }
327
+ catch (error) {
328
+ stages.secrets = 'failed';
329
+ throw error;
330
+ }
331
+ },
332
+ });
333
+ }
334
+ else {
335
+ if (names.length !== 1)
336
+ throw new OperationFailure('usage.invalidArguments', 'Exactly one MCP name is required.');
337
+ const before = lookup(names[0]);
338
+ const secrets = await readMcpSecrets(before.name);
339
+ if (command === 'mcp.edit') {
340
+ if (![
341
+ 'recipe-input',
342
+ 'description',
343
+ 'tags',
344
+ 'add-tag',
345
+ 'remove-tag',
346
+ 'note',
347
+ ].some((key) => options[key] !== undefined))
348
+ throw new OperationFailure('usage.invalidArguments', 'At least one field is required.');
349
+ const recipe = options['recipe-input']
350
+ ? validateRecipe(await jsonInput(options['recipe-input'], project))
351
+ : before.recipe;
352
+ if (recipe.url && stripSecretUrl(recipe.url).secretUrl)
353
+ throw new OperationFailure('usage.invalidArguments', 'Recipe URLs cannot contain credentials; use secret set --url.');
354
+ const next = {
355
+ ...before,
356
+ ...metadataPatch(before, options),
357
+ recipe,
358
+ };
359
+ const clearSecrets = Boolean(before.secretsResetPending ||
360
+ !recipesSameEndpoint(before.recipe, next.recipe));
361
+ const stages = {
362
+ recipe: 'planned',
363
+ secrets: clearSecrets ? 'planned' : 'unchanged',
364
+ };
365
+ const item = {
366
+ name: before.name,
367
+ action: 'edit',
368
+ status: isDeepStrictEqual(before, next) ? 'unchanged' : 'planned',
369
+ reason: 'same-value',
370
+ stages,
371
+ clearSecretKeys: clearSecrets
372
+ ? {
373
+ env: Object.keys(secrets.env),
374
+ headers: Object.keys(secrets.headers),
375
+ url: Boolean(secrets.url),
376
+ }
377
+ : null,
378
+ };
379
+ if (item.status === 'unchanged')
380
+ stages.recipe = 'unchanged';
381
+ plans.push({
382
+ item,
383
+ execute: async () => {
384
+ try {
385
+ await writeCollectedMcpRecord({
386
+ ...next,
387
+ secretsResetPending: clearSecrets,
388
+ });
389
+ stages.recipe = 'committed';
390
+ }
391
+ catch (error) {
392
+ stages.recipe = 'failed';
393
+ stages.secrets = 'not-run';
394
+ throw error;
395
+ }
396
+ if (clearSecrets) {
397
+ try {
398
+ await deleteMcpSecrets(before.name);
399
+ stages.secrets = 'committed';
400
+ await writeCollectedMcpRecord({
401
+ ...next,
402
+ secretsResetPending: false,
403
+ });
404
+ }
405
+ catch (error) {
406
+ stages.secrets = 'failed';
407
+ throw error;
408
+ }
409
+ }
410
+ },
411
+ });
412
+ }
413
+ else if (['mcp.secret.set', 'mcp.secret.unset'].includes(command)) {
414
+ if (before.secretsResetPending)
415
+ throw new OperationFailure('mcp.missingSecrets', 'Complete the endpoint credential reset by retrying import or edit first.', { name: before.name, stage: 'secrets' }, 1);
416
+ const slots = ['env', 'header', 'url'].filter((key) => options[key] !== undefined);
417
+ if (slots.length !== 1)
418
+ throw new OperationFailure('usage.invalidArguments', 'Choose exactly one secret slot.');
419
+ const slot = slots[0] === 'header' ? 'headers' : slots[0];
420
+ const key = slot === 'url' ? 'url' : String(options[slots[0]]);
421
+ if ((slot === 'env' && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) ||
422
+ (slot === 'headers' && !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(key)))
423
+ throw new OperationFailure('usage.invalidArguments', 'Invalid secret key.');
424
+ if (slot === 'url' && before.recipe.transport === 'stdio')
425
+ throw new OperationFailure('usage.unsupportedCapability', 'stdio has no secret URL.');
426
+ const next = structuredClone(secrets);
427
+ let value;
428
+ if (command.endsWith('.set')) {
429
+ if (Boolean(options['value-stdin']) === Boolean(options['value-file']))
430
+ throw new OperationFailure('usage.invalidArguments', 'Choose --value-stdin or --value-file.');
431
+ value = (await inputText(options['value-stdin'] ? '-' : String(options['value-file']), project)).replace(/\r?\n$/, '');
432
+ if (!value)
433
+ throw new OperationFailure('usage.invalidArguments', 'An empty secret value is not accepted.');
434
+ if (slot === 'url' &&
435
+ !recipesSameEndpoint(before.recipe, { ...before.recipe, url: value }))
436
+ throw new OperationFailure('usage.invalidArguments', 'The secret URL must identify the collected endpoint.');
437
+ }
438
+ else
439
+ requireAuthorization(options.yes === true, dryRun, names);
440
+ if (slot === 'url' && value !== undefined) {
441
+ try {
442
+ if (!['http:', 'https:'].includes(new URL(value).protocol))
443
+ throw new Error();
444
+ }
445
+ catch {
446
+ throw new OperationFailure('usage.invalidArguments', 'A valid HTTP URL is required.');
447
+ }
448
+ }
449
+ if (slot === 'url') {
450
+ if (value !== undefined)
451
+ next.url = value;
452
+ else
453
+ delete next.url;
454
+ }
455
+ else {
456
+ const map = next[slot];
457
+ const stored = Object.keys(map).find((name) => slot === 'headers'
458
+ ? name.toLowerCase() === key.toLowerCase()
459
+ : name === key);
460
+ if (stored)
461
+ delete map[stored];
462
+ if (value !== undefined)
463
+ map[key] = value;
464
+ }
465
+ const unchanged = isDeepStrictEqual(secrets, next);
466
+ const stages = {
467
+ recipe: 'unchanged',
468
+ secrets: unchanged ? 'unchanged' : 'planned',
469
+ };
470
+ plans.push({
471
+ item: {
472
+ name: before.name,
473
+ slot,
474
+ key,
475
+ action: command.endsWith('.set') ? 'set-secret' : 'unset-secret',
476
+ status: unchanged ? 'unchanged' : 'planned',
477
+ reason: 'same-value',
478
+ configured: value !== undefined,
479
+ stages,
480
+ },
481
+ execute: async () => {
482
+ try {
483
+ await writeMcpSecrets(before.name, next);
484
+ stages.secrets = 'committed';
485
+ }
486
+ catch (error) {
487
+ stages.secrets = 'failed';
488
+ throw error;
489
+ }
490
+ },
491
+ });
492
+ }
493
+ else
494
+ throw new OperationFailure('usage.unknownCommand', 'Unknown MCP operation.');
495
+ }
496
+ return executeWrites(plans, dryRun, true, command, signal);
497
+ }
498
+ async function collectMcps(request) {
499
+ const { command, options, project, signal } = request;
500
+ const names = [...new Set(request.names)];
501
+ const incoming = [];
502
+ if (command === 'mcp.create') {
503
+ if (names.length !== 1)
504
+ throw new OperationFailure('usage.invalidArguments', 'One MCP name is required.');
505
+ validateNames(names);
506
+ const data = object(await jsonInput(options.input, project), [
507
+ 'recipe',
508
+ 'description',
509
+ 'tags',
510
+ 'note',
511
+ 'secrets',
512
+ ]);
513
+ for (const key of ['description', 'note'])
514
+ if (data[key] !== undefined && typeof data[key] !== 'string')
515
+ throw new OperationFailure('usage.invalidArguments', 'Metadata values must be strings.');
516
+ if (data.tags !== undefined &&
517
+ (!Array.isArray(data.tags) ||
518
+ data.tags.some((tag) => typeof tag !== 'string')))
519
+ throw new OperationFailure('usage.invalidArguments', 'Tags must be strings.');
520
+ const recipe = validateRecipe(data.recipe);
521
+ const secrets = validateSecrets(data.secrets);
522
+ if (recipe.url) {
523
+ const stripped = stripSecretUrl(recipe.url);
524
+ recipe.url = stripped.recipeUrl;
525
+ if (stripped.secretUrl)
526
+ secrets.url = stripped.secretUrl;
527
+ }
528
+ incoming.push({
529
+ mcp: {
530
+ name: names[0],
531
+ description: (data.description ?? ''),
532
+ note: (data.note ?? ''),
533
+ tags: (data.tags ?? []),
534
+ source: { type: 'create' },
535
+ recipe,
536
+ },
537
+ secrets,
538
+ });
539
+ }
540
+ else {
541
+ if (names.length ||
542
+ Boolean(options.input) ===
543
+ Boolean(options.location?.length))
544
+ throw new OperationFailure('usage.invalidArguments', 'Choose --input or --location for import.');
545
+ if (options.input) {
546
+ const parsed = parseMcpJsonSnippet(await inputText(String(options.input), project));
547
+ if (!parsed.ok)
548
+ throw new OperationFailure('usage.invalidArguments', 'The MCP JSON snippet could not be parsed.');
549
+ if (options.name &&
550
+ (parsed.entries.length !== 1 || !parsed.entries[0].unnamed))
551
+ throw new OperationFailure('usage.invalidArguments', '--name is only valid for an unnamed single entry.');
552
+ for (const entry of parsed.entries) {
553
+ const name = entry.unnamed ? String(options.name ?? '') : entry.name;
554
+ validateNames([name]);
555
+ incoming.push({
556
+ mcp: {
557
+ name,
558
+ description: '',
559
+ note: '',
560
+ tags: [],
561
+ source: { type: 'create' },
562
+ recipe: entry.recipe,
563
+ },
564
+ secrets: entry.secrets,
565
+ });
566
+ }
567
+ }
568
+ else {
569
+ if (options.name)
570
+ throw new OperationFailure('usage.invalidArguments', '--name cannot be combined with location import.');
571
+ for (const row of await selectMcpLocations(options.location, project)) {
572
+ if ('absent' in row)
573
+ continue;
574
+ incoming.push({
575
+ mcp: {
576
+ name: assertMcpName(row.nativeKey),
577
+ description: '',
578
+ tags: [],
579
+ note: '',
580
+ recipe: row.recipe,
581
+ source: {
582
+ type: row.agent,
583
+ agent: row.agent,
584
+ scope: row.scope,
585
+ nativeKey: row.nativeKey,
586
+ path: row.filePath,
587
+ },
588
+ },
589
+ secrets: row.secrets,
590
+ });
591
+ }
592
+ }
593
+ }
594
+ return collectMcpRecords(incoming, options, command, signal);
595
+ }
596
+ export async function collectMcpRecords(incoming, options, command, signal) {
597
+ if (new Set(incoming.map((entry) => entry.mcp.name)).size !== incoming.length)
598
+ throw new OperationFailure('usage.ambiguousSelection', 'Duplicate names in the MCP import.');
599
+ const collection = await readMcps();
600
+ if (collection.issues.length)
601
+ throw new OperationFailure('execution.readFailed', 'The MCP collection contains unreadable entries.', { issues: collection.issues }, 1);
602
+ const plans = [];
603
+ for (const { mcp, secrets } of incoming) {
604
+ registerSecrets(secrets);
605
+ const current = collection.items.find((entry) => entry.name === mcp.name);
606
+ const sameEndpoint = collection.items.find((entry) => recipesSameEndpoint(entry.recipe, mcp.recipe));
607
+ const previousSecrets = current
608
+ ? await readMcpSecrets(current.name)
609
+ : emptySecrets();
610
+ let nextSecrets = secrets;
611
+ let recipeChange = true;
612
+ let item = {
613
+ name: mcp.name,
614
+ action: command.endsWith('create') ? 'create' : 'import',
615
+ status: 'planned',
616
+ stages: { recipe: 'planned', secrets: 'planned' },
617
+ secretKeys: {
618
+ env: Object.keys(secrets.env),
619
+ headers: Object.keys(secrets.headers),
620
+ url: Boolean(secrets.url),
621
+ },
622
+ removedSecretKeys: current && !recipesSameEndpoint(current.recipe, mcp.recipe)
623
+ ? {
624
+ env: Object.keys(previousSecrets.env),
625
+ headers: Object.keys(previousSecrets.headers),
626
+ url: Boolean(previousSecrets.url),
627
+ }
628
+ : null,
629
+ };
630
+ if (current) {
631
+ if (command === 'mcp.create') {
632
+ item =
633
+ isDeepStrictEqual({
634
+ recipe: current.recipe,
635
+ description: current.description,
636
+ tags: current.tags,
637
+ note: current.note,
638
+ }, {
639
+ recipe: mcp.recipe,
640
+ description: mcp.description,
641
+ tags: mcp.tags,
642
+ note: mcp.note,
643
+ }) && isDeepStrictEqual(previousSecrets, secrets)
644
+ ? { ...item, status: 'unchanged', reason: 'same-input' }
645
+ : conflictItem(item, 'conflict.alreadyExists', { name: mcp.name });
646
+ }
647
+ else if (recipesSameEndpoint(current.recipe, mcp.recipe)) {
648
+ recipeChange = false;
649
+ nextSecrets = current.secretsResetPending
650
+ ? secrets
651
+ : fillMissing(previousSecrets, secrets);
652
+ item.reason = 'secrets-completed';
653
+ if (!current.secretsResetPending &&
654
+ isDeepStrictEqual(nextSecrets, previousSecrets))
655
+ item = { ...item, status: 'unchanged', reason: 'same-source' };
656
+ }
657
+ else if (!options.replace)
658
+ item = conflictItem(item, 'conflict.sameName', {
659
+ name: mcp.name,
660
+ existing: {
661
+ transport: current.recipe.transport,
662
+ url: current.recipe.url,
663
+ },
664
+ incoming: { transport: mcp.recipe.transport, url: mcp.recipe.url },
665
+ requiredFlags: ['--replace'],
666
+ });
667
+ }
668
+ else if (sameEndpoint && command !== 'mcp.create')
669
+ item = {
670
+ ...item,
671
+ status: 'unchanged',
672
+ reason: 'collected-as',
673
+ collectedName: sameEndpoint.name,
674
+ };
675
+ const stages = item.stages;
676
+ const resetting = Boolean(current &&
677
+ (current.secretsResetPending ||
678
+ !recipesSameEndpoint(current.recipe, mcp.recipe)));
679
+ if (item.status === 'unchanged') {
680
+ stages.recipe = 'unchanged';
681
+ stages.secrets = 'unchanged';
682
+ }
683
+ else if (!recipeChange)
684
+ stages.recipe = 'unchanged';
685
+ plans.push({
686
+ item,
687
+ execute: async () => {
688
+ try {
689
+ if (recipeChange) {
690
+ await writeCollectedMcpRecord({
691
+ ...mcp,
692
+ secretsResetPending: resetting,
693
+ });
694
+ stages.recipe = 'committed';
695
+ }
696
+ else
697
+ stages.recipe = 'unchanged';
698
+ }
699
+ catch (error) {
700
+ stages.recipe = 'failed';
701
+ stages.secrets = 'not-run';
702
+ throw error;
703
+ }
704
+ try {
705
+ if (resetting || !isDeepStrictEqual(previousSecrets, nextSecrets)) {
706
+ await writeMcpSecrets(current?.name ?? mcp.name, nextSecrets);
707
+ stages.secrets = 'committed';
708
+ }
709
+ else
710
+ stages.secrets = 'unchanged';
711
+ if (resetting)
712
+ await writeCollectedMcpRecord({
713
+ ...(recipeChange ? mcp : current),
714
+ secretsResetPending: false,
715
+ });
716
+ }
717
+ catch (error) {
718
+ stages.secrets = 'failed';
719
+ item.restored = false;
720
+ throw error;
721
+ }
722
+ },
723
+ });
724
+ }
725
+ return executeWrites(plans, options['dry-run'] === true, true, command, signal);
726
+ }
727
+ async function maintainMcpLocations(request) {
728
+ const { command, options, project, signal } = request;
729
+ const names = [...new Set(request.names)];
730
+ const ctx = { cwd: project, home: homedir() };
731
+ const plans = [];
732
+ if (command === 'mcp.add') {
733
+ if (!names.length ||
734
+ !options.agent?.length ||
735
+ !['project', 'global'].includes(String(options.scope)))
736
+ throw new OperationFailure('usage.invalidArguments', 'MCP add requires names, --agent and --scope.');
737
+ const targets = [...new Set(options.agent)];
738
+ const scope = options.scope;
739
+ plans.push(...(await planMcpAdds(names, targets.map((agent) => ({ agent, scope })), ctx, options.replace === true)));
740
+ }
741
+ else {
742
+ const selectors = command === 'mcp.update' ? (options.location ?? []) : names;
743
+ if (command === 'mcp.update' && names.length !== 1)
744
+ throw new OperationFailure('usage.invalidArguments', 'MCP update requires one collection name.');
745
+ if (command === 'mcp.uninstall')
746
+ requireAuthorization(options.yes === true, options['dry-run'] === true, names);
747
+ const entries = await selectMcpLocations(selectors, project, command === 'mcp.uninstall');
748
+ const collection = command === 'mcp.update' ? await readMcps() : undefined;
749
+ if (collection?.issues.length)
750
+ throw new OperationFailure('execution.readFailed', 'The MCP collection contains unreadable entries.', { issues: collection.issues }, 1);
751
+ const collected = collection?.items.find((entry) => entry.name === names[0]);
752
+ if (command === 'mcp.update' && !collected)
753
+ throw new OperationFailure('usage.selectionNotFound', 'The MCP is not collected.', { name: names[0] });
754
+ if (collected?.secretsResetPending)
755
+ throw new OperationFailure('mcp.missingSecrets', 'Complete the endpoint credential reset before updating a location.', { name: collected.name, stage: 'secrets' }, 1);
756
+ const overlay = collected
757
+ ? await readMcpSecrets(collected.name)
758
+ : emptySecrets();
759
+ if (collected)
760
+ checkSecrets(collected.recipe, overlay, collected.name);
761
+ for (const entry of entries) {
762
+ if ('absent' in entry) {
763
+ plans.push({
764
+ item: {
765
+ selector: entry.selector,
766
+ action: 'uninstall',
767
+ status: 'unchanged',
768
+ reason: 'absent',
769
+ },
770
+ execute: async () => { },
771
+ });
772
+ continue;
773
+ }
774
+ const info = publicLocation(entry, project);
775
+ const switchable = ['mcp.enable', 'mcp.disable'].includes(command);
776
+ if (!(switchable ? info.canEnable : info.canUpdate))
777
+ throw new OperationFailure('mcp.borrowedNotMutable', 'The selected MCP does not support this operation.', { selector: info.selector });
778
+ let item = {
779
+ ...info,
780
+ action: command.split('.').at(-1),
781
+ status: 'planned',
782
+ };
783
+ if (switchable) {
784
+ const enabled = command === 'mcp.enable';
785
+ if (entry.enabled === enabled)
786
+ item = { ...item, status: 'unchanged', reason: 'same-state' };
787
+ if (entry.agent === 'claude') {
788
+ const all = await readMcpLocations(project, ['claude'], ['project', 'global']);
789
+ const kind = entry.filePath.endsWith('/.mcp.json');
790
+ item.affectedLocations = all.entries
791
+ .filter((row) => row.nativeKey === entry.nativeKey &&
792
+ row.filePath.endsWith('/.mcp.json') === kind)
793
+ .map((row) => mcpSelector(row, project));
794
+ item.writeFiles = [resolve(ctx.home, '.claude.json')];
795
+ }
796
+ else {
797
+ item.affectedLocations = [info.selector];
798
+ item.writeFiles = [entry.filePath];
799
+ }
800
+ plans.push({
801
+ item,
802
+ execute: async () => {
803
+ await setLocationEnabled(entry, ctx, enabled);
804
+ item.enabled = enabled;
805
+ },
806
+ });
807
+ }
808
+ else if (command === 'mcp.uninstall') {
809
+ item.requiredFlags = ['--yes'];
810
+ plans.push({ item, execute: () => writeMcpLocation(entry, ctx) });
811
+ }
812
+ else {
813
+ if (isDeepStrictEqual(entry.recipe, collected.recipe) &&
814
+ isDeepStrictEqual(entry.secrets, overlay))
815
+ item = { ...item, status: 'unchanged', reason: 'same-value' };
816
+ else if (!options.replace)
817
+ item = conflictItem(item, 'conflict.targetExists', {
818
+ selector: info.selector,
819
+ requiredFlags: ['--replace'],
820
+ });
821
+ plans.push({
822
+ item,
823
+ execute: () => writeMcpLocation(entry, ctx, collected.recipe, overlay),
824
+ });
825
+ }
826
+ }
827
+ }
828
+ return executeWrites(plans, options['dry-run'] === true, false, command, signal);
829
+ }
830
+ export async function planMcpAdds(names, targets, ctx, replace = false) {
831
+ validateNames(names);
832
+ const project = ctx.cwd;
833
+ const collection = await readMcps();
834
+ const plans = [];
835
+ const targetKeys = new Set();
836
+ const locations = await readMcpLocations(project, [...new Set(targets.map((target) => target.agent))], [...new Set(targets.map((target) => target.scope))], ctx.home);
837
+ if (locations.issues.length || collection.issues.length)
838
+ throw new OperationFailure('execution.readFailed', 'The MCP configuration could not be read completely.', {}, 1);
839
+ const plannedEndpoints = new Set();
840
+ for (const name of names) {
841
+ const mcp = collection.items.find((entry) => entry.name === name);
842
+ if (!mcp)
843
+ throw new OperationFailure('usage.selectionNotFound', 'The MCP is not collected.', { name });
844
+ const secrets = await readMcpSecrets(name);
845
+ if (mcp.secretsResetPending)
846
+ throw new OperationFailure('mcp.missingSecrets', 'The endpoint credential reset must be completed before writing this MCP.', { name, stage: 'secrets' }, 1);
847
+ checkSecrets(mcp.recipe, secrets, name);
848
+ const identity = recipeEndpoint(mcp.recipe);
849
+ if (plannedEndpoints.has(identity))
850
+ throw new OperationFailure('usage.ambiguousSelection', 'Multiple selected MCPs have the same endpoint.');
851
+ plannedEndpoints.add(identity);
852
+ for (const { agent, scope } of targets) {
853
+ if (!isMcpAgentId(agent))
854
+ throw new OperationFailure('usage.unsupportedCapability', 'Unknown MCP Agent.', { agent });
855
+ if (!(await agentMcpWritable(agent, scope, ctx)))
856
+ throw new OperationFailure('mcp.notWritable', 'The MCP target is not writable.', { agent, scope });
857
+ const entries = locations.entries.filter((entry) => entry.agent === agent && entry.scope === scope);
858
+ const byEndpoint = entries.filter((entry) => recipesSameEndpoint(entry.recipe, mcp.recipe));
859
+ const byName = entries.filter((entry) => entry.nativeKey === name);
860
+ if (byEndpoint.length > 1 ||
861
+ byName.length > 1 ||
862
+ (byName.length && byEndpoint.some((entry) => entry.nativeKey !== name)))
863
+ throw new OperationFailure('usage.ambiguousSelection', 'The target MCP is ambiguous.', {
864
+ candidates: [...byName, ...byEndpoint].map((entry) => publicLocation(entry, project)),
865
+ });
866
+ const file = ownedFilePath(agent, scope, ctx);
867
+ const targetKey = JSON.stringify([
868
+ file,
869
+ agent === 'claude' ? scope : null,
870
+ name,
871
+ ]);
872
+ if (targetKeys.has(targetKey))
873
+ continue;
874
+ targetKeys.add(targetKey);
875
+ let item = {
876
+ name,
877
+ agent,
878
+ scope,
879
+ file,
880
+ nativeKey: name,
881
+ action: 'add',
882
+ status: 'planned',
883
+ ownership: 'owned',
884
+ enabled: true,
885
+ };
886
+ if (byEndpoint.length)
887
+ item = {
888
+ ...item,
889
+ ...publicLocation(byEndpoint[0], project),
890
+ status: 'unchanged',
891
+ reason: 'already-present',
892
+ };
893
+ else if (byName.length) {
894
+ if (byName[0].ownership !== 'owned')
895
+ throw new OperationFailure('mcp.borrowedNotMutable', 'The conflicting target is borrowed.');
896
+ if (!replace)
897
+ item = conflictItem(item, 'conflict.sameName', {
898
+ existing: publicLocation(byName[0], project),
899
+ requiredFlags: ['--replace'],
900
+ });
901
+ else {
902
+ item.action = 'replace';
903
+ item.file = byName[0].filePath;
904
+ item.enabled = byName[0].enabled;
905
+ }
906
+ }
907
+ plans.push({
908
+ item,
909
+ execute: async () => {
910
+ if (byName[0])
911
+ await writeMcpLocation(byName[0], ctx, mcp.recipe, secrets);
912
+ else
913
+ await writeOwnedServer(agent, scope, ctx, name, mcp.recipe, secrets);
914
+ const selected = (await readMcpLocations(project, [agent], [scope], ctx.home)).entries.find((entry) => entry.nativeKey === name && entry.ownership === 'owned');
915
+ if (selected)
916
+ Object.assign(item, {
917
+ selector: mcpSelector(selected, project),
918
+ enabled: selected.enabled,
919
+ ownership: selected.ownership,
920
+ });
921
+ },
922
+ });
923
+ }
924
+ }
925
+ return plans;
926
+ }
927
+ //# sourceMappingURL=agent-mcp-write.js.map