@kabmo-labs/kabmo 0.16.0 → 0.17.0

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/README.md +2 -2
  2. package/dist/client/index.html +1 -1
  3. package/dist/client/index.js +417 -417
  4. package/dist/client/static/js/index-3ve31rzx.css +1 -0
  5. package/dist/client/static/js/{index-cpydmygd.js → index-rerjq5th.js} +839 -837
  6. package/package.json +1 -1
  7. package/src/client/components/common/code-surface/bracket-guide.test.ts +2 -2
  8. package/src/client/components/common/code-surface/bracket-guide.ts +2 -2
  9. package/src/client/components/common/code-surface/conflict-markers.ts +5 -5
  10. package/src/client/components/common/code-surface/extensions.ts +7 -4
  11. package/src/client/components/common/code-surface/theme.ts +34 -9
  12. package/src/client/components/common/code-surface/whitespace.test.ts +223 -0
  13. package/src/client/components/common/code-surface/whitespace.ts +140 -0
  14. package/src/client/components/common/{server-switcher/index.tsx → server-control/Panel.tsx} +73 -35
  15. package/src/client/components/common/{server-switcher → server-control}/index.test.tsx +98 -37
  16. package/src/client/components/common/server-control/index.tsx +118 -0
  17. package/src/client/components/layout/desktop-layout/TopNavbar.tsx +8 -50
  18. package/src/client/components/mobile/mobile-main-view/Header.tsx +6 -12
  19. package/src/client/components/mobile/mobile-session-sidebar/Header.tsx +41 -13
  20. package/src/client/components/settings/Modal.tsx +9 -3
  21. package/src/client/components/settings/ProjectSelectorDropdown.tsx +19 -9
  22. package/src/client/components/settings/categories/AgentSettings.tsx +27 -6
  23. package/src/client/components/settings/categories/ProjectSettings.tsx +122 -156
  24. package/src/client/components/settings/categories/SkillCatalogSettings.tsx +220 -260
  25. package/src/client/components/settings/categories/SkillSettings.tsx +6 -3
  26. package/src/client/components/settings/categories/agent-settings/SidebarList.tsx +5 -0
  27. package/src/client/components/settings/categories/project-settings/AccentPalette.test.tsx +189 -0
  28. package/src/client/components/settings/categories/project-settings/AccentPalette.tsx +156 -24
  29. package/src/client/components/settings/categories/project-settings/AddProjectModal.tsx +175 -0
  30. package/src/client/components/settings/categories/project-settings/DeleteProjectModal.tsx +107 -0
  31. package/src/client/components/settings/categories/project-settings/DetailsForm.tsx +40 -24
  32. package/src/client/components/settings/categories/project-settings/DetailsHeader.tsx +17 -7
  33. package/src/client/components/settings/categories/project-settings/IconGrid.tsx +164 -69
  34. package/src/client/components/settings/categories/project-settings/ModelDropdown.test.tsx +122 -0
  35. package/src/client/components/settings/categories/project-settings/ModelDropdown.tsx +124 -53
  36. package/src/client/components/settings/categories/project-settings/NameInput.tsx +57 -11
  37. package/src/client/components/settings/categories/project-settings/PathField.tsx +122 -0
  38. package/src/client/components/settings/categories/project-settings/SidebarList.tsx +100 -59
  39. package/src/client/components/settings/categories/skill-catalog/GitImportPanel.tsx +253 -0
  40. package/src/client/components/settings/categories/skill-catalog/SkillCard.tsx +89 -0
  41. package/src/client/components/settings/categories/skill-catalog/SourceRail.tsx +122 -0
  42. package/src/client/components/settings/categories/skill-catalog/catalog-ui.test.tsx +179 -0
  43. package/src/client/components/settings/categories/skill-settings/DetailHeader.tsx +208 -0
  44. package/src/client/components/settings/categories/skill-settings/DetailPane.tsx +137 -232
  45. package/src/client/components/settings/categories/skill-settings/InstructionsEditor.tsx +84 -0
  46. package/src/client/components/settings/categories/skill-settings/SidebarList.tsx +123 -87
  47. package/src/client/components/settings/categories/skill-settings/pane.test.tsx +179 -0
  48. package/src/client/components/settings/categories/skill-settings/row-meta.ts +58 -0
  49. package/src/client/components/workspace/chat-timeline/index.tsx +6 -1
  50. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Proc.test.ts +46 -0
  51. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Proc.tsx +15 -6
  52. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Wait.test.ts +29 -0
  53. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Wait.tsx +11 -3
  54. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/card-header.test.ts +24 -1
  55. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/card-header.ts +6 -2
  56. package/src/client/components/workspace/editor/viewers/SvgPreview.tsx +18 -2
  57. package/src/client/components/workspace/editor/viewers/viewers.test.ts +39 -0
  58. package/src/client/components/workspace/file-explorer/ContextMenu.tsx +18 -5
  59. package/src/client/components/workspace/file-explorer/Modals.tsx +15 -1
  60. package/src/client/components/workspace/file-explorer/RowLabel.tsx +68 -0
  61. package/src/client/components/workspace/file-explorer/TreeItem.tsx +47 -57
  62. package/src/client/components/workspace/file-explorer/collapsed-chain.test.ts +167 -0
  63. package/src/client/components/workspace/file-explorer/drag-props.ts +42 -0
  64. package/src/client/components/workspace/file-explorer/drag.test.ts +43 -0
  65. package/src/client/components/workspace/file-explorer/index.tsx +21 -20
  66. package/src/client/data/settings/omp-schema.json +91 -4
  67. package/src/client/data/settings/project.ts +9 -28
  68. package/src/client/data/settings/skill.ts +6 -32
  69. package/src/client/hooks/chat/timeline/pending-model.ts +28 -0
  70. package/src/client/hooks/settings/projects/index.ts +294 -0
  71. package/src/client/hooks/settings/projects.test.ts +237 -0
  72. package/src/client/hooks/settings/skill-catalog.ts +101 -9
  73. package/src/client/hooks/settings/skill-git-import.ts +153 -0
  74. package/src/client/hooks/shell/servers.test.ts +166 -0
  75. package/src/client/hooks/{desktop → shell}/servers.ts +17 -14
  76. package/src/client/hooks/ui/updates/shell-download.ts +1 -1
  77. package/src/client/hooks/ui/updates/shell-update.ts +2 -6
  78. package/src/client/hooks/workspace/file-row-drag.ts +41 -0
  79. package/src/client/hooks/workspace/file-tree-actions.ts +25 -1
  80. package/src/client/hooks/workspace/file-tree-edits.ts +23 -6
  81. package/src/client/hooks/workspace/root-drop-target.ts +77 -0
  82. package/src/client/hooks/workspace/unfolded-chains.ts +165 -0
  83. package/src/client/lib/desktop/dropped-paths.ts +1 -1
  84. package/src/client/lib/desktop/titlebar.test.ts +12 -3
  85. package/src/client/lib/desktop/titlebar.ts +1 -1
  86. package/src/client/lib/shell/desktop.ts +117 -0
  87. package/src/client/lib/shell/servers.ts +75 -0
  88. package/src/client/lib/shell/transport.ts +216 -0
  89. package/src/client/main.tsx +9 -0
  90. package/src/server/lib/fs/git-merge-conflict.test.ts +14 -1
  91. package/src/server/lib/omp/config/skill-sources.ts +49 -0
  92. package/src/server/lib/omp/config/skills-git-install.ts +155 -0
  93. package/src/server/lib/omp/config/skills-git-repo.ts +288 -0
  94. package/src/server/lib/omp/config/skills-git.test.ts +220 -0
  95. package/src/server/lib/workspace/project-model.server.test.ts +102 -0
  96. package/src/server/lib/workspace/project-model.server.ts +47 -0
  97. package/src/server/lib/workspace/project-patch.server.ts +156 -0
  98. package/src/server/routes/agent/new.ts +8 -1
  99. package/src/server/routes/settings/agents.ts +19 -7
  100. package/src/server/routes/settings/projects.ts +53 -19
  101. package/src/server/routes/settings/settings-projects-routes.test.ts +214 -0
  102. package/src/server/routes/settings/settings-store-routes.test.ts +5 -2
  103. package/src/server/routes/settings/skills-catalog-actions.ts +195 -0
  104. package/src/server/routes/settings/skills.test.ts +225 -0
  105. package/src/server/routes/settings/skills.ts +18 -15
  106. package/src/shared/lib/fs/folder-chain.test.ts +81 -1
  107. package/src/shared/lib/fs/folder-chain.ts +84 -0
  108. package/src/shared/lib/omp/config/schema.test.ts +35 -0
  109. package/src/shared/lib/omp/session/job-progress.test.ts +37 -1
  110. package/src/shared/lib/omp/session/job-progress.ts +31 -0
  111. package/src/shared/lib/omp/session/proc.ts +5 -0
  112. package/src/shared/lib/omp/session/wait.ts +5 -0
  113. package/src/shared/lib/ui/mobile-overlay.ts +61 -0
  114. package/src/shared/lib/ui/svg-scope.test.ts +97 -0
  115. package/src/shared/lib/ui/svg-scope.ts +134 -0
  116. package/src/shared/lib/workspace/project-accent.test.ts +69 -0
  117. package/src/shared/lib/workspace/project-accent.ts +63 -0
  118. package/src/shared/lib/workspace/project-icon.ts +40 -0
  119. package/src/shared/lib/workspace/project-model.test.ts +79 -0
  120. package/src/shared/lib/workspace/project-model.ts +64 -0
  121. package/src/shared/types/settings/skill.ts +53 -3
  122. package/src/test-support/file-explorer-disk.test-util.ts +25 -1
  123. package/src/test-support/file-explorer-drag.test-util.ts +88 -0
  124. package/src/test-support/file-explorer.test-util.ts +47 -47
  125. package/dist/client/static/js/index-fjnq2z2d.css +0 -1
  126. package/src/client/components/common/code-surface/indent-guide.ts +0 -104
  127. package/src/client/components/settings/categories/skill-catalog/AddSourceModal.tsx +0 -133
  128. package/src/client/hooks/desktop/servers.test.ts +0 -73
  129. package/src/client/lib/desktop/bridge.ts +0 -203
  130. package/src/shared/lib/code/editor/indent-guide-rule.test.ts +0 -65
  131. package/src/shared/lib/code/editor/indent-guide-rule.ts +0 -47
