@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,216 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The shell transport, and the reason every other module asks this one whether it
8
+ * is running inside a shell.
9
+ *
10
+ * FIVE shells speak to this page, and they do NOT all inject the same thing:
11
+ *
12
+ * - `packages/macos` / `packages/windows` / `packages/linux` install
13
+ * `window.__kabmoCall` themselves, at document start, together with
14
+ * `window.__kabmoDesktop` (their identity). Nothing in this file has to run for
15
+ * them: `installShellTransport` is a no-op when a call function already exists.
16
+ * - `packages/android` exposes only `window.kabmoHost` (a `@JavascriptInterface`),
17
+ * and `packages/ios` only `window.webkit.messageHandlers.kabmo`. Neither can
18
+ * inject script before the page, so THIS module adapts their transport into
19
+ * `__kabmoCall` — one shape for the whole console — from
20
+ * `installShellTransport()` in `main.tsx`.
21
+ *
22
+ * The split between `isDesktopShell()` and `isMobileShell()` is load-bearing, not
23
+ * bookkeeping: `titlebarInsetLeft` treats "a shell, with no identity" as a macOS
24
+ * window whose traffic lights float over the page's left edge. A phone that
25
+ * answered `isDesktopShell() === true` would reserve 5rem for controls it does
26
+ * not have and draw its wordmark 80px from the edge.
27
+ *
28
+ * Params cross the mobile transport FORM-ENCODED (`k=v&k=v`), not as JSON:
29
+ * Android's `org.json` is a stub in a JVM unit test, so a JSON wire would leave
30
+ * the parser that most needs a test as the only one that cannot have one. State
31
+ * comes back as JSON TEXT for the same reason — the native side builds one string,
32
+ * and the page parses it in the one place that has a real JSON parser.
33
+ */
34
+
35
+ /** Which shell host is answering, once one is present. */
36
+ export type ShellHostKind = 'desktop' | 'android' | 'ios';
37
+
38
+ /** What a phone's native side exposes. Android only; iOS uses WebKit messages. */
39
+ interface AndroidHost {
40
+ post: (method: string, id: string, params: string) => void;
41
+ }
42
+
43
+ declare global {
44
+ interface Window {
45
+ __kabmoCall?: (method: string, params?: Record<string, unknown>) => Promise<unknown>;
46
+ __kabmoReply?: (id: number, ok: boolean, payload: unknown) => void;
47
+ /** Set by `installShellTransport` — which host answered this page. */
48
+ __kabmoShellHost?: 'android' | 'ios';
49
+ kabmoHost?: AndroidHost;
50
+ webkit?: {
51
+ messageHandlers?: {
52
+ kabmo?: { postMessage: (message: unknown) => void };
53
+ };
54
+ };
55
+ }
56
+ }
57
+
58
+ /** The host object a phone's native side has already installed, if any. */
59
+ function detectedHost(): 'android' | 'ios' | null {
60
+ if (typeof window === 'undefined') return null;
61
+ if (window.kabmoHost) return 'android';
62
+ if (window.webkit?.messageHandlers?.kabmo) return 'ios';
63
+ return null;
64
+ }
65
+
66
+ /**
67
+ * Which shell this page is inside, or null in a browser.
68
+ *
69
+ * A desktop shell is identified by the transport it installed by itself; a phone
70
+ * by the host object its native side exposes (or by the marker
71
+ * `installShellTransport` wrote once it adapted that host).
72
+ */
73
+ export function shellHost(): ShellHostKind | null {
74
+ if (typeof window === 'undefined') return null;
75
+ const marked = window.__kabmoShellHost;
76
+ if (marked) return marked;
77
+ // The DESKTOP trio is asked FIRST, and not for tidiness: macOS and Linux post
78
+ // over `window.webkit.messageHandlers.kabmo` — the very handler name iOS uses
79
+ // — so a phone-first check read every macOS/Linux shell as `ios`,
80
+ // `isDesktopShell()` answered false, and `titlebarInsetLeft` stopped reserving
81
+ // the 5rem macOS keeps for its traffic lights. The wordmark and the drawer's
82
+ // title were drawn UNDER close / minimise / maximise.
83
+ if (window.__kabmoDesktop) return 'desktop';
84
+ if (typeof window.__kabmoCall === 'function') return 'desktop';
85
+ return detectedHost();
86
+ }
87
+
88
+ /** True once some shell answers `__kabmoCall` — desktop or a phone. */
89
+ export function hasShellBridge(): boolean {
90
+ if (typeof window === 'undefined') return false;
91
+ if (typeof window.__kabmoCall === 'function') return true;
92
+ return detectedHost() !== null;
93
+ }
94
+
95
+ /** True in the macOS / Windows / Linux shells. */
96
+ export function isDesktopShell(): boolean {
97
+ return shellHost() === 'desktop';
98
+ }
99
+
100
+ /** True in the Android / iOS shells. */
101
+ export function isMobileShell(): boolean {
102
+ const host = shellHost();
103
+ return host === 'android' || host === 'ios';
104
+ }
105
+
106
+ /** `{ label: 'NAS', port: 3000 }` → `label=NAS&port=3000`. */
107
+ function encodeParams(params: Record<string, unknown>): string {
108
+ const parts: string[] = [];
109
+ for (const [key, value] of Object.entries(params)) {
110
+ if (value === undefined) continue;
111
+ const text = value === null ? '' : String(value);
112
+ parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(text)}`);
113
+ }
114
+ return parts.join('&');
115
+ }
116
+
117
+ /**
118
+ * How long a phone's shell gets to answer one command.
119
+ *
120
+ * `servers_state` PROBES every stored URL (`GET /api/health`, 6 s each), so the
121
+ * budget has to cover a short list of unreachable servers rather than a single
122
+ * round trip. A timeout here reports the shell as unresponsive, which is the
123
+ * honest answer for a native thread that never replied.
124
+ */
125
+ const REPLY_TIMEOUT_MS = 60_000;
126
+
127
+ /**
128
+ * Adapt a phone's native transport into the `__kabmoCall` shape the console uses.
129
+ *
130
+ * Idempotent, and a no-op in a browser and in a desktop shell (both either have no
131
+ * host or already have the function). Installed before the first render, so the
132
+ * server control is drawn on the first paint.
133
+ */
134
+ export function installShellTransport(): void {
135
+ if (typeof window === 'undefined') return;
136
+ // A desktop shell installed its own transport before the page's scripts, and
137
+ // macOS/Linux expose the same WebKit handler name a phone does — so this test
138
+ // is the identity, not `detectedHost()`.
139
+ if (window.__kabmoDesktop) return;
140
+ if (typeof window.__kabmoCall === 'function') return;
141
+ const host = detectedHost();
142
+ if (!host) return;
143
+
144
+ window.__kabmoShellHost = host;
145
+
146
+ // The bare globals, not `window.setTimeout`: this file's tests install a
147
+ // minimal `window`, and the timer is the one thing they must not have to fake.
148
+ /** The handle this runtime hands back: a number in a browser, an object under Bun. */
149
+ type TimerHandle = ReturnType<typeof setTimeout>;
150
+
151
+ interface PendingReply {
152
+ resolve: (value: unknown) => void;
153
+ reject: (reason: Error) => void;
154
+ timer: TimerHandle;
155
+ }
156
+ const pending = new Map<number, PendingReply>();
157
+ let next = 1;
158
+
159
+ window.__kabmoReply = (id, ok, payload) => {
160
+ const entry = pending.get(id);
161
+ if (!entry) return;
162
+ pending.delete(id);
163
+ clearTimeout(entry.timer);
164
+ if (!ok) {
165
+ entry.reject(new Error(typeof payload === 'string' ? payload : 'The shell refused that command.'));
166
+ return;
167
+ }
168
+ // State crosses as JSON TEXT (see this module's header): an unparseable answer
169
+ // is still the shell's answer, so it resolves as-is rather than turning a
170
+ // working command into a failure.
171
+ if (typeof payload !== 'string') {
172
+ entry.resolve(payload);
173
+ return;
174
+ }
175
+ try {
176
+ entry.resolve(JSON.parse(payload));
177
+ } catch {
178
+ entry.resolve(payload);
179
+ }
180
+ };
181
+
182
+ window.__kabmoCall = (method, params) => {
183
+ const { promise, resolve, reject } = Promise.withResolvers<unknown>();
184
+ const id = next++;
185
+ const timer = setTimeout(() => {
186
+ pending.delete(id);
187
+ reject(new Error(`The shell did not answer ${method} within 60s.`));
188
+ }, REPLY_TIMEOUT_MS);
189
+ pending.set(id, { resolve, reject, timer });
190
+ const form = encodeParams(params ?? {});
191
+ if (host === 'android') {
192
+ window.kabmoHost?.post(method, String(id), form);
193
+ } else {
194
+ window.webkit?.messageHandlers?.kabmo?.postMessage({ id, method, params: form });
195
+ }
196
+ return promise;
197
+ };
198
+ }
199
+
200
+ /** One command over whichever transport this shell installed. */
201
+ export async function callShell<T>(method: string, params: Record<string, unknown> = {}): Promise<T> {
202
+ const invoke = typeof window === 'undefined' ? undefined : window.__kabmoCall;
203
+ if (!invoke) throw new Error('Not running inside a Kabmo shell.');
204
+ return (await invoke(method, params)) as T;
205
+ }
206
+
207
+ /**
208
+ * A refused command's message.
209
+ *
210
+ * The shell sends its own sentence (a refused URL, a server that exited), which is
211
+ * what the UI shows. Nothing is stripped: a message that genuinely starts with
212
+ * "Error" would lose its first word.
213
+ */
214
+ export function bridgeError(error: unknown): string {
215
+ return error instanceof Error ? error.message : String(error);
216
+ }
@@ -12,6 +12,7 @@ import { installUiKit } from '@/client/lib/plugins/kit';
12
12
  import { installScrollbarActivity } from '@/client/lib/scrollbar-activity';
13
13
  import { installBackDispatcher } from '@/client/lib/native/back';
14
14
  import { installPalettePublisher } from '@/client/lib/native/palette';
15
+ import { installShellTransport } from '@/client/lib/shell/transport';
15
16
  import { installResumeDispatcher } from '@/client/lib/native/resume';
16
17
  import { installFileLaunchHandler } from '@/client/lib/launch/file-handlers';
17
18
  import { installOpenPaths } from '@/client/lib/native/open-paths';
@@ -79,6 +80,14 @@ installBackDispatcher();
79
80
  // asks on the load it is hiding, not on a later interaction.
80
81
  installPalettePublisher();
81
82
 
83
+ // A phone's shell exposes its own transport (`window.kabmoHost` on Android,
84
+ // `window.webkit.messageHandlers.kabmo` on iOS) and cannot inject script before
85
+ // the page — so the console adapts it into `__kabmoCall` here, before the first
86
+ // render, which is what makes the header's server control appear on the first
87
+ // paint instead of after a round trip. A no-op in a browser and in the three
88
+ // desktop shells, which install `__kabmoCall` themselves.
89
+ installShellTransport();
90
+
82
91
  // The native shell calls `window.__kabmoResume()` when its app returns to the
83
92
  // foreground. A backgrounded Android WebView fires no `visibilitychange` and
84
93
  // gets no `close` for a socket the server reaped, so the shell's own lifecycle
@@ -20,7 +20,7 @@
20
20
  * a real failure (a bad ref, a dirty tree) leaves none.
21
21
  */
22
22
 
23
- import { afterEach, describe, expect, test } from 'bun:test';
23
+ import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test';
24
24
  import fs from 'node:fs';
25
25
  import os from 'node:os';
26
26
  import path from 'node:path';
@@ -28,6 +28,19 @@ import { mergeBranch, rebaseOnto } from '@/server/lib/fs/git-merge';
28
28
  import { applyStash, pushStash } from '@/server/lib/fs/git-stash';
29
29
  import { readGitState } from '@/server/lib/fs/git-state';
30
30
 
31
+ /**
32
+ * Every case here builds a real repository and drives several `git` processes
33
+ * through it (`init`, two `config`, `add`, two `commit`, `stash push`, `stash
34
+ * pop`), so Bun's 5s per-test default is a budget for the RUNNER rather than
35
+ * for the code. Measured on `windows-latest`: "applyStash resolves with the
36
+ * stash-pop state" timed out at 5011ms while the same suite is green locally in
37
+ * well under a second, and process spawn on that runner costs several times
38
+ * what it does on POSIX. A budget, not a skip: the behaviour is identical on
39
+ * both platforms. `git-actions-sync.test.ts` and the route's `git-merge.test.ts`
40
+ * set the same 30s for the same reason.
41
+ */
42
+ setDefaultTimeout(30_000);
43
+
31
44
  const repos: string[] = [];
32
45
 
33
46
  afterEach(() => {
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The stored catalog sources — the git repositories the Skills Catalog offers.
8
+ *
9
+ * Its own module because two surfaces read it (the loader's payload and every
10
+ * source mutation) and a second reader is how the two shapes would drift. The
11
+ * normalisation is the whole job: a source written by the previous UI carried
12
+ * `stars` and `updatedAt` literals that no request had produced, and a count
13
+ * that was never measured. Reading through `toCatalogSource` drops the first two
14
+ * and turns a missing count into `null` — "not scanned" — which is what the card
15
+ * prints. A guessed number is indistinguishable from a measured one once it is on
16
+ * screen, so it is never stored.
17
+ */
18
+
19
+ import type { SkillCatalogSource } from '@/shared/types';
20
+ import { DEFAULT_CATALOG_SOURCES } from '@/client/data/settings/skill';
21
+ import { readSettingsJson, writeSettingsJson } from '@/server/lib/db/settings-store';
22
+ import type { DbClient } from '@/server/lib/db/client';
23
+
24
+ export const SOURCES_KEY = 'omp_catalog_sources';
25
+
26
+ /** One stored record, narrowed to the fields this build understands. */
27
+ export function toCatalogSource(source: Partial<SkillCatalogSource>): SkillCatalogSource {
28
+ return {
29
+ id: String(source.id ?? ''),
30
+ name: String(source.name ?? source.repo ?? 'source'),
31
+ repo: String(source.repo ?? ''),
32
+ skillCount: typeof source.skillCount === 'number' ? source.skillCount : null,
33
+ scannedAt: typeof source.scannedAt === 'number' ? source.scannedAt : null,
34
+ isCustom: source.isCustom === true,
35
+ };
36
+ }
37
+
38
+ /** Every source, with the shipped defaults standing in when none is stored. */
39
+ export async function readCatalogSources(db: DbClient): Promise<SkillCatalogSource[]> {
40
+ const stored = await readSettingsJson<Partial<SkillCatalogSource>[]>(db, SOURCES_KEY, DEFAULT_CATALOG_SOURCES);
41
+ const list = Array.isArray(stored) && stored.length > 0 ? stored : DEFAULT_CATALOG_SOURCES;
42
+ // `toCatalogSource` with no id is a record this build cannot address; drop it
43
+ // rather than render a card every action would 404 on.
44
+ return list.map(toCatalogSource).filter((source) => source.id.length > 0 && source.repo.length > 0);
45
+ }
46
+
47
+ export async function writeCatalogSources(db: DbClient, sources: SkillCatalogSource[]): Promise<void> {
48
+ await writeSettingsJson(db, SOURCES_KEY, sources);
49
+ }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The WRITE half of skill import: copying the skills a user picked out of a
8
+ * cloned repository into a root Kabmo owns.
9
+ *
10
+ * The clone and the SKILL.md scan live in `skills-git-repo.ts`, because the
11
+ * inspector and the installer must agree on what a repository contains — a
12
+ * second scan here is how an installer copies a skill the list never showed.
13
+ *
14
+ * Every refusal is per skill, never per batch: one name that collides with an
15
+ * installed skill (or one directory past the size cap) is reported in `skipped`
16
+ * while the rest install, because a repository of twenty skills must not fail as
17
+ * a whole over one collision.
18
+ *
19
+ * Two properties are load-bearing:
20
+ *
21
+ * - **The destination is always `<managed root>/<validated name>`.** Nothing is
22
+ * copied to a path the repository supplied: `safeSkillDirName` refuses a
23
+ * separator, and the source directory itself is re-derived from the scan and
24
+ * checked with `withinRoot` before it is read.
25
+ * - **The source directory is copied WHOLE** (scripts, references, assets), not
26
+ * just its SKILL.md — a skill whose instructions point at `scripts/build.sh`
27
+ * is broken the moment only the markdown survives.
28
+ */
29
+
30
+ import fs from 'fs';
31
+ import { tmpdir } from 'os';
32
+ import { join } from 'path';
33
+ import { invalidateSkillCache, managedSkillRoots } from '@/server/lib/omp/config/skills';
34
+ import { MAX_SKILL_DIR_BYTES } from '@/server/lib/omp/config/skills-git-repo';
35
+ import {
36
+ scanSkillRepository,
37
+ stageClone,
38
+ toSkillRepoRef,
39
+ withinRoot,
40
+ } from '@/server/lib/omp/config/skills-git-repo';
41
+
42
+ /** The directory a skill's name sanitises to, or a refusal. */
43
+ function safeSkillDirName(name: string): string {
44
+ const trimmed = name.trim();
45
+ if (!trimmed) throw new Error('A skill has no name');
46
+ if (/[\\/]/.test(trimmed) || trimmed === '.' || trimmed === '..') {
47
+ throw new Error(`Skill name refuses a path separator: ${trimmed}`);
48
+ }
49
+ return trimmed;
50
+ }
51
+
52
+ async function dirSize(dir: string): Promise<number> {
53
+ let total = 0;
54
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true }).catch(() => []);
55
+ for (const entry of entries) {
56
+ const full = join(dir, entry.name);
57
+ if (entry.isDirectory()) total += await dirSize(full);
58
+ else if (entry.isFile()) total += await fs.promises.stat(full).then((s) => s.size).catch(() => 0);
59
+ if (total > MAX_SKILL_DIR_BYTES) return total;
60
+ }
61
+ return total;
62
+ }
63
+
64
+ export interface InstallFromRepoOptions {
65
+ scope: 'user' | 'project';
66
+ projectDir?: string | null;
67
+ /** A skill whose directory already exists is replaced, not skipped. */
68
+ overwrite?: boolean;
69
+ stagingParent?: string;
70
+ /** Test seam: read from an existing directory instead of cloning. */
71
+ sourceDir?: string;
72
+ }
73
+
74
+ export interface InstallFromRepoOutcome {
75
+ installed: string[];
76
+ skipped: Array<{ name: string; reason: string }>;
77
+ }
78
+
79
+ /**
80
+ * Copy the picked skills out of `rawUrl` into a managed root. `wantedPaths` are
81
+ * repo-relative paths exactly as the inspector reported them.
82
+ */
83
+ export async function installSkillCopies(
84
+ rawUrl: string,
85
+ wantedPaths: string[],
86
+ options: InstallFromRepoOptions,
87
+ ): Promise<InstallFromRepoOutcome> {
88
+ const ref = toSkillRepoRef(rawUrl);
89
+ if (!ref) throw new Error('Expected a git URL or an owner/repo pair');
90
+ if (options.scope === 'project' && !options.projectDir) {
91
+ throw new Error('A workspace root is required to install a project skill');
92
+ }
93
+
94
+ const stagingParent = options.stagingParent ?? tmpdir();
95
+ const staged = options.sourceDir
96
+ ? { dir: options.sourceDir, cleanup: async () => {} }
97
+ : await stageClone(ref.url, stagingParent);
98
+
99
+ const installed: string[] = [];
100
+ const skipped: Array<{ name: string; reason: string }> = [];
101
+ const wanted = new Set(wantedPaths);
102
+
103
+ try {
104
+ const entries = (await scanSkillRepository(staged.dir)).filter((entry) => wanted.has(entry.path));
105
+ if (entries.length === 0) throw new Error('None of the selected skills are in that repository');
106
+
107
+ const roots = managedSkillRoots(options.projectDir ?? null);
108
+ const root = options.scope === 'project' ? roots[1] : roots[0];
109
+ if (!root) throw new Error('A workspace root is required to install a project skill');
110
+
111
+ for (const entry of entries) {
112
+ const sourceDir = join(staged.dir, ...entry.path.split('/'));
113
+ if (!withinRoot(staged.dir, sourceDir)) {
114
+ skipped.push({ name: entry.name, reason: 'path is outside the repository' });
115
+ continue;
116
+ }
117
+ let dirName: string;
118
+ try {
119
+ dirName = safeSkillDirName(entry.name);
120
+ } catch (error) {
121
+ skipped.push({ name: entry.name, reason: error instanceof Error ? error.message : String(error) });
122
+ continue;
123
+ }
124
+ if (!entry.loadable) {
125
+ skipped.push({ name: entry.name, reason: 'SKILL.md has no description, so omp will not load it' });
126
+ continue;
127
+ }
128
+
129
+ const target = join(root, dirName);
130
+ const exists = await fs.promises.stat(target).then((s) => s.isDirectory()).catch(() => false);
131
+ if (exists && !options.overwrite) {
132
+ skipped.push({ name: entry.name, reason: 'already installed — enable overwrite to replace it' });
133
+ continue;
134
+ }
135
+ const size = await dirSize(sourceDir);
136
+ if (size > MAX_SKILL_DIR_BYTES) {
137
+ skipped.push({
138
+ name: entry.name,
139
+ reason: `skill directory is ${Math.round(size / 1024)} KB (limit ${MAX_SKILL_DIR_BYTES / 1024} KB)`,
140
+ });
141
+ continue;
142
+ }
143
+
144
+ if (exists) await fs.promises.rm(target, { recursive: true, force: true });
145
+ await fs.promises.mkdir(root, { recursive: true });
146
+ await fs.promises.cp(sourceDir, target, { recursive: true, force: true });
147
+ installed.push(entry.name);
148
+ }
149
+
150
+ if (installed.length > 0) invalidateSkillCache();
151
+ return { installed, skipped };
152
+ } finally {
153
+ await staged.cleanup();
154
+ }
155
+ }