iskills 0.2.46 → 0.2.48

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 (128) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +4 -6
  3. package/README.zh-CN.md +3 -5
  4. package/bin/iskills.js +3 -2
  5. package/dist/src/cli.js +9 -5
  6. package/dist/src/cli.js.map +1 -1
  7. package/dist/src/commands/browser-actions.d.ts +2 -0
  8. package/dist/src/commands/browser-actions.js +123 -29
  9. package/dist/src/commands/browser-actions.js.map +1 -1
  10. package/dist/src/commands/config.js +3 -2
  11. package/dist/src/commands/config.js.map +1 -1
  12. package/dist/src/commands/create.js +10 -7
  13. package/dist/src/commands/create.js.map +1 -1
  14. package/dist/src/commands/index.js +2 -1
  15. package/dist/src/commands/index.js.map +1 -1
  16. package/dist/src/commands/library.d.ts +46 -12
  17. package/dist/src/commands/library.js +362 -213
  18. package/dist/src/commands/library.js.map +1 -1
  19. package/dist/src/commands/search.js +13 -40
  20. package/dist/src/commands/search.js.map +1 -1
  21. package/dist/src/domain/collection-write.d.ts +53 -2
  22. package/dist/src/domain/collection-write.js +287 -63
  23. package/dist/src/domain/collection-write.js.map +1 -1
  24. package/dist/src/domain/core.d.ts +46 -5
  25. package/dist/src/domain/core.js +161 -60
  26. package/dist/src/domain/core.js.map +1 -1
  27. package/dist/src/domain/cross-agent-install.d.ts +32 -0
  28. package/dist/src/domain/cross-agent-install.js +147 -0
  29. package/dist/src/domain/cross-agent-install.js.map +1 -0
  30. package/dist/src/domain/errors.d.ts +20 -0
  31. package/dist/src/domain/errors.js +31 -0
  32. package/dist/src/domain/errors.js.map +1 -0
  33. package/dist/src/domain/git.js +15 -15
  34. package/dist/src/domain/git.js.map +1 -1
  35. package/dist/src/i18n/en.js +32 -28
  36. package/dist/src/i18n/en.js.map +1 -1
  37. package/dist/src/i18n/index.d.ts +7 -0
  38. package/dist/src/i18n/index.js +35 -0
  39. package/dist/src/i18n/index.js.map +1 -1
  40. package/dist/src/i18n/zh.d.ts +32 -27
  41. package/dist/src/i18n/zh.js +32 -28
  42. package/dist/src/i18n/zh.js.map +1 -1
  43. package/dist/src/ui/browser/browse-capabilities.d.ts +26 -0
  44. package/dist/src/ui/browser/browse-capabilities.js +130 -0
  45. package/dist/src/ui/browser/browse-capabilities.js.map +1 -0
  46. package/dist/src/ui/browser/browser.js +94 -34
  47. package/dist/src/ui/browser/browser.js.map +1 -1
  48. package/dist/src/ui/browser/detail.js +1 -2
  49. package/dist/src/ui/browser/detail.js.map +1 -1
  50. package/dist/src/ui/browser/footer.js +26 -105
  51. package/dist/src/ui/browser/footer.js.map +1 -1
  52. package/dist/src/ui/browser/format.d.ts +0 -17
  53. package/dist/src/ui/browser/format.js +11 -97
  54. package/dist/src/ui/browser/format.js.map +1 -1
  55. package/dist/src/ui/browser/index.js +34 -3
  56. package/dist/src/ui/browser/index.js.map +1 -1
  57. package/dist/src/ui/browser/shortcut-help.js +1 -3
  58. package/dist/src/ui/browser/shortcut-help.js.map +1 -1
  59. package/dist/src/ui/browser/store.d.ts +4 -0
  60. package/dist/src/ui/browser/store.js +2 -0
  61. package/dist/src/ui/browser/store.js.map +1 -1
  62. package/dist/src/ui/browser/types.d.ts +6 -0
  63. package/dist/src/ui/components/framed-panel.d.ts +6 -1
  64. package/dist/src/ui/components/framed-panel.js +5 -3
  65. package/dist/src/ui/components/framed-panel.js.map +1 -1
  66. package/dist/src/ui/components/mouse/index.d.ts +1 -1
  67. package/dist/src/ui/components/mouse/index.js +1 -1
  68. package/dist/src/ui/components/mouse/index.js.map +1 -1
  69. package/dist/src/ui/components/mouse/parse.d.ts +0 -7
  70. package/dist/src/ui/components/mouse/parse.js +0 -41
  71. package/dist/src/ui/components/mouse/parse.js.map +1 -1
  72. package/dist/src/ui/components/multi-select.js +3 -11
  73. package/dist/src/ui/components/multi-select.js.map +1 -1
  74. package/dist/src/ui/components/options.d.ts +2 -0
  75. package/dist/src/ui/components/options.js +9 -0
  76. package/dist/src/ui/components/options.js.map +1 -1
  77. package/dist/src/ui/components/select.js +1 -2
  78. package/dist/src/ui/components/select.js.map +1 -1
  79. package/dist/src/ui/components/tag-editor.js +1 -1
  80. package/dist/src/ui/components/tag-editor.js.map +1 -1
  81. package/dist/src/ui/components/termcn.d.ts +1 -5
  82. package/dist/src/ui/components/termcn.js +1 -4
  83. package/dist/src/ui/components/termcn.js.map +1 -1
  84. package/dist/src/ui/config/settings.js +1 -1
  85. package/dist/src/ui/config/settings.js.map +1 -1
  86. package/dist/src/ui/footer/resolve-footer.js +6 -1
  87. package/dist/src/ui/footer/resolve-footer.js.map +1 -1
  88. package/dist/src/ui/footer/types.d.ts +6 -0
  89. package/dist/src/ui/import/review.js +2 -6
  90. package/dist/src/ui/import/review.js.map +1 -1
  91. package/dist/src/ui/import/skill-select.js +6 -26
  92. package/dist/src/ui/import/skill-select.js.map +1 -1
  93. package/dist/src/ui/install/review.js +12 -14
  94. package/dist/src/ui/install/review.js.map +1 -1
  95. package/dist/src/ui/overlay/bridge.d.ts +4 -1
  96. package/dist/src/ui/overlay/bridge.js +20 -0
  97. package/dist/src/ui/overlay/bridge.js.map +1 -1
  98. package/dist/src/ui/overlay/host.js +4 -0
  99. package/dist/src/ui/overlay/host.js.map +1 -1
  100. package/dist/src/ui/prompts/present.js +63 -0
  101. package/dist/src/ui/prompts/present.js.map +1 -1
  102. package/dist/src/ui/search/index.js +6 -5
  103. package/dist/src/ui/search/index.js.map +1 -1
  104. package/dist/src/ui/shell/app-shell.d.ts +1 -1
  105. package/dist/src/ui/shell/app-shell.js +1 -1
  106. package/dist/src/ui/shell/run.d.ts +0 -11
  107. package/dist/src/ui/shell/run.js +0 -43
  108. package/dist/src/ui/shell/run.js.map +1 -1
  109. package/dist/src/ui/skill-labels.d.ts +1 -0
  110. package/dist/src/ui/skill-labels.js +9 -8
  111. package/dist/src/ui/skill-labels.js.map +1 -1
  112. package/dist/src/ui/tui/hooks.d.ts +1 -13
  113. package/dist/src/ui/tui/hooks.js +1 -11
  114. package/dist/src/ui/tui/hooks.js.map +1 -1
  115. package/dist/src/ui/tui/index.d.ts +1 -1
  116. package/dist/src/ui/tui/index.js +1 -1
  117. package/dist/src/ui/tui/index.js.map +1 -1
  118. package/package.json +8 -10
  119. package/bin/patch-react-reconciler.mjs +0 -71
  120. package/dist/src/ui/components/confirm.d.ts +0 -6
  121. package/dist/src/ui/components/confirm.js +0 -22
  122. package/dist/src/ui/components/confirm.js.map +0 -1
  123. package/dist/src/ui/components/link.d.ts +0 -7
  124. package/dist/src/ui/components/link.js +0 -17
  125. package/dist/src/ui/components/link.js.map +0 -1
  126. package/dist/src/ui/components/modal.d.ts +0 -16
  127. package/dist/src/ui/components/modal.js +0 -58
  128. package/dist/src/ui/components/modal.js.map +0 -1