@@ -0,0 +1,288 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Skill import from an arbitrary git repository.
8
+ *
9
+ * The catalog's other install path is `bunx skills add <package>`, which works
10
+ * for a repository the skills.sh registry knows and tells the user nothing about
11
+ * what is inside. A URL a user pastes is neither: it may hold one SKILL.md at the
12
+ * root, twenty under `skills/`, or a plugin layout, and the user has to see the
13
+ * list before anything lands on disk. So this module clones the repository into
14
+ * a staging directory, reads the SKILL.md frontmatter itself, and installs the
15
+ * entries the user picked.
16
+ *
17
+ * Three properties are load-bearing:
18
+ *
19
+ * - **`bunx skills add <repo> --list` is NOT the inspector.** It prints a
20
+ * human-oriented tree (measured: 60+ wrapped lines for one repository), has no
21
+ * `--json` form (`--json` is refused together with `--list`), and no exit code
22
+ * or machine shape to parse. Reading SKILL.md from a clone is the only shape
23
+ * that survives a CLI rewrite.
24
+ * - **Everything is quoted as argv and path-joined through `join()`.** A skill
25
+ * name is author-chosen, so nothing here builds a shell string, and nothing
26
+ * copies a path the frontmatter supplied: a copy target is always
27
+ * `<root>/<validated name>`.
28
+ * - **The clone is always removed.** A failed clone, a repository with no
29
+ * SKILL.md and a successful install all `rm -rf` the staging directory in a
30
+ * `finally`, because a leftover clone is a directory the next scan would have
31
+ * to reason about.
32
+ *
33
+ * This half CLONES and SCANS; `skills-git-install.ts` is the half that writes
34
+ * into a managed root, and it imports the scanner rather than repeating it.
35
+ */
36
+
37
+ import fs from 'fs';
38
+ import { tmpdir } from 'os';
39
+ import { dirname, join, relative, resolve, sep } from 'path';
40
+ import { gitRun, firstLine } from '@/server/lib/wiki/git';
41
+ import { parseFrontmatter } from '@/server/lib/omp/config/yaml';
42
+ import { repoSlug } from '@/shared/lib/git/url';
43
+ import type { GitSkillEntry } from '@/shared/types';
44
+
45
+ export const CLONE_TIMEOUT_MS = 120_000;
46
+ export const MAX_SKILL_ENTRIES = 60;
47
+ /** A skill directory is instructions plus optional scripts/assets. Past this it
48
+ * is not a skill Kabmo should silently copy. */
49
+ export const MAX_SKILL_DIR_BYTES = 5 * 1024 * 1024;
50
+ const MAX_SCAN_DEPTH = 4;
51
+ const MAX_SKILL_MD_BYTES = 512 * 1024;
52
+
53
+ /** A repo reference Kabmo is willing to hand to `git clone`. */
54
+ export interface SkillRepoRef {
55
+ /** The URL exactly as git should receive it. */
56
+ url: string;
57
+ /** `owner/repo` for a GitHub URL, else the repo slug. Display and dedupe. */
58
+ slug: string;
59
+ }
60
+
61
+ /**
62
+ * Normalise what a user pasted into a clone URL.
63
+ *
64
+ * Accepts an https/ssh URL, the `git@host:owner/repo` form, a `github.com/owner/repo`
65
+ * shorthand with no scheme, and a bare `owner/repo` pair — the last two are what
66
+ * a catalog source card holds, and refusing them would mean the same repository
67
+ * had to be written two different ways in two panes.
68
+ */
69
+ export function toSkillRepoRef(raw: string): SkillRepoRef | null {
70
+ const value = raw.trim().replace(/\/+$/, '');
71
+ if (!value || /\s/.test(value)) return null;
72
+
73
+ if (/^(https?|ssh|file):\/\/\S+$/i.test(value) || /^git@[^:/\s]+:\S+$/.test(value)) {
74
+ return { url: value, slug: displaySlug(value) };
75
+ }
76
+ if (value.startsWith('/') || value.startsWith('~') || /^[a-z]:[\\/]/i.test(value)) {
77
+ // A local path: git clones it, and a test fixtures directory is a real use
78
+ // (an offline clone is the only way to exercise this offline). The key IS the
79
+ // path — its last segment would make two different checkouts both named
80
+ // "repo" one source, and the stored value is fed back to `git clone`, which
81
+ // cannot resolve a bare directory name.
82
+ return { url: value, slug: value };
83
+ }
84
+
85
+ const shorthand = value.replace(/^github\.com\//i, '');
86
+ if (/^[\w.-]+\/[\w.-]+$/.test(shorthand)) {
87
+ return { url: `https://github.com/${shorthand}.git`, slug: shorthand.replace(/\.git$/i, '') };
88
+ }
89
+ return null;
90
+ }
91
+
92
+ /**
93
+ * `owner/repo` for a URL that has an owner, the last path segment otherwise.
94
+ *
95
+ * `repoSlug` answers the DIRECTORY name a clone takes, which is the repository
96
+ * only — a catalog card that showed `skills` for `anthropics/skills` would name
97
+ * a repository that does not exist.
98
+ */
99
+ function displaySlug(url: string): string {
100
+ const withoutScheme = url.replace(/^[a-z]+:\/\//i, '').replace(/^git@[^:]+:/i, '');
101
+ const segments = withoutScheme.split('/').filter(Boolean);
102
+ const tail = segments.slice(-2).map((part) => part.replace(/\.git$/i, ''));
103
+ if (tail.length === 2 && !tail[0].includes(':')) return `${tail[0]}/${tail[1]}`;
104
+ return repoSlug(url) || url;
105
+ }
106
+
107
+ export function withinRoot(root: string, candidate: string): boolean {
108
+ const rel = relative(resolve(root), resolve(candidate));
109
+ return rel !== '' && !rel.startsWith('..') && !rel.startsWith(sep) && !rel.startsWith('/');
110
+ }
111
+
112
+ /** Directories a scan never descends into. A clone of a real repository is
113
+ * mostly these, and walking them costs seconds per inspection. */
114
+ const SKIP_DIRS: Record<string, true> = {
115
+ node_modules: true,
116
+ '.git': true,
117
+ dist: true,
118
+ build: true,
119
+ out: true,
120
+ coverage: true,
121
+ vendor: true,
122
+ '.next': true,
123
+ target: true,
124
+ };
125
+
126
+ async function readSkillEntry(stagingDir: string, skillMdPath: string): Promise<GitSkillEntry | null> {
127
+ const dir = dirname(skillMdPath);
128
+ if (!withinRoot(stagingDir, dir)) return null;
129
+ let stat: fs.Stats;
130
+ try {
131
+ stat = await fs.promises.stat(skillMdPath);
132
+ } catch {
133
+ return null;
134
+ }
135
+ if (!stat.isFile() || stat.size > MAX_SKILL_MD_BYTES) return null;
136
+
137
+ let text: string;
138
+ try {
139
+ text = await fs.promises.readFile(skillMdPath, 'utf8');
140
+ } catch {
141
+ return null;
142
+ }
143
+ const { data } = parseFrontmatter(text);
144
+ const name = (data.name || dir.split(sep).pop() || '').trim();
145
+ if (!name) return null;
146
+ const description = (data.description || '').replace(/\s+/g, ' ').trim();
147
+ return {
148
+ path: relative(stagingDir, dir).split(sep).join('/'),
149
+ name,
150
+ description,
151
+ // omp skips a SKILL.md with no description outright. Reporting such an entry
152
+ // as installable would promise a skill that cannot run.
153
+ loadable: description.length > 0,
154
+ };
155
+ }
156
+
157
+ /** Collect `SKILL.md` files, `skills/*` first. A repository that keeps its
158
+ * skills at the top level (one SKILL.md at the root) and one that keeps them
159
+ * under `skills/` both resolve, and a nested plugin layout is reached by the
160
+ * bounded walk. */
161
+ async function scanSkillDirs(stagingDir: string): Promise<string[]> {
162
+ const found: string[] = [];
163
+ const seen = new Set<string>();
164
+ const push = (file: string) => {
165
+ const dir = dirname(file);
166
+ if (seen.has(dir) || found.length >= MAX_SKILL_ENTRIES * 3) return;
167
+ seen.add(dir);
168
+ found.push(file);
169
+ };
170
+
171
+ const readdir = async (dir: string): Promise<fs.Dirent[]> => {
172
+ try {
173
+ return await fs.promises.readdir(dir, { withFileTypes: true });
174
+ } catch {
175
+ return [];
176
+ }
177
+ };
178
+
179
+ const rootEntries = await readdir(stagingDir);
180
+ for (const entry of rootEntries) {
181
+ if (entry.isFile() && entry.name === 'SKILL.md') push(join(stagingDir, entry.name));
182
+ }
183
+
184
+ for (const preferred of ['skills', 'plugins', 'agents']) {
185
+ const dir = join(stagingDir, preferred);
186
+ if (!(await fs.promises.stat(dir).then((s) => s.isDirectory()).catch(() => false))) continue;
187
+ for (const child of await readdir(dir)) {
188
+ if (!child.isDirectory()) continue;
189
+ const candidate = join(dir, child.name, 'SKILL.md');
190
+ if (await fs.promises.stat(candidate).then((s) => s.isFile()).catch(() => false)) push(candidate);
191
+ }
192
+ }
193
+
194
+ // Bounded walk for anything the conventional layouts did not cover.
195
+ const walk = async (dir: string, depth: number): Promise<void> => {
196
+ if (depth > MAX_SCAN_DEPTH || found.length >= MAX_SKILL_ENTRIES * 3) return;
197
+ for (const child of await readdir(dir)) {
198
+ if (found.length >= MAX_SKILL_ENTRIES * 3) return;
199
+ if (!child.isDirectory() || child.name.startsWith('.') || Object.hasOwn(SKIP_DIRS, child.name)) continue;
200
+ const next = join(dir, child.name);
201
+ const candidate = join(next, 'SKILL.md');
202
+ if (await fs.promises.stat(candidate).then((s) => s.isFile()).catch(() => false)) push(candidate);
203
+ await walk(next, depth + 1);
204
+ }
205
+ };
206
+ await walk(stagingDir, 1);
207
+ return found;
208
+ }
209
+
210
+ /** Every skill a repository holds, in listing order. */
211
+ export async function scanSkillRepository(stagingDir: string): Promise<GitSkillEntry[]> {
212
+ const files = await scanSkillDirs(stagingDir);
213
+ const entries: GitSkillEntry[] = [];
214
+ const names = new Set<string>();
215
+ for (const file of files) {
216
+ const entry = await readSkillEntry(stagingDir, file);
217
+ if (!entry) continue;
218
+ const key = `${entry.path}::${entry.name}`;
219
+ if (names.has(key)) continue;
220
+ names.add(key);
221
+ entries.push(entry);
222
+ if (entries.length >= MAX_SKILL_ENTRIES) break;
223
+ }
224
+ // Loadable entries first: a repository with three broken SKILL.md files and
225
+ // one real skill should not lead with the broken ones.
226
+ return entries.sort((a, b) => Number(b.loadable) - Number(a.loadable));
227
+ }
228
+
229
+ export interface InspectOptions {
230
+ /** Where the repository is cloned. Defaults to the OS temp dir. */
231
+ stagingParent?: string;
232
+ /** Test seam: clone a directory that already exists instead of running git. */
233
+ sourceDir?: string;
234
+ }
235
+
236
+ export async function stageClone(url: string, stagingParent: string): Promise<{ dir: string; cleanup: () => Promise<void> }> {
237
+ const slug = repoSlug(url) || 'repo';
238
+ const dir = join(stagingParent, `kabmo-skill-stage-${slug}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
239
+ await fs.promises.rm(dir, { recursive: true, force: true });
240
+ await fs.promises.mkdir(dirname(dir), { recursive: true });
241
+ const clone = await gitRun(['clone', '--depth', '1', '--quiet', url, dir], { timeoutMs: CLONE_TIMEOUT_MS });
242
+ const cleanup = async () => {
243
+ await fs.promises.rm(dir, { recursive: true, force: true }).catch(() => {});
244
+ };
245
+ if (clone.failed || clone.exitCode !== 0) {
246
+ await cleanup();
247
+ const detail = firstLine(clone.stderr);
248
+ if (/could not read Username|authentication failed|Permission denied/i.test(clone.stderr)) {
249
+ throw new Error(`${detail || 'git clone failed'} — the repository needs credentials Kabmo cannot supply`);
250
+ }
251
+ throw new Error(detail || 'git clone failed');
252
+ }
253
+ return { dir, cleanup };
254
+ }
255
+
256
+ /**
257
+ * Clone `url` into a staging directory, list its skills, and remove the clone.
258
+ *
259
+ * Errors are thrown with git's own first line, because "clone failed" tells the
260
+ * user nothing about a typo in the owner name or a private repository.
261
+ */
262
+ export async function inspectSkillRepo(
263
+ rawUrl: string,
264
+ options: InspectOptions = {},
265
+ ): Promise<{ repo: string; skills: GitSkillEntry[]; notes: string[] }> {
266
+ const ref = toSkillRepoRef(rawUrl);
267
+ if (!ref) throw new Error('Expected a git URL or an owner/repo pair');
268
+
269
+ if (options.sourceDir) {
270
+ const skills = await scanSkillRepository(options.sourceDir);
271
+ return { repo: ref.slug, skills, notes: [...(skills.length >= MAX_SKILL_ENTRIES ? [`Only the first ${MAX_SKILL_ENTRIES} skills are listed.`] : [])] };
272
+ }
273
+
274
+ const stagingParent = options.stagingParent ?? tmpdir();
275
+ const staged = await stageClone(ref.url, stagingParent);
276
+ try {
277
+ const skills = await scanSkillRepository(staged.dir);
278
+ const notes: string[] = [];
279
+ if (skills.length === 0) notes.push('No SKILL.md found in this repository.');
280
+ if (skills.length >= MAX_SKILL_ENTRIES) notes.push(`Only the first ${MAX_SKILL_ENTRIES} skills are listed.`);
281
+ const unloadable = skills.filter((skill) => !skill.loadable).length;
282
+ if (unloadable > 0) notes.push(`${unloadable} SKILL.md file(s) have no description, so omp would not load them.`);
283
+ return { repo: ref.slug, skills, notes };
284
+ } finally {
285
+ await staged.cleanup();
286
+ }
287
+ }
288
+
@@ -0,0 +1,220 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Skill import from a git repository: what the inspector is willing to list and
8
+ * what the managed-copy installer will and will not write.
9
+ *
10
+ * The cases pinned here are the ones that quietly corrupt a skill tree:
11
+ *
12
+ * - a skill whose frontmatter has no `description` is NOT loadable (omp skips
13
+ * the file outright), so offering it as installable would promise a skill that
14
+ * never appears in the agent;
15
+ * - a name carrying a path separator is refused rather than joined, which is the
16
+ * only thing standing between a repository and `join(root, '../../x')`;
17
+ * - an existing directory is a SKIP unless `overwrite` is set, so importing a
18
+ * repository twice cannot silently replace the user's edits to a skill;
19
+ * - every refusal is per skill: one collision must not abort the batch.
20
+ *
21
+ * Fixtures are plain directories on disk (`sourceDir`), so no case needs a
22
+ * network or a git binary. The one clone case points `git` at a local repository
23
+ * it creates itself, which is the only way to prove the staging directory is
24
+ * removed afterwards.
25
+ */
26
+
27
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
28
+ import fs from 'fs';
29
+ import { tmpdir } from 'os';
30
+ import { join } from 'path';
31
+ import { scanSkillRepository, toSkillRepoRef, inspectSkillRepo } from '@/server/lib/omp/config/skills-git-repo';
32
+ import { installSkillCopies } from '@/server/lib/omp/config/skills-git-install';
33
+ import { invalidateSkillCache } from '@/server/lib/omp/config/skills';
34
+ import { removeDir } from '@/test-support/remove-dir';
35
+
36
+ const ROOT = join(tmpdir(), 'kabmo-skills-git-test');
37
+ const REPO = join(ROOT, 'repo');
38
+ const AGENT_DIR = join(ROOT, 'agent');
39
+ let realAgentDir: string | undefined;
40
+
41
+ function writeSkill(dir: string, frontmatter: string, body = 'do the thing'): void {
42
+ fs.mkdirSync(dir, { recursive: true });
43
+ fs.writeFileSync(join(dir, 'SKILL.md'), `---\n${frontmatter}\n---\n\n${body}\n`);
44
+ }
45
+
46
+ beforeAll(() => {
47
+ removeDir(ROOT);
48
+ realAgentDir = Bun.env.PI_CODING_AGENT_DIR;
49
+ Bun.env.PI_CODING_AGENT_DIR = AGENT_DIR;
50
+ fs.mkdirSync(AGENT_DIR, { recursive: true });
51
+
52
+ writeSkill(join(REPO, 'skills', 'review-pr'), 'name: review-pr\ndescription: Review pull requests');
53
+ writeSkill(join(REPO, 'skills', 'diagnose'), 'name: diagnose\ndescription: Diagnose a bug');
54
+ writeSkill(join(REPO, 'skills', 'no-description'), 'name: no-description');
55
+ writeSkill(join(REPO, 'plugins', 'nested-skill'), 'name: nested-skill\ndescription: Lives under plugins/');
56
+ // A directory with an unrelated README is not a skill.
57
+ fs.mkdirSync(join(REPO, 'docs'), { recursive: true });
58
+ fs.writeFileSync(join(REPO, 'docs', 'README.md'), '# docs\n');
59
+ });
60
+
61
+ afterAll(() => {
62
+ if (realAgentDir === undefined) delete Bun.env.PI_CODING_AGENT_DIR;
63
+ else Bun.env.PI_CODING_AGENT_DIR = realAgentDir;
64
+ removeDir(ROOT);
65
+ });
66
+
67
+ describe('toSkillRepoRef', () => {
68
+ test('accepts a URL, the scp form, a github shorthand and an owner/repo pair', () => {
69
+ expect(toSkillRepoRef('https://github.com/anthropics/skills')?.url).toBe('https://github.com/anthropics/skills');
70
+ expect(toSkillRepoRef('https://github.com/anthropics/skills')?.slug).toBe('anthropics/skills');
71
+ expect(toSkillRepoRef('git@github.com:anthropics/skills.git')?.slug).toBe('anthropics/skills');
72
+ expect(toSkillRepoRef('github.com/anthropics/skills')?.url).toBe('https://github.com/anthropics/skills.git');
73
+ expect(toSkillRepoRef('anthropics/skills')?.slug).toBe('anthropics/skills');
74
+ });
75
+
76
+ test('a shorthand slug is owner/repo, not the clone directory name', () => {
77
+ // `repoSlug` answers the DIRECTORY a clone takes ("skills"); a card showing
78
+ // that would name a repository that does not exist.
79
+ expect(toSkillRepoRef('https://github.com/anthropics/skills')?.slug).not.toBe('skills');
80
+ expect(toSkillRepoRef('https://gitlab.com/team/tools/skills')?.slug).toBe('tools/skills');
81
+ });
82
+
83
+ test('refuses an empty value and anything with whitespace', () => {
84
+ expect(toSkillRepoRef('')).toBeNull();
85
+ expect(toSkillRepoRef(' ')).toBeNull();
86
+ expect(toSkillRepoRef('not a repo')).toBeNull();
87
+ });
88
+ });
89
+
90
+ describe('scanSkillRepository', () => {
91
+ test('lists skills/ and plugins/ entries and marks the unloadable one', async () => {
92
+ const skills = await scanSkillRepository(REPO);
93
+ const byName = new Map(skills.map((skill) => [skill.name, skill]));
94
+ expect(byName.get('review-pr')?.path).toBe('skills/review-pr');
95
+ expect(byName.get('diagnose')?.loadable).toBe(true);
96
+ expect(byName.get('nested-skill')?.path).toBe('plugins/nested-skill');
97
+ expect(byName.get('no-description')?.loadable).toBe(false);
98
+ expect(byName.has('README')).toBe(false);
99
+ });
100
+
101
+ test('loadable entries come first', async () => {
102
+ const skills = await scanSkillRepository(REPO);
103
+ const firstBlocked = skills.findIndex((skill) => !skill.loadable);
104
+ if (firstBlocked !== -1) {
105
+ expect(skills.slice(firstBlocked).every((skill) => !skill.loadable)).toBe(true);
106
+ }
107
+ });
108
+
109
+ test('a repository with no SKILL.md reports nothing and says so', async () => {
110
+ const empty = join(ROOT, 'empty-repo');
111
+ fs.mkdirSync(empty, { recursive: true });
112
+ fs.writeFileSync(join(empty, 'package.json'), '{}');
113
+ const inspection = await inspectSkillRepo(empty, { sourceDir: empty });
114
+ expect(inspection.skills).toEqual([]);
115
+ });
116
+ });
117
+
118
+ describe('installSkillCopies', () => {
119
+ test('copies a skill directory whole into the managed user root', async () => {
120
+ invalidateSkillCache();
121
+ const outcome = await installSkillCopies('owner/repo', ['skills/review-pr'], {
122
+ scope: 'user',
123
+ sourceDir: REPO,
124
+ });
125
+ expect(outcome.installed).toEqual(['review-pr']);
126
+ expect(outcome.skipped).toEqual([]);
127
+ const target = join(AGENT_DIR, 'skills', 'review-pr');
128
+ expect(fs.existsSync(join(target, 'SKILL.md'))).toBe(true);
129
+ expect(fs.readFileSync(join(target, 'SKILL.md'), 'utf8')).toContain('description: Review pull requests');
130
+ });
131
+
132
+ test('an existing skill is skipped, not overwritten, and the batch continues', async () => {
133
+ const outcome = await installSkillCopies('owner/repo', ['skills/review-pr', 'skills/diagnose'], {
134
+ scope: 'user',
135
+ sourceDir: REPO,
136
+ });
137
+ expect(outcome.installed).toEqual(['diagnose']);
138
+ expect(outcome.skipped).toEqual([
139
+ { name: 'review-pr', reason: 'already installed — enable overwrite to replace it' },
140
+ ]);
141
+ });
142
+
143
+ test('overwrite replaces the directory', async () => {
144
+ fs.writeFileSync(join(AGENT_DIR, 'skills', 'review-pr', 'SKILL.md'), 'local edit');
145
+ const outcome = await installSkillCopies('owner/repo', ['skills/review-pr'], {
146
+ scope: 'user',
147
+ sourceDir: REPO,
148
+ overwrite: true,
149
+ });
150
+ expect(outcome.installed).toEqual(['review-pr']);
151
+ expect(fs.readFileSync(join(AGENT_DIR, 'skills', 'review-pr', 'SKILL.md'), 'utf8')).toContain('Review pull requests');
152
+ });
153
+
154
+ test('a SKILL.md with no description is refused by name', async () => {
155
+ const outcome = await installSkillCopies('owner/repo', ['skills/no-description'], {
156
+ scope: 'user',
157
+ sourceDir: REPO,
158
+ });
159
+ expect(outcome.installed).toEqual([]);
160
+ expect(outcome.skipped[0]?.name).toBe('no-description');
161
+ expect(outcome.skipped[0]?.reason).toContain('no description');
162
+ expect(fs.existsSync(join(AGENT_DIR, 'skills', 'no-description'))).toBe(false);
163
+ });
164
+
165
+ test('a name carrying a path separator cannot escape the managed root', async () => {
166
+ const evil = join(ROOT, 'evil-repo');
167
+ writeSkill(join(evil, 'skills', 'escape'), 'name: ../../escaped\ndescription: tries to escape');
168
+ const outcome = await installSkillCopies('owner/repo', ['skills/escape'], {
169
+ scope: 'user',
170
+ sourceDir: evil,
171
+ });
172
+ expect(outcome.installed).toEqual([]);
173
+ expect(outcome.skipped[0]?.reason).toContain('path separator');
174
+ expect(fs.existsSync(join(AGENT_DIR, 'skills', 'escaped'))).toBe(false);
175
+ });
176
+
177
+ test('a project install with no workspace is refused, never redirected', async () => {
178
+ await expect(
179
+ installSkillCopies('owner/repo', ['skills/diagnose'], { scope: 'project', sourceDir: REPO }),
180
+ ).rejects.toThrow(/workspace root/);
181
+ });
182
+
183
+ test('selecting nothing from the repository is an error, not an empty success', async () => {
184
+ await expect(
185
+ installSkillCopies('owner/repo', ['skills/does-not-exist'], { scope: 'user', sourceDir: REPO }),
186
+ ).rejects.toThrow(/None of the selected skills/);
187
+ });
188
+ });
189
+
190
+ describe('inspectSkillRepo over a real clone', () => {
191
+ test('clones a local repository, lists its skills, and removes the staging directory', async () => {
192
+ const origin = join(ROOT, 'origin');
193
+ writeSkill(join(origin, 'skills', 'cloned'), 'name: cloned\ndescription: Came from a clone');
194
+ const stagingParent = join(ROOT, 'staging');
195
+ fs.mkdirSync(stagingParent, { recursive: true });
196
+
197
+ const init = Bun.spawnSync({ cmd: ['git', 'init', '--quiet'], cwd: origin });
198
+ expect(init.exitCode).toBe(0);
199
+ Bun.spawnSync({ cmd: ['git', 'add', '.'], cwd: origin });
200
+ Bun.spawnSync({
201
+ cmd: ['git', '-c', 'user.email=t@example.com', '-c', 'user.name=t', 'commit', '-qm', 'init'],
202
+ cwd: origin,
203
+ });
204
+
205
+ const inspection = await inspectSkillRepo(origin, { stagingParent });
206
+ expect(inspection.skills.map((skill) => skill.name)).toEqual(['cloned']);
207
+ const leftovers = fs.readdirSync(stagingParent).filter((entry) => entry.startsWith('kabmo-skill-stage-'));
208
+ expect(leftovers).toEqual([]);
209
+ });
210
+
211
+ test('a clone of a path that is not a repository reports git’s own line', async () => {
212
+ const notARepo = join(ROOT, 'not-a-repo');
213
+ fs.mkdirSync(notARepo, { recursive: true });
214
+ await expect(inspectSkillRepo(notARepo, { stagingParent: join(ROOT, 'staging2') })).rejects.toThrow();
215
+ });
216
+
217
+ test('an unusable URL is refused before any process starts', async () => {
218
+ await expect(inspectSkillRepo('not a repo')).rejects.toThrow(/Expected a git URL/);
219
+ });
220
+ });
@@ -0,0 +1,102 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The project default model reaching a new chat.
8
+ *
9
+ * "Defaults for new chats" is only a setting if the spawn reads it: the column
10
+ * rendered in two panes while `POST /api/agent/new` fell back to Kabmo's global
11
+ * pick, so every chat started on the global model regardless. These cases pin
12
+ * the resolution — exact root, a worktree/nested cwd under the root, a folder
13
+ * with no model (inherit), and a legacy display name that cannot name a model.
14
+ */
15
+
16
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
17
+ import { mkdtempSync } from 'node:fs';
18
+ import * as os from 'node:os';
19
+ import * as path from 'node:path';
20
+
21
+ import { createDb, type DbClient } from '@/server/lib/db/client';
22
+ import { projectModelForCwd } from '@/server/lib/workspace/project-model.server';
23
+ import { removeDir } from '@/test-support/remove-dir';
24
+
25
+ const ROOT = `${os.tmpdir()}/kabmo-project-model-${process.pid}`;
26
+
27
+ let workRoot = '';
28
+ let db: DbClient;
29
+
30
+ beforeAll(async () => {
31
+ workRoot = mkdtempSync(path.join(os.tmpdir(), 'kabmo-project-model-'));
32
+ db = createDb(path.join(workRoot, 'db.sqlite'));
33
+ await db.exec(`
34
+ CREATE TABLE workspace_folders (
35
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
36
+ name TEXT NOT NULL,
37
+ project_path TEXT,
38
+ model TEXT
39
+ );
40
+ `);
41
+ await db.run('INSERT INTO workspace_folders (name, project_path, model) VALUES (?, ?, ?)', [
42
+ 'kenari-project',
43
+ ROOT,
44
+ 'kenari:deepseek-v4-flash',
45
+ ]);
46
+ await db.run('INSERT INTO workspace_folders (name, project_path, model) VALUES (?, ?, ?)', [
47
+ 'legacy',
48
+ `${ROOT}-legacy`,
49
+ 'GPT-4o',
50
+ ]);
51
+ await db.run('INSERT INTO workspace_folders (name, project_path, model) VALUES (?, ?, ?)', [
52
+ 'unset',
53
+ `${ROOT}-unset`,
54
+ 'Not selected',
55
+ ]);
56
+ await db.run('INSERT INTO workspace_folders (name, project_path, model) VALUES (?, ?, ?)', [
57
+ 'nested',
58
+ `${ROOT}/nested`,
59
+ 'openai:gpt-5',
60
+ ]);
61
+ });
62
+
63
+ afterAll(() => {
64
+ db.raw.close();
65
+ removeDir(workRoot);
66
+ });
67
+
68
+ describe('projectModelForCwd', () => {
69
+ test('resolves the bound root to the composite model the picker stored', async () => {
70
+ expect(await projectModelForCwd(db, ROOT)).toEqual({
71
+ provider: 'kenari',
72
+ modelId: 'deepseek-v4-flash',
73
+ });
74
+ });
75
+
76
+ test('a cwd nested under the root (a worktree) resolves to the same project', async () => {
77
+ expect(await projectModelForCwd(db, `${ROOT}/.worktrees/feature-x`)).toEqual({
78
+ provider: 'kenari',
79
+ modelId: 'deepseek-v4-flash',
80
+ });
81
+ });
82
+
83
+ test('the schema default and a legacy display name both yield no override', async () => {
84
+ expect(await projectModelForCwd(db, `${ROOT}-unset`)).toBeNull();
85
+ // A display name cannot name a model: falling back to Kabmo's pick is
86
+ // honest, and inventing a provider would start the chat on the wrong model.
87
+ expect(await projectModelForCwd(db, `${ROOT}-legacy`)).toBeNull();
88
+ });
89
+
90
+ test('a nested workspace wins over the root that contains it', async () => {
91
+ expect(await projectModelForCwd(db, `${ROOT}/nested/crate`)).toEqual({
92
+ provider: 'openai',
93
+ modelId: 'gpt-5',
94
+ });
95
+ });
96
+
97
+ test('an unregistered cwd and an empty one yield no override', async () => {
98
+ expect(await projectModelForCwd(db, '/nowhere/at/all')).toBeNull();
99
+ expect(await projectModelForCwd(db, '')).toBeNull();
100
+ expect(await projectModelForCwd(db, null)).toBeNull();
101
+ });
102
+ });
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The default model a NEW chat inherits from the workspace it starts in.
8
+ *
9
+ * "Defaults for new chats" on a project is only a setting if the spawn reads
10
+ * it. The spawn used to fall back to Kabmo's global persisted pick and nothing
11
+ * else, so the project's model column rendered in the settings pane and in the
12
+ * sidebar payload while every chat actually started on the global pick — a
13
+ * control that promised something it never decided.
14
+ *
15
+ * Resolution is by the spawn's cwd, compared the way the sidebar compares
16
+ * folders: the row holds the spelling the user registered, while the composer
17
+ * may hand over a worktree or a symlinked path of the same project.
18
+ */
19
+
20
+ import type { DbClient } from '@/server/lib/db/client';
21
+ import { projectPathKey } from '@/server/lib/omp/core/paths';
22
+ import { parseProjectModel } from '@/shared/lib/workspace/project-model';
23
+ import type { SelectedModel } from '@/shared/types';
24
+
25
+ export async function projectModelForCwd(db: DbClient, cwd: string | null | undefined): Promise<SelectedModel | null> {
26
+ if (!cwd || !cwd.trim()) return null;
27
+
28
+ const rows = await db.all<{ model: string | null; project_path: string | null }>(
29
+ 'SELECT model, project_path FROM workspace_folders WHERE project_path IS NOT NULL ORDER BY length(project_path) DESC',
30
+ );
31
+ if (rows.length === 0) return null;
32
+
33
+ const target = projectPathKey(cwd);
34
+ const exact = rows.find((row) => row.project_path && projectPathKey(row.project_path) === target);
35
+ if (exact) return parseProjectModel(exact.model);
36
+
37
+ // A linked checkout runs outside its project root, and its own path is not
38
+ // registered — so the nearest bound root that CONTAINS it is the folder the
39
+ // chat belongs to. Longest first, so a project nested inside another
40
+ // workspace resolves to the more specific one.
41
+ const nested = rows.find((row) => {
42
+ if (!row.project_path) return false;
43
+ const root = projectPathKey(row.project_path);
44
+ return target.startsWith(`${root}/`);
45
+ });
46
+ return nested ? parseProjectModel(nested.model) : null;
47
+ }