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,926 @@
1
+ import { cp, lstat, mkdir, mkdtemp, readFile, readlink, readdir, realpath, rename, rm, } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path';
4
+ import { isDeepStrictEqual } from 'node:util';
5
+ import { AGENTS, PROJECT_SKILL_DIRS, assertRelativePath, assertSkillName, baselinePath, classifyCollectionMatch, collectionPaths, discoverSkills, exists, isExactSymlink, metadataPath, parseGitSource, pathPresent, readMetadata, readSkill, readState, validateSkillTree, writeMetadata, writeState, ensureCollection, normalizeGitRepositoryIdentity, } from './core.js';
6
+ import { createCollectionSkill, setSkillPrivate, installCollectionSkill, removeFromCollection, materializeSkillReferences, removeSkillLocations, unbindCollectedSkillSource, } from './collection-write.js';
7
+ import { installSkillTarget } from './install-target.js';
8
+ import { canonicalizePath, resolveCrossAgentInstallPlan, } from './cross-agent-install.js';
9
+ import { inspectGitSource, readSkills, readSkillLocations, validateAgents, } from './agent-read.js';
10
+ import { executeWrites, conflictItem, requireAuthorization, } from './agent-write.js';
11
+ import { OperationFailure, operationError, } from './operation.js';
12
+ import { renameTagInList, writeTagRenameBatch, normalizeNewTagName, } from './tags.js';
13
+ import { updateGitSkill, detectRenamedSkillPath, readPrivateSkillNames } from './git.js';
14
+ import { domainNotify } from './errors.js';
15
+ function strings(options, key) {
16
+ return [...new Set(options[key] ?? [])];
17
+ }
18
+ export function metadataPatch(before, options) {
19
+ let tags = before.tags;
20
+ if (options.tags !== undefined) {
21
+ if (options['add-tag'] || options['remove-tag'])
22
+ throw new OperationFailure('usage.invalidArguments', '--tags cannot be combined with incremental tags.');
23
+ try {
24
+ tags = JSON.parse(options.tags);
25
+ }
26
+ catch {
27
+ throw new OperationFailure('usage.invalidArguments', 'Tags must be a JSON array.');
28
+ }
29
+ if (!Array.isArray(tags) || tags.some((tag) => typeof tag !== 'string'))
30
+ throw new OperationFailure('usage.invalidArguments', 'Tags must be an array of strings.');
31
+ }
32
+ const add = strings(options, 'add-tag');
33
+ const remove = strings(options, 'remove-tag');
34
+ if (add.some((tag) => remove.includes(tag)))
35
+ throw new OperationFailure('usage.invalidArguments', 'The same tag cannot be added and removed.');
36
+ tags = [...new Set([...tags, ...add].map(normalizeNewTagName))].filter((tag) => !remove.includes(tag));
37
+ return {
38
+ tags,
39
+ note: options.note ?? before.note,
40
+ ...(options.description !== undefined
41
+ ? { description: options.description }
42
+ : {}),
43
+ };
44
+ }
45
+ export async function sameTree(left, right) {
46
+ const a = await lstat(left);
47
+ const b = await lstat(right);
48
+ if (a.isSymbolicLink() || b.isSymbolicLink())
49
+ return (a.isSymbolicLink() &&
50
+ b.isSymbolicLink() &&
51
+ (await readlink(left)) === (await readlink(right)));
52
+ if (a.isDirectory() !== b.isDirectory())
53
+ return false;
54
+ if (!a.isDirectory())
55
+ return (a.isFile() &&
56
+ b.isFile() &&
57
+ (await readFile(left)).equals(await readFile(right)));
58
+ const names = (await readdir(left)).sort();
59
+ if (!isDeepStrictEqual(names, (await readdir(right)).sort()))
60
+ return false;
61
+ for (const name of names)
62
+ if (!(await sameTree(join(left, name), join(right, name))))
63
+ return false;
64
+ return true;
65
+ }
66
+ /** One planner owns target identity, unchanged content, replacement and recovery. */
67
+ export async function planSkillTargets(inputs) {
68
+ const plans = new Map();
69
+ const sources = new Map();
70
+ for (const input of inputs) {
71
+ const { name, source, target, copy } = input;
72
+ const physicalSource = await canonicalizePath(source);
73
+ const key = join(await canonicalizePath(dirname(target)), basename(target));
74
+ if (sources.has(key) && sources.get(key) !== physicalSource)
75
+ throw new OperationFailure('usage.ambiguousSelection', 'Multiple sources resolve to the same installation target.', { target });
76
+ const previous = plans.get(key);
77
+ if (previous) {
78
+ previous.item.agents = [
79
+ ...new Set([
80
+ ...previous.item.agents,
81
+ ...(input.agents ?? []),
82
+ ]),
83
+ ];
84
+ continue;
85
+ }
86
+ const exact = await isExactSymlink(target, source);
87
+ const physicalTarget = await canonicalizePath(target);
88
+ if ((physicalTarget === physicalSource &&
89
+ (input.rejectSelfReference || !exact)) ||
90
+ physicalTarget.startsWith(`${physicalSource}${sep}`))
91
+ throw new OperationFailure('usage.invalidLocation', 'The target points to or is inside the source itself.', { target });
92
+ let item = {
93
+ name,
94
+ target,
95
+ agents: input.agents ?? [],
96
+ scope: input.scope ?? null,
97
+ action: copy ? 'copy' : 'link',
98
+ status: 'planned',
99
+ };
100
+ if (exact && !copy)
101
+ item = { ...item, status: 'unchanged', reason: 'same-reference' };
102
+ else if (await pathPresent(target)) {
103
+ if (copy &&
104
+ !(await lstat(target)).isSymbolicLink() &&
105
+ (await sameTree(source, target)))
106
+ item = { ...item, status: 'unchanged', reason: 'same-content' };
107
+ else if (!input.replace)
108
+ item = conflictItem(item, 'conflict.targetExists', {
109
+ target,
110
+ requiredFlags: ['--replace'],
111
+ });
112
+ }
113
+ plans.set(key, {
114
+ item,
115
+ execute: () => installSkillTarget(name, source, target, copy, input.registerUsage),
116
+ });
117
+ sources.set(key, physicalSource);
118
+ }
119
+ return [...plans.values()];
120
+ }
121
+ function validateNames(names) {
122
+ for (const name of names) {
123
+ try {
124
+ if (assertSkillName(name) !== name)
125
+ throw new Error();
126
+ }
127
+ catch {
128
+ throw new OperationFailure('usage.invalidArguments', 'Invalid skill name.', { name });
129
+ }
130
+ }
131
+ return names;
132
+ }
133
+ async function matchesCreateTemplate(name, target) {
134
+ try {
135
+ if (!(await lstat(target)).isDirectory())
136
+ return false;
137
+ if (!(await pathPresent(metadataPath(name))))
138
+ return false;
139
+ if (!isDeepStrictEqual(await readMetadata(name), {
140
+ name,
141
+ description: '',
142
+ tags: [],
143
+ note: '',
144
+ source: { type: 'unknown' },
145
+ }))
146
+ return false;
147
+ const entries = await readdir(target);
148
+ return entries.length === 1 &&
149
+ entries[0] === 'SKILL.md' &&
150
+ (await lstat(join(target, 'SKILL.md'))).isFile() &&
151
+ (await readFile(join(target, 'SKILL.md'), 'utf8')) ===
152
+ `---\nname: ${name}\ndescription: \n---\n\n# ${name}\n\n`;
153
+ }
154
+ catch (error) {
155
+ if (['ENOENT', 'ENOTDIR'].includes(error.code ?? ''))
156
+ return false;
157
+ throw error;
158
+ }
159
+ }
160
+ async function requireSkills(names, all = false) {
161
+ const collection = await readSkills();
162
+ const selected = all
163
+ ? collection.items
164
+ : names.map((name) => {
165
+ const skill = collection.items.find((item) => item.name === name);
166
+ if (!skill) {
167
+ const issue = collection.issues.find((entry) => entry.path.endsWith(`/${name}`));
168
+ if (issue)
169
+ throw new OperationFailure('execution.readFailed', 'The selected skill in collection is unreadable.', { name, issue }, 1);
170
+ throw new OperationFailure('usage.selectionNotFound', 'The skill does not exist.', { name });
171
+ }
172
+ return skill;
173
+ });
174
+ return selected.map(({ name, description, tags, note, source }) => ({
175
+ name,
176
+ description,
177
+ tags,
178
+ note,
179
+ source,
180
+ }));
181
+ }
182
+ export async function executeSkillWrite(request) {
183
+ const { command, project, options, signal } = request;
184
+ const names = command === 'skill.tag.rename'
185
+ ? request.names
186
+ : [...new Set(request.names)];
187
+ const dryRun = options['dry-run'] === true;
188
+ const plans = [];
189
+ if (command === 'skill.import')
190
+ return importSkills(request);
191
+ if (command === 'skill.install')
192
+ return installSkills(request);
193
+ if (['skill.uninstall', 'skill.materialize'].includes(command))
194
+ return maintainLocations(request);
195
+ if (command === 'skill.tag.rename') {
196
+ const [from, to] = names;
197
+ if (names.length !== 2)
198
+ throw new OperationFailure('usage.invalidArguments', 'Two tag names are required.');
199
+ normalizeNewTagName(to);
200
+ const selected = await requireSkills([], true);
201
+ const changes = selected.flatMap((before) => {
202
+ const tags = renameTagInList(before.tags, from, to);
203
+ return tags ? [{ before, after: { ...before, tags } }] : [];
204
+ });
205
+ return executeWrites([
206
+ {
207
+ item: {
208
+ name: from,
209
+ action: 'rename-tag',
210
+ status: changes.length ? 'planned' : 'unchanged',
211
+ reason: 'same-value',
212
+ affectedNames: changes.map((change) => change.before.name),
213
+ },
214
+ execute: () => writeTagRenameBatch(changes, writeMetadata),
215
+ },
216
+ ], dryRun, true, command, signal);
217
+ }
218
+ validateNames(names);
219
+ if (options.all && names.length)
220
+ throw new OperationFailure('usage.invalidArguments', '--all and names are mutually exclusive.');
221
+ if (!names.length && !options.all)
222
+ throw new OperationFailure('usage.selectionRequired', 'Select at least one skill.');
223
+ if ([
224
+ 'skill.create',
225
+ 'skill.edit',
226
+ 'skill.source.bind',
227
+ 'skill.source.unbind',
228
+ ].includes(command) &&
229
+ names.length !== 1)
230
+ throw new OperationFailure('usage.invalidArguments', 'Exactly one skill name is required.');
231
+ if (['skill.remove', 'skill.source.unbind'].includes(command))
232
+ requireAuthorization(options.yes === true, dryRun, names);
233
+ const privateNames = options.private || options.public
234
+ ? new Set(await readPrivateSkillNames())
235
+ : new Set();
236
+ if (command === 'skill.create') {
237
+ const name = names[0];
238
+ const target = join(collectionPaths().skills, name);
239
+ const present = await pathPresent(target);
240
+ const privacyChanged = options.private === true && !privateNames.has(name);
241
+ let item = {
242
+ name,
243
+ path: target,
244
+ action: 'create',
245
+ ...(options.private ? { private: true } : {}),
246
+ status: 'planned',
247
+ };
248
+ if (present) {
249
+ item = await matchesCreateTemplate(name, target)
250
+ ? { ...item, status: privacyChanged ? 'planned' : 'unchanged', reason: 'same-template' }
251
+ : conflictItem(item, 'conflict.alreadyExists', { name });
252
+ }
253
+ plans.push({
254
+ item,
255
+ execute: async () => {
256
+ if (!present) {
257
+ await createCollectionSkill(name, { private: options.private === true });
258
+ return;
259
+ }
260
+ if (!(await matchesCreateTemplate(name, target)))
261
+ throw new OperationFailure('conflict.alreadyExists', 'The existing skill no longer matches the creation template.', { name }, 1);
262
+ if (privacyChanged)
263
+ await setSkillPrivate(collectionPaths().root, name, true);
264
+ },
265
+ });
266
+ }
267
+ else if (command === 'skill.adopt') {
268
+ const candidates = options.all
269
+ ? (await readdir(collectionPaths().skills, {
270
+ withFileTypes: true,
271
+ }).catch(() => []))
272
+ .filter((entry) => entry.isDirectory())
273
+ .map((entry) => entry.name)
274
+ .sort()
275
+ : names;
276
+ for (const name of candidates) {
277
+ const skill = await readSkill(join(collectionPaths().skills, name));
278
+ if (skill.name !== name)
279
+ throw new OperationFailure('source.invalidSkill', 'Skill directory and name disagree.', { name }, 1);
280
+ const present = await pathPresent(metadataPath(name));
281
+ const privacyChanged = options.private === true && !privateNames.has(name);
282
+ plans.push({
283
+ item: {
284
+ name,
285
+ action: 'adopt',
286
+ ...(options.private ? { private: true } : {}),
287
+ status: present && !privacyChanged ? 'unchanged' : 'planned',
288
+ reason: 'metadata-present',
289
+ },
290
+ execute: async () => {
291
+ if (privacyChanged)
292
+ await setSkillPrivate(collectionPaths().root, name, true);
293
+ if (!present)
294
+ await writeMetadata({
295
+ name,
296
+ description: skill.description,
297
+ tags: [],
298
+ note: '',
299
+ source: { type: 'unknown' },
300
+ });
301
+ },
302
+ });
303
+ }
304
+ }
305
+ else if (command === 'skill.remove') {
306
+ const state = await readState();
307
+ for (const name of names) {
308
+ const target = join(collectionPaths().skills, name);
309
+ if (await pathPresent(target)) {
310
+ const skill = await readSkill(target);
311
+ if (skill.name !== name || (await lstat(target)).isSymbolicLink())
312
+ throw new OperationFailure('usage.invalidLocation', 'The collected skill directory is invalid.', { name, path: target });
313
+ }
314
+ const links = state.links.filter((link) => link.skill === name);
315
+ const origin = links.find((link) => link.kind === 'origin');
316
+ const restore = origin && (await isExactSymlink(origin.path, target))
317
+ ? origin.path
318
+ : null;
319
+ const usage = [];
320
+ for (const link of links.filter((link) => link.kind === 'usage'))
321
+ if (await isExactSymlink(link.path, target))
322
+ usage.push(link.path);
323
+ plans.push({
324
+ item: {
325
+ name,
326
+ action: 'remove',
327
+ status: (await pathPresent(target)) ? 'planned' : 'unchanged',
328
+ reason: 'absent',
329
+ restoredOrigin: restore,
330
+ removedUsagePaths: usage,
331
+ requiredFlags: ['--yes'],
332
+ },
333
+ execute: () => removeFromCollection(name, true, true),
334
+ });
335
+ }
336
+ }
337
+ else if (command === 'skill.update')
338
+ return updateSkills(request);
339
+ else {
340
+ const selected = await requireSkills(names);
341
+ for (const before of selected) {
342
+ if (command === 'skill.edit') {
343
+ if (options.private && options.public)
344
+ throw new OperationFailure('usage.invalidArguments', '--private and --public are mutually exclusive.');
345
+ if (!['tags', 'add-tag', 'remove-tag', 'note', 'private', 'public'].some((key) => options[key] !== undefined))
346
+ throw new OperationFailure('usage.invalidArguments', 'At least one metadata field is required.');
347
+ const after = {
348
+ ...before,
349
+ ...metadataPatch(before, options),
350
+ };
351
+ const privacyChanged = (options.private === true || options.public === true) &&
352
+ privateNames.has(before.name) !== (options.private === true);
353
+ const metadataChanged = !isDeepStrictEqual(before, after);
354
+ plans.push({
355
+ item: {
356
+ name: before.name,
357
+ action: 'edit',
358
+ ...(options.private || options.public ? { private: options.private === true } : {}),
359
+ status: !privacyChanged && !metadataChanged ? 'unchanged' : 'planned',
360
+ reason: 'same-value',
361
+ },
362
+ execute: async () => {
363
+ if (privacyChanged)
364
+ await setSkillPrivate(collectionPaths().root, before.name, options.private === true);
365
+ if (metadataChanged)
366
+ await writeMetadata(after);
367
+ },
368
+ });
369
+ }
370
+ else if (command === 'skill.source.unbind') {
371
+ if (!['git', 'unknown'].includes(before.source.type))
372
+ throw new OperationFailure('usage.unsupportedCapability', 'Only a Git source can be unbound.', { name: before.name });
373
+ plans.push({
374
+ item: {
375
+ name: before.name,
376
+ action: 'unbind',
377
+ status: before.source.type === 'unknown' ? 'unchanged' : 'planned',
378
+ reason: 'already-unbound',
379
+ baseline: baselinePath(before.name),
380
+ clearsConflicts: (await readState()).conflicts.filter((conflict) => conflict.type === 'source' && conflict.skill === before.name),
381
+ requiredFlags: ['--yes'],
382
+ },
383
+ execute: () => unbindCollectedSkillSource(before.name),
384
+ });
385
+ }
386
+ else if (command === 'skill.source.bind') {
387
+ if (typeof options.git !== 'string' || typeof options.path !== 'string')
388
+ throw new OperationFailure('usage.invalidArguments', '--git and --path are required.');
389
+ const parsed = parseGitSource(options.git);
390
+ const source = {
391
+ type: 'git',
392
+ url: parsed.url,
393
+ path: assertRelativePath(options.path),
394
+ refType: /^[0-9a-f]{7,40}$/i.test(parsed.ref ?? '')
395
+ ? 'commit'
396
+ : 'branch',
397
+ ...(parsed.ref ? { ref: parsed.ref } : {}),
398
+ };
399
+ const same = before.source.type === 'git' &&
400
+ normalizeGitRepositoryIdentity(before.source.url ?? '') ===
401
+ normalizeGitRepositoryIdentity(source.url) &&
402
+ before.source.path === source.path &&
403
+ before.source.ref === source.ref &&
404
+ before.source.refType === source.refType;
405
+ let item = {
406
+ name: before.name,
407
+ action: 'bind',
408
+ status: same ? 'unchanged' : 'planned',
409
+ reason: 'same-source',
410
+ source,
411
+ baseline: baselinePath(before.name),
412
+ clearsConflicts: (await readState()).conflicts.filter((conflict) => conflict.type === 'source' && conflict.skill === before.name),
413
+ };
414
+ if (!same && before.source.type === 'git' && !options.replace)
415
+ item = conflictItem(item, 'conflict.sameName', {
416
+ existing: before.source,
417
+ incoming: source,
418
+ requiredFlags: ['--replace'],
419
+ });
420
+ plans.push({ item, execute: () => bindSource(before, source) });
421
+ }
422
+ else
423
+ throw new OperationFailure('usage.unknownCommand', 'Unknown skill operation.', { command });
424
+ }
425
+ }
426
+ return executeWrites(plans, dryRun, true, command, signal);
427
+ }
428
+ /** Both presenters pass reviewed imports through the same tree validation and executor. */
429
+ export async function executePreparedSkillImports(inputs, signal = new AbortController().signal) {
430
+ if (new Set(inputs.map((input) => input.name)).size !== inputs.length)
431
+ throw new OperationFailure('usage.ambiguousSelection', 'Duplicate skill names.');
432
+ const plans = [];
433
+ const privateNames = inputs.some((input) => input.private)
434
+ ? new Set(await readPrivateSkillNames())
435
+ : new Set();
436
+ for (const input of inputs) {
437
+ await validateSkillTree(input.sourceTree);
438
+ const target = join(collectionPaths().skills, input.name);
439
+ let item = {
440
+ name: input.name,
441
+ action: 'import',
442
+ status: 'planned',
443
+ source: input.metadata.source,
444
+ };
445
+ if (await pathPresent(target)) {
446
+ const match = await classifyCollectionMatch(await readMetadata(input.name), input.metadata);
447
+ if (match === 'same-source')
448
+ item = { ...item, status: input.private && !privateNames.has(input.name) ? 'planned' : 'unchanged', reason: 'same-source' };
449
+ else if (!input.allowReplace)
450
+ item = conflictItem(item, match === 'unverified-source'
451
+ ? 'conflict.sourceUnverified'
452
+ : 'conflict.sameName', { name: input.name, requiredFlags: ['--replace'] });
453
+ }
454
+ plans.push({
455
+ item,
456
+ execute: async () => {
457
+ await installCollectionSkill({ ...input, commit: false });
458
+ },
459
+ });
460
+ }
461
+ return executeWrites(plans, false, true, 'skill.import', signal);
462
+ }
463
+ export async function bindSource(before, source) {
464
+ const paths = await ensureCollection();
465
+ const transaction = await mkdtemp(join(paths.local, '.bind-'));
466
+ const baseline = baselinePath(before.name);
467
+ const backup = join(transaction, 'old');
468
+ const state = await readState();
469
+ let backedUp = false;
470
+ let baselineInstalled = false;
471
+ try {
472
+ await cp(join(paths.skills, before.name), join(transaction, 'new'), {
473
+ recursive: true,
474
+ });
475
+ if (await pathPresent(baseline)) {
476
+ await rename(baseline, backup);
477
+ backedUp = true;
478
+ }
479
+ await mkdir(dirname(baseline), { recursive: true });
480
+ await rename(join(transaction, 'new'), baseline);
481
+ baselineInstalled = true;
482
+ await writeMetadata({ ...before, source });
483
+ await writeState({
484
+ ...state,
485
+ conflicts: state.conflicts.filter((conflict) => conflict.type !== 'source' || conflict.skill !== before.name),
486
+ });
487
+ }
488
+ catch (error) {
489
+ try {
490
+ await writeMetadata(before);
491
+ await writeState(state);
492
+ if (baselineInstalled)
493
+ await rm(baseline, { recursive: true, force: true });
494
+ if (backedUp)
495
+ await rename(backup, baseline);
496
+ }
497
+ catch {
498
+ throw new OperationFailure('execution.rollbackFailed', 'The source binding could not be restored.', { name: before.name, recoveryPath: transaction }, 1, 'inspect-state');
499
+ }
500
+ throw error;
501
+ }
502
+ for (const path of [
503
+ ...state.conflicts.flatMap((conflict) => conflict.type === 'source' && conflict.skill === before.name
504
+ ? [conflict.path]
505
+ : []),
506
+ transaction,
507
+ ]) {
508
+ await rm(path, { recursive: true, force: true }).catch(() => domainNotify('domain.warnConflictCleanup'));
509
+ }
510
+ }
511
+ async function importSkills(request) {
512
+ const { options, project, signal, command } = request;
513
+ if (request.names.length)
514
+ throw new OperationFailure('usage.invalidArguments', 'Import takes options, not positional names.');
515
+ if (Boolean(options.git) === Boolean(options.local))
516
+ throw new OperationFailure('usage.invalidArguments', 'Choose --git or --local.');
517
+ const paths = strings(options, 'path');
518
+ if (Boolean(options.all) === Boolean(paths.length))
519
+ throw new OperationFailure('usage.selectionRequired', 'Select --all or one or more --path values.');
520
+ if (options['expect-commit'] &&
521
+ (!options.git ||
522
+ !/^[0-9a-f]{7,40}$/i.test(String(options['expect-commit']))))
523
+ throw new OperationFailure('usage.invalidArguments', '--expect-commit requires a Git source and a valid SHA.');
524
+ const cloned = options.git
525
+ ? await inspectGitSource(String(options.git), signal)
526
+ : undefined;
527
+ const root = cloned?.repository ?? resolve(project, String(options.local));
528
+ try {
529
+ if (cloned &&
530
+ options['expect-commit'] &&
531
+ !cloned.source
532
+ .commit.toLowerCase()
533
+ .startsWith(String(options['expect-commit']).toLowerCase()))
534
+ throw new OperationFailure('source.commitMismatch', 'The source commit differs from the expected commit.', {
535
+ expectedCommit: options['expect-commit'],
536
+ actualCommit: cloned.source.commit,
537
+ }, 1);
538
+ const candidates = await discoverSkills(root);
539
+ const selected = options.all
540
+ ? candidates.sort((a, b) => a.name.localeCompare(b.name, 'en'))
541
+ : paths.map((path) => {
542
+ const rel = assertRelativePath(path);
543
+ const candidate = candidates.find((skill) => (relative(root, skill.path) || '.') === rel);
544
+ if (!candidate)
545
+ throw new OperationFailure('usage.selectionNotFound', 'The source path was not discovered.', {
546
+ path,
547
+ candidates: candidates.map((skill) => ({
548
+ name: skill.name,
549
+ path: relative(root, skill.path) || '.',
550
+ })),
551
+ });
552
+ return candidate;
553
+ });
554
+ if (!selected.length)
555
+ throw new OperationFailure('usage.selectionNotFound', 'No skills were found.', { root: cloned ? null : root });
556
+ if (new Set(selected.map((skill) => skill.name)).size !== selected.length)
557
+ throw new OperationFailure('usage.ambiguousSelection', 'The selection contains duplicate skill names.');
558
+ const plans = [];
559
+ const privateNames = options.private
560
+ ? new Set(await readPrivateSkillNames())
561
+ : new Set();
562
+ for (const skill of selected) {
563
+ const actual = await realpath(skill.path);
564
+ if (!cloned) {
565
+ const collectionRoot = await canonicalizePath(collectionPaths().root);
566
+ if (actual === collectionRoot ||
567
+ actual.startsWith(`${collectionRoot}${sep}`)) {
568
+ const metadata = await readMetadata(skill.name);
569
+ if (actual !==
570
+ (await canonicalizePath(join(collectionPaths().skills, skill.name))) ||
571
+ metadata.source.type !== 'local')
572
+ throw new OperationFailure('usage.invalidLocation', 'The local import source must be outside collection content.', { path: skill.path });
573
+ }
574
+ }
575
+ await validateSkillTree(actual);
576
+ const source = cloned
577
+ ? { ...cloned.source, path: relative(root, skill.path) || '.' }
578
+ : { type: 'local', path: actual };
579
+ const metadata = {
580
+ name: skill.name,
581
+ description: skill.description,
582
+ tags: strings(options, 'tag'),
583
+ note: '',
584
+ source,
585
+ };
586
+ const target = join(collectionPaths().skills, skill.name);
587
+ let item = {
588
+ name: skill.name,
589
+ action: 'import',
590
+ ...(options.private ? { private: true } : {}),
591
+ status: 'planned',
592
+ source,
593
+ collectionPath: target,
594
+ ...(!cloned
595
+ ? { originPath: actual, moved: true, originLink: actual }
596
+ : {}),
597
+ };
598
+ if (await pathPresent(target)) {
599
+ const current = await readMetadata(skill.name);
600
+ const match = await classifyCollectionMatch(current, metadata);
601
+ if (match === 'same-source')
602
+ item = {
603
+ ...item,
604
+ status: options.private && !privateNames.has(skill.name) ? 'planned' : 'unchanged',
605
+ reason: 'same-source',
606
+ source: current.source,
607
+ moved: false,
608
+ ...(!cloned
609
+ ? {
610
+ originPath: current.source.path,
611
+ originLink: current.source.path &&
612
+ await isExactSymlink(current.source.path, target)
613
+ ? current.source.path
614
+ : null,
615
+ }
616
+ : {}),
617
+ };
618
+ else if (!options.replace)
619
+ item = conflictItem(item, match === 'unverified-source'
620
+ ? 'conflict.sourceUnverified'
621
+ : 'conflict.sameName', {
622
+ existing: current.source,
623
+ incoming: source,
624
+ requiredFlags: ['--replace'],
625
+ });
626
+ else
627
+ item.action = 'replace';
628
+ }
629
+ plans.push({
630
+ item,
631
+ execute: async () => {
632
+ try {
633
+ if (options.private && (await pathPresent(target)) &&
634
+ await classifyCollectionMatch(await readMetadata(skill.name), metadata) === 'same-source') {
635
+ await setSkillPrivate(collectionPaths().root, skill.name, true);
636
+ return;
637
+ }
638
+ await installCollectionSkill({
639
+ name: skill.name,
640
+ sourceTree: actual,
641
+ metadata,
642
+ allowReplace: options.replace === true,
643
+ commit: false,
644
+ ...(options.private ? { private: true } : {}),
645
+ ...(!cloned
646
+ ? {
647
+ local: {
648
+ originPath: actual,
649
+ selectedPath: skill.path,
650
+ selectedWasSymlink: (await lstat(skill.path)).isSymbolicLink(),
651
+ },
652
+ }
653
+ : {}),
654
+ });
655
+ }
656
+ catch (error) {
657
+ item.restored = 'unknown';
658
+ throw error;
659
+ }
660
+ },
661
+ });
662
+ }
663
+ return await executeWrites(plans, options['dry-run'] === true, true, command, signal);
664
+ }
665
+ finally {
666
+ if (cloned)
667
+ await rm(cloned.temporary, { recursive: true, force: true });
668
+ }
669
+ }
670
+ async function installSkills(request) {
671
+ const { options, project, signal, command } = request;
672
+ const sources = strings(options, 'from-location');
673
+ if (Boolean(request.names.length) === Boolean(sources.length))
674
+ throw new OperationFailure('usage.selectionRequired', 'Select collection names or --from-location.');
675
+ const agents = strings(options, 'agent');
676
+ const scope = options.scope;
677
+ if (options.to
678
+ ? agents.length || scope
679
+ : !agents.length || !['project', 'global'].includes(String(scope)))
680
+ throw new OperationFailure('usage.invalidArguments', 'Choose --to or explicit --agent and --scope.');
681
+ if (sources.length && (options.to || options.copy))
682
+ throw new OperationFailure('usage.invalidArguments', 'Cross-Agent install does not accept --to or --copy.');
683
+ if (agents.length)
684
+ validateAgents(agents);
685
+ if (sources.some((path) => !path.startsWith('/')))
686
+ throw new OperationFailure('usage.invalidLocation', 'Source installation paths must be absolute.');
687
+ const selected = sources.length
688
+ ? await Promise.all(sources.map((path) => readSkill(resolve(project, path))))
689
+ : (await requireSkills(validateNames([...new Set(request.names)]))).map((skill) => ({
690
+ ...skill,
691
+ path: join(collectionPaths().skills, skill.name),
692
+ }));
693
+ for (const skill of selected)
694
+ await validateSkillTree(await realpath(skill.path));
695
+ const inputs = [];
696
+ const locations = sources.length
697
+ ? (await readSkillLocations(project, [], ['project', 'global'])).result
698
+ .items
699
+ : [];
700
+ for (const skill of selected) {
701
+ const cross = sources.length
702
+ ? await resolveCrossAgentInstallPlan(skill)
703
+ : undefined;
704
+ if (sources.length &&
705
+ (!cross ||
706
+ !locations.some((entry) => entry.path === skill.path &&
707
+ entry.scope === scope &&
708
+ entry.canInstallAcrossAgents)))
709
+ throw new OperationFailure('usage.invalidLocation', 'The source is not an installable Agent skill in the selected scope.', { path: skill.path });
710
+ const source = cross?.linkTarget ?? skill.path;
711
+ for (const agent of options.to ? ['custom'] : agents) {
712
+ const config = AGENTS[agent];
713
+ if (!options.to && scope === 'project' && !config?.project)
714
+ throw new OperationFailure('usage.unsupportedCapability', 'The Agent has no project skill directory.', { agent, scope });
715
+ const root = options.to
716
+ ? resolve(project, String(options.to))
717
+ : scope === 'global'
718
+ ? config.global(homedir())
719
+ : join(project, config.project);
720
+ const target = join(root, skill.name);
721
+ inputs.push({
722
+ name: skill.name,
723
+ source,
724
+ target,
725
+ agents: agent === 'custom' ? [] : [agent],
726
+ scope: options.to ? null : scope,
727
+ copy: options.copy === true,
728
+ registerUsage: cross?.registerUsage ?? options.copy !== true,
729
+ replace: options.replace === true,
730
+ rejectSelfReference: sources.length > 0,
731
+ });
732
+ }
733
+ }
734
+ return executeWrites(await planSkillTargets(inputs), options['dry-run'] === true, false, command, signal);
735
+ }
736
+ async function maintainLocations(request) {
737
+ const { names, options, project, signal, command } = request;
738
+ if (!names.length)
739
+ throw new OperationFailure('usage.selectionRequired', 'Select at least one installation path.');
740
+ const dryRun = options['dry-run'] === true;
741
+ if (command === 'skill.uninstall')
742
+ requireAuthorization(options.yes === true, dryRun, names);
743
+ if (names.some((path) => !path.startsWith('/')))
744
+ throw new OperationFailure('usage.invalidLocation', 'Installation paths must be absolute.');
745
+ const paths = [...new Set(names.map((path) => resolve(project, path)))];
746
+ const collection = resolve(collectionPaths().root);
747
+ const skills = [];
748
+ const items = [];
749
+ const broken = [];
750
+ for (const path of paths) {
751
+ const physicalParent = await canonicalizePath(dirname(path));
752
+ const physicalCollection = await canonicalizePath(collection);
753
+ if (path === collection ||
754
+ path.startsWith(`${collection}${sep}`) ||
755
+ physicalParent === physicalCollection ||
756
+ physicalParent.startsWith(`${physicalCollection}${sep}`))
757
+ throw new OperationFailure('usage.invalidLocation', 'Collection content cannot be maintained by path.', { path });
758
+ if (!(await pathPresent(path))) {
759
+ if (command === 'skill.materialize')
760
+ throw new OperationFailure('usage.selectionNotFound', 'The skill reference no longer exists.', { path });
761
+ items.push({
762
+ path,
763
+ action: 'uninstall',
764
+ status: 'unchanged',
765
+ reason: 'absent',
766
+ });
767
+ continue;
768
+ }
769
+ if ((await lstat(path)).isSymbolicLink() &&
770
+ !(await exists(path)) &&
771
+ command === 'skill.uninstall') {
772
+ const roots = [
773
+ ...PROJECT_SKILL_DIRS.map((root) => resolve(project, root)),
774
+ ...Object.values(AGENTS).map((config) => config.global(homedir())),
775
+ ];
776
+ if (!roots.includes(dirname(path)) &&
777
+ !(await readState()).links.some((link) => resolve(link.path) === path))
778
+ throw new OperationFailure('usage.invalidLocation', 'The broken link is not a known installation location.', { path });
779
+ broken.push(path);
780
+ items.push({ path, action: 'uninstall', status: 'planned' });
781
+ continue;
782
+ }
783
+ let skill;
784
+ try {
785
+ skill = await readSkill(path);
786
+ }
787
+ catch {
788
+ throw new OperationFailure('usage.invalidLocation', 'The selected path is not a valid skill location.', { path });
789
+ }
790
+ if (command === 'skill.materialize') {
791
+ const locations = await readSkillLocations(project, [], ['project']);
792
+ if (!locations.result.items.some((entry) => entry.path === path && entry.canMaterialize))
793
+ throw new OperationFailure('usage.invalidLocation', 'Only project skill references can be materialized.', { path });
794
+ }
795
+ skills.push(skill);
796
+ items.push({
797
+ path,
798
+ name: skill.name,
799
+ action: command.endsWith('materialize') ? 'materialize' : 'uninstall',
800
+ status: 'planned',
801
+ ...(command.endsWith('uninstall') ? { requiredFlags: ['--yes'] } : {}),
802
+ });
803
+ }
804
+ if (dryRun)
805
+ return { result: { items, git: { status: 'not-needed' }, plannedGit: [] } };
806
+ try {
807
+ if (signal.aborted)
808
+ throw new OperationFailure('execution.interrupted', 'The operation was interrupted.', {}, 130, 'inspect-state');
809
+ if (command === 'skill.materialize')
810
+ await materializeSkillReferences(skills, { signal });
811
+ else
812
+ await removeSkillLocations(skills, broken);
813
+ const result = {
814
+ items: items.map((item) => ({
815
+ ...item,
816
+ status: item.status === 'planned' ? 'committed' : item.status,
817
+ })),
818
+ git: { status: 'not-needed' },
819
+ };
820
+ return {
821
+ result,
822
+ ...(signal.aborted
823
+ ? {
824
+ error: {
825
+ code: 'execution.interrupted',
826
+ message: 'The operation was interrupted.',
827
+ details: {},
828
+ retry: 'inspect-state',
829
+ },
830
+ exitCode: 130,
831
+ partial: true,
832
+ }
833
+ : {}),
834
+ };
835
+ }
836
+ catch (error) {
837
+ const failure = signal.aborted
838
+ ? {
839
+ code: 'execution.interrupted',
840
+ message: 'The operation was interrupted.',
841
+ details: {},
842
+ retry: 'inspect-state',
843
+ }
844
+ : operationError(error, 'write');
845
+ return {
846
+ result: {
847
+ items: items.map((item) => item.status === 'planned'
848
+ ? { ...item, status: 'failed', error: failure, restored: 'unknown' }
849
+ : item),
850
+ git: { status: 'not-needed' },
851
+ },
852
+ error: failure,
853
+ exitCode: signal.aborted ? 130 : 1,
854
+ };
855
+ }
856
+ }
857
+ async function updateSkills(request) {
858
+ const { names, options, command, signal } = request;
859
+ if (Boolean(options['allow-delete']) !== Boolean(options.yes))
860
+ throw new OperationFailure('usage.invalidArguments', 'Deletion requires --allow-delete and --yes together.');
861
+ const selected = await requireSkills(names, options.all === true);
862
+ const plans = [];
863
+ const clones = [];
864
+ try {
865
+ const state = await readState();
866
+ for (const skill of selected) {
867
+ let cloned;
868
+ let item = {
869
+ name: skill.name,
870
+ action: 'update',
871
+ status: 'planned',
872
+ oldCommit: skill.source.commit ?? null,
873
+ };
874
+ if (skill.source.type !== 'git')
875
+ item = { ...item, status: 'unchanged', reason: 'unmanaged' };
876
+ else if (skill.source.refType !== 'branch')
877
+ item = { ...item, status: 'unchanged', reason: 'pinned' };
878
+ else if (state.conflicts.some((conflict) => conflict.type === 'source' && conflict.skill === skill.name))
879
+ item = conflictItem(item, 'conflict.sourceMerge', {
880
+ name: skill.name,
881
+ conflicts: state.conflicts.filter((conflict) => conflict.type === 'source' && conflict.skill === skill.name),
882
+ });
883
+ else {
884
+ const source = await inspectGitSource(`${skill.source.url}${skill.source.ref ? `#${skill.source.ref}` : ''}`, signal, true);
885
+ cloned = source;
886
+ clones.push(source.temporary);
887
+ item.newCommit = source.source.commit;
888
+ if (source.source.commit === skill.source.commit)
889
+ item = { ...item, status: 'unchanged', reason: 'same-commit' };
890
+ else if (!(await exists(join(source.repository, skill.source.commit
891
+ ? await detectRenamedSkillPath(source.repository, skill.source.commit, source.source.commit, skill.source.path ?? '.')
892
+ : (skill.source.path ?? '.'), 'SKILL.md')))) {
893
+ if (!options['allow-delete'])
894
+ item = conflictItem(item, 'conflict.upstreamDeleted', {
895
+ name: skill.name,
896
+ requiredFlags: ['--allow-delete', '--yes'],
897
+ });
898
+ else
899
+ item.action = 'remove';
900
+ }
901
+ else {
902
+ const path = skill.source.commit
903
+ ? await detectRenamedSkillPath(source.repository, skill.source.commit, source.source.commit, skill.source.path ?? '.')
904
+ : (skill.source.path ?? '.');
905
+ await readSkill(join(source.repository, path));
906
+ await validateSkillTree(join(source.repository, path));
907
+ }
908
+ }
909
+ plans.push({
910
+ item,
911
+ execute: async () => {
912
+ const result = await updateGitSkill({ ...skill, path: join(collectionPaths().skills, skill.name) }, options['allow-delete'] === true, { quietDelete: true, ...(cloned ? { clone: cloned } : {}) });
913
+ item.updateStatus = result;
914
+ if (result === 'conflict')
915
+ throw new OperationFailure('conflict.sourceMerge', 'The source update needs conflict resolution.', { name: skill.name, conflicts: (await readState()).conflicts }, 1, 'inspect-state');
916
+ },
917
+ });
918
+ }
919
+ return await executeWrites(plans, options['dry-run'] === true, true, command, signal);
920
+ }
921
+ finally {
922
+ for (const path of clones)
923
+ await rm(path, { recursive: true, force: true });
924
+ }
925
+ }
926
+ //# sourceMappingURL=agent-skill-write.js.map