@@ -1,13 +1,24 @@
1
- import { cp, lstat, mkdir, mkdtemp, realpath, rm, symlink } from 'node:fs/promises';
2
- import { homedir } from 'node:os';
3
- import { join, relative, resolve, sep } from 'node:path';
1
+ import { cp, lstat, mkdir, realpath, rename, rm, symlink } from 'node:fs/promises';
2
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path';
4
3
  import { parseArgs } from 'node:util';
5
- import { noPresentAgentsError, PROJECT_SKILL_DIRS, agentGlobalPath, agentProjectPath, assertRelativePath, assertSkillName, baselinePath, classifyCollectionMatch, collectionPaths, commitCollection, discoverSkills, ensureCollection, exists, getAgent, isExactSymlink, isGitSource, listCollection, listPresentAgents, moveDirectory, pathPresent, provenanceFromKnownLocks, readMetadata, sameGitIdentity, sanitizeTerminal, validateSkillTree, writeMetadata, } from '../domain/core.js';
6
- import { registerCollectionLinks, replaceCollectionSkill, } from '../domain/collection-write.js';
4
+ import { noPresentAgentsError, PROJECT_SKILL_DIRS, agentGlobalPath, agentProjectPath, assertRelativePath, classifyCollectionMatch, collectionPaths, commitCollection, discoverSkills, exists, isExactSymlink, isGitSource, listCollection, listGlobalGroups, listPresentAgents, pathPresent, readMetadata, readState, resolveIncomingProvenance, sanitizeTerminal, writeState, } from '../domain/core.js';
5
+ import { installCollectionSkill, registerCollectionLinks, } from '../domain/collection-write.js';
6
+ import { canonicalizePath, isPhysicalSelfInstall, resolveCrossAgentInstallPlan, } from '../domain/cross-agent-install.js';
7
+ import { DomainError } from '../domain/errors.js';
7
8
  import { matchesSkill } from '../domain/skill-query.js';
8
9
  import { cloneGitSource } from '../domain/git.js';
9
10
  import { collectionMatchLabels } from '../ui/collection-match.js';
10
11
  import { t } from '../i18n/index.js';
12
+ export function formatSkillIdentity(meta) {
13
+ const source = meta.source;
14
+ // Local / path-only: show the path once (do not also append as /suffix).
15
+ if (source.type === 'local' || (!source.url && !source.id && source.path)) {
16
+ return sanitizeTerminal(source.path || source.type || 'local');
17
+ }
18
+ const base = source.url || source.id || source.type;
19
+ const path = source.path && source.path !== '.' ? `/${source.path}` : '';
20
+ return sanitizeTerminal(`${String(base).replace(/\/$/, '')}${path}`);
21
+ }
11
22
  function present() {
12
23
  return import('../ui/prompts/present.js');
13
24
  }
@@ -19,235 +30,243 @@ function gitSkillDisplayPath(skill, gitContext) {
19
30
  : '';
20
31
  return `${sanitizeTerminal(gitContext.source.url)}${sanitizeTerminal(ref)} · ${sanitizeTerminal(sourcePath)}${status}`;
21
32
  }
22
- function gitSkillMetadata(skill, gitContext, tags = []) {
33
+ async function gitSkillMetadata(skill, gitContext, tags = []) {
23
34
  return {
24
35
  name: skill.name,
25
36
  description: skill.description,
26
37
  tags,
27
38
  note: '',
28
- source: {
29
- ...gitContext.source,
30
- path: assertRelativePath(relative(gitContext.repository, skill.path).split(sep).join('/')),
31
- },
39
+ source: await resolveIncomingProvenance(skill, gitContext),
32
40
  };
33
41
  }
34
- function annotateGitCollectionStatus(skills, gitContext, collection) {
35
- return skills.map((skill) => {
42
+ async function annotateGitCollectionStatus(skills, gitContext, collection) {
43
+ const out = [];
44
+ for (const skill of skills) {
36
45
  const sameName = collection.find((collected) => collected.name.toLowerCase() === skill.name.toLowerCase());
37
- if (!sameName)
38
- return skill;
39
- return {
46
+ if (!sameName) {
47
+ out.push(skill);
48
+ continue;
49
+ }
50
+ out.push({
40
51
  ...skill,
41
- collectionStatus: classifyCollectionMatch(sameName, gitSkillMetadata(skill, gitContext)),
42
- };
43
- });
52
+ collectionStatus: await classifyCollectionMatch(sameName, await gitSkillMetadata(skill, gitContext)),
53
+ });
54
+ }
55
+ return out;
44
56
  }
57
+ /** Write only — caller owns post-write commitCollection (and success messaging). */
45
58
  async function importLocalSkill(skill, allowReplace, tags = []) {
46
- const paths = collectionPaths();
47
59
  const selectedPath = resolve(skill.path);
48
60
  const selectedStats = await lstat(selectedPath);
49
- const source = selectedStats.isSymbolicLink() ? await realpath(selectedPath) : selectedPath;
50
- const target = join(paths.skills, assertSkillName(skill.name));
51
- if (source === target)
52
- return false;
53
- const provenance = await provenanceFromKnownLocks(skill);
54
- await validateSkillTree(source);
55
- if (await pathPresent(target)) {
56
- if (!allowReplace) {
57
- throw new Error(t('cmd.sameNameExistsReplace', { name: skill.name }));
58
- }
59
- await ensureCollection();
60
- const transaction = await mkdtemp(join(paths.local, `.prepare-${skill.name}-`));
61
- const staged = join(transaction, 'tree');
62
- try {
63
- await cp(source, staged, { recursive: true, errorOnExist: true });
64
- await replaceCollectionSkill({
65
- name: skill.name,
66
- staged,
67
- metadata: {
68
- name: skill.name,
69
- description: skill.description,
70
- tags,
71
- note: '',
72
- source: provenance,
73
- },
74
- local: {
75
- source,
76
- selectedPath,
77
- selectedWasSymlink: selectedStats.isSymbolicLink(),
78
- },
79
- });
80
- }
81
- finally {
82
- await rm(transaction, { recursive: true, force: true });
83
- }
84
- return true;
85
- }
86
- await ensureCollection();
87
- await moveDirectory(source, target);
88
- try {
89
- await symlink(target, source, 'dir');
90
- }
91
- catch (error) {
92
- await moveDirectory(target, source);
93
- throw error;
94
- }
95
- await writeMetadata({
61
+ const originPath = selectedStats.isSymbolicLink() ? await realpath(selectedPath) : selectedPath;
62
+ const provenance = await resolveIncomingProvenance(skill);
63
+ const metadata = {
96
64
  name: skill.name,
97
65
  description: skill.description,
98
66
  tags,
99
67
  note: '',
100
68
  source: provenance,
69
+ };
70
+ const result = await installCollectionSkill({
71
+ name: skill.name,
72
+ sourceTree: originPath,
73
+ metadata,
74
+ allowReplace,
75
+ local: {
76
+ originPath,
77
+ selectedPath,
78
+ selectedWasSymlink: selectedStats.isSymbolicLink(),
79
+ },
80
+ commit: false,
81
+ commitMessage: `import ${skill.name}`,
101
82
  });
102
- if (provenance.type === 'git' && !provenance.commit) {
103
- const baseline = baselinePath(skill.name);
104
- await rm(baseline, { recursive: true, force: true });
105
- await cp(target, baseline, { recursive: true });
106
- }
107
- const links = [{ skill: skill.name, path: source, kind: 'origin' }];
108
- if (selectedStats.isSymbolicLink()) {
109
- links.push({ skill: skill.name, path: selectedPath, kind: 'dependent' });
110
- }
111
- await registerCollectionLinks(links);
112
- return true;
83
+ return result === 'installed' || result === 'installed-uncommitted';
113
84
  }
85
+ /** Write only — caller owns post-write commitCollection (and success messaging). */
114
86
  async function importRemoteSkill(skill, gitContext, allowReplace, tags = []) {
115
- const paths = collectionPaths();
116
- const target = join(paths.skills, assertSkillName(skill.name));
117
- const metadata = gitSkillMetadata(skill, gitContext, tags);
118
- await validateSkillTree(skill.path);
119
- if (await pathPresent(target)) {
120
- const current = await readMetadata(skill.name);
121
- if (sameGitIdentity(current, metadata))
122
- return false;
123
- if (!allowReplace) {
124
- throw new Error(t('cmd.sameNameExistsReplace', { name: skill.name }));
125
- }
126
- await ensureCollection();
127
- const transaction = await mkdtemp(join(paths.local, `.prepare-${skill.name}-`));
128
- const staged = join(transaction, 'tree');
129
- try {
130
- await cp(skill.path, staged, { recursive: true, errorOnExist: true });
131
- await replaceCollectionSkill({
132
- name: skill.name,
133
- staged,
134
- metadata,
135
- });
136
- }
137
- finally {
138
- await rm(transaction, { recursive: true, force: true });
139
- }
140
- return true;
141
- }
142
- await ensureCollection();
143
- await cp(skill.path, target, { recursive: true, errorOnExist: true });
144
- await writeMetadata(metadata);
145
- return true;
87
+ const metadata = await gitSkillMetadata(skill, gitContext, tags);
88
+ const result = await installCollectionSkill({
89
+ name: skill.name,
90
+ sourceTree: skill.path,
91
+ metadata,
92
+ allowReplace,
93
+ commit: false,
94
+ commitMessage: `import ${skill.name}`,
95
+ });
96
+ return result === 'installed' || result === 'installed-uncommitted';
146
97
  }
147
98
  export async function importRemoteSkillToCollection(source, skillName, options = {}) {
148
99
  const gitContext = await cloneGitSource(source);
149
100
  try {
150
101
  const found = (await discoverSkills(gitContext.repository)).filter((skill) => skill.name.toLowerCase() === skillName.toLowerCase());
151
102
  if (!found.length)
152
- throw new Error(t('cmd.skillMissingInSource', { name: skillName }));
103
+ throw new DomainError('cmd.skillMissingInSource', { name: skillName });
153
104
  if (found.length > 1)
154
- throw new Error(t('cmd.skillDuplicateInSource', { name: skillName }));
105
+ throw new DomainError('cmd.skillDuplicateInSource', { name: skillName });
155
106
  const skill = found[0];
156
- const incoming = gitSkillMetadata(skill, gitContext);
107
+ const incoming = await gitSkillMetadata(skill, gitContext);
157
108
  const target = join(collectionPaths().skills, skill.name);
158
109
  const replacing = await pathPresent(target);
159
110
  if (replacing) {
160
111
  const current = await readMetadata(skill.name);
161
- if (sameGitIdentity(current, incoming)) {
112
+ const match = await classifyCollectionMatch(current, incoming);
113
+ if (match === 'same-source') {
162
114
  return { name: skill.name, status: 'unchanged' };
163
115
  }
164
116
  if (!options.replace) {
165
117
  if (!options.confirmReplace) {
166
- throw new Error(t('cmd.conflictingSourceExists', { name: skill.name }));
118
+ throw new DomainError(match === 'unverified-source'
119
+ ? 'cmd.unverifiedSourceExists'
120
+ : 'cmd.conflictingSourceExists', { name: skill.name });
167
121
  }
168
- if (!(await options.confirmReplace(current, incoming))) {
122
+ const allowed = await options.confirmReplace([
123
+ { name: skill.name, match, current, incoming },
124
+ ]);
125
+ if (!allowed) {
169
126
  return { name: skill.name, status: 'cancelled' };
170
127
  }
171
128
  }
172
129
  }
173
- await importRemoteSkill(skill, gitContext, replacing, options.tags ?? []);
174
- if (!replacing)
175
- await commitCollection(`import ${skill.name}`);
130
+ const wrote = await importRemoteSkill(skill, gitContext, replacing, options.tags ?? []);
131
+ if (!wrote)
132
+ return { name: skill.name, status: 'unchanged' };
133
+ // Soft-fail commit: warn already emitted; distinct from user cancel.
134
+ if (!(await commitCollection(`import ${skill.name}`))) {
135
+ return { name: skill.name, status: 'commit-failed' };
136
+ }
176
137
  return { name: skill.name, status: 'imported' };
177
138
  }
178
139
  finally {
179
140
  await rm(gitContext.temporary, { recursive: true, force: true });
180
141
  }
181
142
  }
182
- export async function importSkillsToCollection(skills, options = {}) {
183
- if (!skills.length)
184
- return { count: 0 };
185
- let selected = skills;
186
- let allowReplace = options.replace ?? false;
143
+ async function classifyImportReplacements(skills, gitContext) {
187
144
  const paths = collectionPaths();
188
- const conflicts = [];
189
- for (const skill of selected) {
190
- if (await exists(join(paths.skills, skill.name)))
191
- conflicts.push(skill.name);
145
+ const sameSource = [];
146
+ const candidates = [];
147
+ for (const skill of skills) {
148
+ if (!(await pathPresent(join(paths.skills, skill.name))))
149
+ continue;
150
+ const current = await readMetadata(skill.name);
151
+ const incoming = gitContext
152
+ ? await gitSkillMetadata(skill, gitContext, skill.tags ?? [])
153
+ : {
154
+ name: skill.name,
155
+ description: skill.description,
156
+ tags: skill.tags ?? [],
157
+ note: skill.note ?? '',
158
+ source: await resolveIncomingProvenance(skill),
159
+ };
160
+ // Always re-classify at plan time; scan-time collectionStatus is display-only.
161
+ const match = await classifyCollectionMatch(current, incoming);
162
+ if (match === 'same-source') {
163
+ sameSource.push(skill.name);
164
+ continue;
165
+ }
166
+ candidates.push({ name: skill.name, match, current, incoming });
192
167
  }
193
- if (conflicts.length && !allowReplace) {
168
+ return { sameSource, candidates };
169
+ }
170
+ export function defaultReplaceConfirmMessage(candidates) {
171
+ if (candidates.length === 1) {
172
+ const item = candidates[0];
173
+ return {
174
+ message: t('cmd.replaceIdentityConfirm', {
175
+ name: item.name,
176
+ from: formatSkillIdentity(item.current),
177
+ to: formatSkillIdentity(item.incoming),
178
+ }),
179
+ details: [collectionMatchLabels()[item.match]],
180
+ };
181
+ }
182
+ return {
183
+ message: t('cmd.replaceSameNameConfirm', {
184
+ names: candidates.map((c) => c.name).join(t('common.listSep')),
185
+ }),
186
+ details: candidates.map((c) => `${c.name}: ${formatSkillIdentity(c.current)} → ${formatSkillIdentity(c.incoming)} · ${collectionMatchLabels()[c.match]}`),
187
+ };
188
+ }
189
+ /** Shared replace confirm for CLI default, browser, and search. */
190
+ export async function confirmCollectionReplace(candidates) {
191
+ const { message, details } = defaultReplaceConfirmMessage(candidates);
192
+ return (await import('../ui/overlay/static.js')).Modal.confirm({
193
+ title: t('cmd.replaceCollectionTitle'),
194
+ message,
195
+ details,
196
+ });
197
+ }
198
+ async function resolveImportSelection(skills, options, gitContext) {
199
+ let selected = skills;
200
+ const replaceNames = new Set();
201
+ if (options.replace) {
202
+ for (const skill of selected)
203
+ replaceNames.add(skill.name);
204
+ }
205
+ const { sameSource, candidates } = await classifyImportReplacements(selected, gitContext);
206
+ const sameSourceNames = new Set(sameSource);
207
+ selected = selected.filter((skill) => !sameSourceNames.has(skill.name));
208
+ if (candidates.length && !options.replace) {
194
209
  if (!process.stdin.isTTY || options.yes) {
195
- throw new Error(t('cmd.conflictsExistReplace', { names: conflicts.join(', ') }));
196
- }
197
- allowReplace = options.confirmReplace
198
- ? await options.confirmReplace(conflicts)
199
- : await (await import('../ui/overlay/static.js')).Modal.confirm({
200
- title: t('common.confirm'),
201
- message: t('cmd.replaceSameNameConfirm', { names: conflicts.join(', ') }),
210
+ throw new DomainError('cmd.conflictsExistReplace', {
211
+ names: candidates.map((c) => c.name).join(t('common.listSep')),
202
212
  });
203
- if (!allowReplace) {
204
- selected = selected.filter((skill) => !conflicts.includes(skill.name));
213
+ }
214
+ const confirm = options.confirmReplace
215
+ ? await options.confirmReplace(candidates)
216
+ : await confirmCollectionReplace(candidates);
217
+ if (!confirm) {
218
+ const blocked = new Set(candidates.map((c) => c.name));
219
+ selected = selected.filter((skill) => !blocked.has(skill.name));
220
+ }
221
+ else {
222
+ for (const c of candidates)
223
+ replaceNames.add(c.name);
205
224
  }
206
225
  }
226
+ return { selected, replaceNames };
227
+ }
228
+ export async function importSkillsToCollection(skills, options = {}) {
229
+ if (!skills.length)
230
+ return { count: 0 };
231
+ const { selected, replaceNames } = await resolveImportSelection(skills, options);
207
232
  if (!selected.length)
208
233
  return { count: 0 };
209
- let count = 0;
234
+ const installed = [];
210
235
  for (const skill of selected) {
211
- if (await importLocalSkill(skill, allowReplace, options.tags ?? []))
212
- count++;
236
+ if (await importLocalSkill(skill, replaceNames.has(skill.name), options.tags ?? [])) {
237
+ installed.push(skill.name);
238
+ }
213
239
  }
214
- await commitCollection(`import ${selected.map((skill) => skill.name).join(', ')}`);
215
- if (!options.quiet) {
216
- console.log(t('cmd.importedCount', { count }));
240
+ if (!installed.length)
241
+ return { count: 0 };
242
+ // One commit point. Soft-fail: warn via domainNotify; no 已导入 line.
243
+ if (!(await commitCollection(`import ${installed.join(', ')}`))) {
244
+ return { count: installed.length, commitFailed: true };
217
245
  }
218
- return { count };
246
+ if (!options.quiet)
247
+ console.log(t('cmd.importedCount', { count: installed.length }));
248
+ return { count: installed.length };
219
249
  }
220
- export async function globalSkillGroups(names = []) {
221
- const home = homedir();
222
- const collectedByPath = new Map();
223
- for (const skill of await listCollection()) {
224
- try {
225
- collectedByPath.set(await realpath(skill.path), skill);
250
+ export async function importGitSkillsToCollection(skills, gitContext, options = {}) {
251
+ if (!skills.length)
252
+ return { count: 0 };
253
+ const { selected, replaceNames } = await resolveImportSelection(skills, options, gitContext);
254
+ if (!selected.length)
255
+ return { count: 0 };
256
+ const installed = [];
257
+ for (const skill of selected) {
258
+ if (await importRemoteSkill(skill, gitContext, replaceNames.has(skill.name), options.tags ?? [])) {
259
+ installed.push(skill.name);
226
260
  }
227
- catch { }
228
261
  }
229
- // Empty present → empty groups (browser global tab). import -g checks separately.
230
- const selected = names.length
231
- ? names.map((name) => ({ name, agent: getAgent(name) }))
232
- : (await listPresentAgents(home)).map((name) => ({ name, agent: getAgent(name) }));
233
- const groups = [];
234
- for (const { name, agent } of selected) {
235
- const root = agent.global(home);
236
- const skills = await Promise.all((await discoverSkills(root)).map(async (skill) => {
237
- try {
238
- const collected = collectedByPath.get(await realpath(skill.path));
239
- return collected
240
- ? { ...collected, path: skill.path, fromCollection: true }
241
- : { ...skill, fromCollection: false };
242
- }
243
- catch {
244
- return { ...skill, fromCollection: false };
245
- }
246
- }));
247
- skills.sort((a, b) => a.name.localeCompare(b.name));
248
- groups.push({ agent: name, root, skills });
262
+ if (!installed.length)
263
+ return { count: 0 };
264
+ if (!(await commitCollection(`import ${installed.join(', ')}`))) {
265
+ return { count: installed.length, commitFailed: true };
249
266
  }
250
- return groups.sort((a, b) => a.agent.localeCompare(b.agent));
267
+ if (!options.quiet)
268
+ console.log(t('cmd.importedCount', { count: installed.length }));
269
+ return { count: installed.length };
251
270
  }
252
271
  export async function commandImport(argv) {
253
272
  const { values, positionals } = parseArgs({
@@ -262,9 +281,9 @@ export async function commandImport(argv) {
262
281
  },
263
282
  });
264
283
  if (values.global && positionals.length)
265
- throw new Error(t('cmd.cannotSourceAndGlobal'));
284
+ throw new DomainError('cmd.cannotSourceAndGlobal');
266
285
  if (positionals.length > 1)
267
- throw new Error(t('cmd.oneImportRootOnly'));
286
+ throw new DomainError('cmd.oneImportRootOnly');
268
287
  const input = positionals[0];
269
288
  const localInput = input ? resolve(input) : undefined;
270
289
  const gitContext = input && localInput && !(await exists(localInput)) && isGitSource(input)
@@ -278,13 +297,13 @@ export async function commandImport(argv) {
278
297
  let globalGroups;
279
298
  if (gitContext) {
280
299
  const collection = await listCollection().catch(() => []);
281
- skills = annotateGitCollectionStatus((await discoverSkills(gitContext.repository)).filter(isCollected), gitContext, collection);
300
+ skills = await annotateGitCollectionStatus((await discoverSkills(gitContext.repository)).filter(isCollected), gitContext, collection);
282
301
  }
283
302
  else if (values.global) {
284
303
  if (!(values.agent?.length) && !(await listPresentAgents()).length) {
285
- throw new Error(noPresentAgentsError());
304
+ throw noPresentAgentsError();
286
305
  }
287
- const groups = await globalSkillGroups(values.agent);
306
+ const groups = await listGlobalGroups(values.agent);
288
307
  globalGroups = groups
289
308
  .map((group) => ({
290
309
  agent: group.agent,
@@ -297,11 +316,11 @@ export async function commandImport(argv) {
297
316
  skills = (await discoverSkills(localInput || resolve('.'))).filter(isCollected);
298
317
  }
299
318
  if (!skills.length)
300
- throw new Error(t('cmd.noSkillMd'));
319
+ throw new DomainError('cmd.noSkillMd');
301
320
  let selected = skills;
302
321
  if (!values.all && (skills.length > 1 || !input)) {
303
322
  if (!process.stdin.isTTY)
304
- throw new Error(t('cmd.useAllOrInteractive'));
323
+ throw new DomainError('cmd.useAllOrInteractive');
305
324
  const groups = globalGroups ?? [{ agent: gitContext ? t('common.git') : t('common.local'), skills }];
306
325
  selected = await (await present()).promptSkillGroups(groups, globalGroups
307
326
  ? t('cmd.scanGlobalSkills')
@@ -314,7 +333,7 @@ export async function commandImport(argv) {
314
333
  let importTags = [];
315
334
  if (!values.yes) {
316
335
  if (!process.stdin.isTTY)
317
- throw new Error(t('cmd.useYesToConfirmImport'));
336
+ throw new DomainError('cmd.useYesToConfirmImport');
318
337
  const existingTags = [...new Set((await listCollection().catch(() => []))
319
338
  .flatMap((skill) => skill.tags))]
320
339
  .sort((a, b) => a.localeCompare(b));
@@ -328,40 +347,19 @@ export async function commandImport(argv) {
328
347
  return;
329
348
  importTags = review.tags;
330
349
  }
331
- let allowReplace = values.replace ?? false;
332
350
  if (!gitContext) {
333
351
  await importSkillsToCollection(selected, {
334
- replace: allowReplace,
352
+ replace: values.replace ?? false,
335
353
  yes: values.yes ?? false,
336
354
  tags: importTags,
337
355
  });
338
356
  return;
339
357
  }
340
- const conflicts = [];
341
- for (const skill of selected) {
342
- if (await exists(join(paths.skills, skill.name)) &&
343
- skill.collectionStatus !== 'same-source') {
344
- conflicts.push(skill.name);
345
- }
346
- }
347
- if (conflicts.length && !allowReplace) {
348
- if (!process.stdin.isTTY) {
349
- throw new Error(t('cmd.conflictsExistReplace', { names: conflicts.join(', ') }));
350
- }
351
- allowReplace = await (await import('../ui/overlay/static.js')).Modal.confirm({
352
- title: t('common.confirm'),
353
- message: t('cmd.replaceSameNameConfirm', { names: conflicts.join(', ') }),
354
- });
355
- if (!allowReplace)
356
- selected = selected.filter((skill) => !conflicts.includes(skill.name));
357
- }
358
- let count = 0;
359
- for (const skill of selected) {
360
- if (await importRemoteSkill(skill, gitContext, allowReplace, importTags))
361
- count++;
362
- }
363
- await commitCollection(`import ${selected.map((skill) => skill.name).join(', ')}`);
364
- console.log(t('cmd.importedCount', { count }));
358
+ await importGitSkillsToCollection(selected, gitContext, {
359
+ replace: values.replace ?? false,
360
+ yes: values.yes ?? false,
361
+ tags: importTags,
362
+ });
365
363
  }
366
364
  finally {
367
365
  if (gitContext)
@@ -376,13 +374,13 @@ async function resolveTargets(values) {
376
374
  let names = requestedAgents;
377
375
  if (!names.length) {
378
376
  if (!process.stdin.isTTY)
379
- throw new Error(t('cmd.globalNeedsAgent'));
377
+ throw new DomainError('cmd.globalNeedsAgent');
380
378
  const presentNames = await listPresentAgents();
381
379
  if (!presentNames.length)
382
- throw new Error(noPresentAgentsError());
380
+ throw noPresentAgentsError();
383
381
  names = await (await present()).promptChoicesMany(presentNames.map((name) => ({ label: name, value: name })), t('cmd.selectGlobalAgent'));
384
382
  if (!names.length)
385
- throw new Error(noPresentAgentsError());
383
+ throw noPresentAgentsError();
386
384
  }
387
385
  return [...new Set(names.map((name) => agentGlobalPath(name)))];
388
386
  }
@@ -411,11 +409,11 @@ async function selectCollectionSkills(names) {
411
409
  const found = new Set(selected.map((skill) => skill.name));
412
410
  const missing = names.filter((name) => !found.has(name));
413
411
  if (missing.length)
414
- throw new Error(t('cmd.missingInCollection', { names: missing.join(', ') }));
412
+ throw new DomainError('cmd.missingInCollection', { names: missing.join(', ') });
415
413
  return selected;
416
414
  }
417
415
  if (!process.stdin.isTTY)
418
- throw new Error(t('cmd.specifySkillNames'));
416
+ throw new DomainError('cmd.specifySkillNames');
419
417
  if (!skills.length) {
420
418
  let source;
421
419
  const ui = await present();
@@ -451,7 +449,7 @@ export async function addSkillsToProject(skills, values = {}) {
451
449
  for (const skill of skills) {
452
450
  const target = join(targetRoot, skill.name);
453
451
  if (target === resolve(skill.path) || target.startsWith(`${resolve(skill.path)}${sep}`)) {
454
- throw new Error(t('cmd.targetPointsSelf', { target }));
452
+ throw new DomainError('cmd.targetPointsSelf', { target });
455
453
  }
456
454
  if (await pathPresent(target)) {
457
455
  if (await isExactSymlink(target, skill.path))
@@ -468,7 +466,7 @@ export async function addSkillsToProject(skills, values = {}) {
468
466
  if (!replace) {
469
467
  if (process.stdin.isTTY && !values.yes)
470
468
  continue;
471
- throw new Error(t('cmd.targetExistsReplace', { target }));
469
+ throw new DomainError('cmd.targetExistsReplace', { target });
472
470
  }
473
471
  await rm(target, { recursive: true });
474
472
  }
@@ -493,6 +491,157 @@ export async function addSkillsToProject(skills, values = {}) {
493
491
  }
494
492
  return { count: addedSkills.size, targetCount: addedTargets.size };
495
493
  }
494
+ /** Move existing target aside, create symlink, restore on failure. */
495
+ async function replacePathWithSymlink(target, linkTarget) {
496
+ const absolute = resolve(target);
497
+ const parent = dirname(absolute);
498
+ await mkdir(parent, { recursive: true });
499
+ let backup;
500
+ if (await pathPresent(absolute)) {
501
+ backup = join(parent, `.iskills-replace-${basename(absolute)}-${process.pid}-${Date.now()}`);
502
+ await rename(absolute, backup);
503
+ }
504
+ try {
505
+ await symlink(linkTarget, absolute, 'dir');
506
+ if (backup)
507
+ await rm(backup, { recursive: true, force: true });
508
+ }
509
+ catch (error) {
510
+ await rm(absolute, { recursive: true, force: true }).catch(() => { });
511
+ if (backup)
512
+ await rename(backup, absolute);
513
+ throw error;
514
+ }
515
+ }
516
+ /**
517
+ * Drop any collection links recorded at `paths`, then append usage links for successful installs.
518
+ */
519
+ async function rewriteUsageLinksAtTargets(clearPaths, add) {
520
+ if (!clearPaths.length && !add.length)
521
+ return;
522
+ const clear = new Set(clearPaths.map((path) => resolve(path)));
523
+ const state = await readState();
524
+ const links = state.links.filter((link) => !clear.has(resolve(link.path)));
525
+ for (const item of add) {
526
+ links.push({ skill: item.skill, path: resolve(item.path), kind: 'usage' });
527
+ }
528
+ await writeState({ ...state, links });
529
+ }
530
+ /**
531
+ * Install skills from one agent location into other agent roots (symlink only).
532
+ * Collection-backed refs link to the collection skill path; local dirs link to A.
533
+ * Conflict handling aligns with add (best-effort); replace is confirmed once for all conflicts.
534
+ */
535
+ export async function installSkillsAcrossAgents(skills, targetRoots, options = {}) {
536
+ if (!skills.length || !targetRoots.length)
537
+ return { count: 0, targetCount: 0 };
538
+ const plans = [];
539
+ for (const skill of skills) {
540
+ const plan = await resolveCrossAgentInstallPlan(skill);
541
+ if (!plan) {
542
+ throw new DomainError('cmd.crossAgentUnsupported', { name: skill.name, path: skill.path });
543
+ }
544
+ plans.push(plan);
545
+ }
546
+ // Dedupe target roots by canonical identity (symlink aliases collapse).
547
+ const rootsByCanon = new Map();
548
+ for (const root of targetRoots) {
549
+ const absolute = resolve(root);
550
+ await mkdir(absolute, { recursive: true });
551
+ const canon = await canonicalizePath(absolute);
552
+ if (!rootsByCanon.has(canon))
553
+ rootsByCanon.set(canon, absolute);
554
+ }
555
+ const roots = [...rootsByCanon.values()];
556
+ // One plan per absolute target path; reject ambiguous same-name sources.
557
+ const planByTarget = new Map();
558
+ for (const targetRoot of roots) {
559
+ for (const plan of plans) {
560
+ const target = resolve(join(targetRoot, plan.skill.name));
561
+ if (await isPhysicalSelfInstall(target, plan.linkTarget)) {
562
+ throw new DomainError('cmd.targetPointsSelf', { target });
563
+ }
564
+ if (target === resolve(plan.linkTarget) ||
565
+ target.startsWith(`${resolve(plan.linkTarget)}${sep}`)) {
566
+ throw new DomainError('cmd.targetPointsSelf', { target });
567
+ }
568
+ const existing = planByTarget.get(target);
569
+ if (existing) {
570
+ if (existing.linkTarget === plan.linkTarget)
571
+ continue;
572
+ throw new DomainError('cmd.crossAgentAmbiguousSource', {
573
+ name: plan.skill.name,
574
+ target,
575
+ });
576
+ }
577
+ planByTarget.set(target, plan);
578
+ }
579
+ }
580
+ const work = [];
581
+ const conflicts = [];
582
+ for (const [target, plan] of planByTarget) {
583
+ if (await pathPresent(target)) {
584
+ if (await isExactSymlink(target, plan.linkTarget))
585
+ continue;
586
+ // Same physical tree via agent-root alias — never treat as replaceable conflict.
587
+ if (await isPhysicalSelfInstall(target, plan.linkTarget)) {
588
+ throw new DomainError('cmd.targetPointsSelf', { target });
589
+ }
590
+ conflicts.push(target);
591
+ }
592
+ work.push({ plan, target });
593
+ }
594
+ let replaceAll = options.replace ?? false;
595
+ if (conflicts.length && !replaceAll) {
596
+ if (options.confirmReplaceAll) {
597
+ replaceAll = await options.confirmReplaceAll(conflicts);
598
+ }
599
+ else if (process.stdin.isTTY) {
600
+ replaceAll = await (await import('../ui/overlay/static.js')).Modal.confirm({
601
+ title: t('cmd.replaceTargetTitle'),
602
+ message: t('cmd.replaceTargetsConfirm', { count: conflicts.length }),
603
+ details: conflicts,
604
+ });
605
+ }
606
+ else {
607
+ throw new DomainError('cmd.targetExistsReplace', { target: conflicts[0] ?? '' });
608
+ }
609
+ }
610
+ const conflictSet = new Set(conflicts);
611
+ const addedSkills = new Set();
612
+ const addedTargets = new Set();
613
+ const writtenPaths = [];
614
+ const usageAdds = [];
615
+ for (const item of work) {
616
+ const { plan, target } = item;
617
+ const isConflict = conflictSet.has(target);
618
+ if (isConflict && !replaceAll)
619
+ continue;
620
+ if (await pathPresent(target)) {
621
+ if (await isExactSymlink(target, plan.linkTarget))
622
+ continue;
623
+ if (await isPhysicalSelfInstall(target, plan.linkTarget)) {
624
+ throw new DomainError('cmd.targetPointsSelf', { target });
625
+ }
626
+ if (!isConflict && !replaceAll)
627
+ continue;
628
+ await replacePathWithSymlink(target, plan.linkTarget);
629
+ }
630
+ else {
631
+ await mkdir(dirname(target), { recursive: true });
632
+ await symlink(plan.linkTarget, target, 'dir');
633
+ }
634
+ writtenPaths.push(target);
635
+ if (plan.registerUsage) {
636
+ usageAdds.push({ skill: plan.skill.name, path: target });
637
+ }
638
+ addedSkills.add(plan.skill.name);
639
+ addedTargets.add(dirname(target));
640
+ }
641
+ // Clear stale link records at written paths, then register new usage rows.
642
+ await rewriteUsageLinksAtTargets(writtenPaths, usageAdds);
643
+ return { count: addedSkills.size, targetCount: addedTargets.size };
644
+ }
496
645
  export async function commandAdd(argv) {
497
646
  const { values, positionals } = parseArgs({
498
647
  args: argv,