@useavalon/caelence-agent 0.1.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 (161) hide show
  1. package/README.md +201 -0
  2. package/bin/harness.ts +10 -0
  3. package/package.json +75 -0
  4. package/skills/copy-editor/SKILL.md +74 -0
  5. package/skills/copy-editor/references/anti-slop.md +62 -0
  6. package/skills/copy-editor/references/ui-states.md +46 -0
  7. package/skills/copy-editor/scripts/lint-copy.py +78 -0
  8. package/skills/copy-harry-dry/SKILL.md +120 -0
  9. package/skills/copy-rmbc/SKILL.md +97 -0
  10. package/skills/copywriting/SKILL.md +73 -0
  11. package/skills/impeccable/SKILL.md +133 -0
  12. package/skills/impeccable/references/visual-slop.md +36 -0
  13. package/src/cli/main.test.ts +36 -0
  14. package/src/cli/main.ts +384 -0
  15. package/src/cli/media-models.ts +82 -0
  16. package/src/cli/models.ts +43 -0
  17. package/src/cli/openrouter-live.test.ts +35 -0
  18. package/src/cli/openrouter-live.ts +72 -0
  19. package/src/cli/openrouter-modality.test.ts +25 -0
  20. package/src/cli/openrouter-modality.ts +83 -0
  21. package/src/cli/picker.test.ts +53 -0
  22. package/src/cli/picker.ts +48 -0
  23. package/src/cli/plain-text.ts +15 -0
  24. package/src/cli/slash-dispatch.test.ts +213 -0
  25. package/src/cli/slash-dispatch.ts +298 -0
  26. package/src/cli/slash.test.ts +113 -0
  27. package/src/cli/slash.ts +119 -0
  28. package/src/cli/theme.test.ts +10 -0
  29. package/src/cli/theme.ts +44 -0
  30. package/src/cli/tui-layout.test.ts +33 -0
  31. package/src/cli/tui-layout.ts +33 -0
  32. package/src/cli/tui-screen.test.ts +33 -0
  33. package/src/cli/tui-screen.ts +13 -0
  34. package/src/cli/tui.tsx +735 -0
  35. package/src/config.ts +86 -0
  36. package/src/core/approval.test.ts +60 -0
  37. package/src/core/approval.ts +83 -0
  38. package/src/core/auto-router.test.ts +31 -0
  39. package/src/core/auto-router.ts +66 -0
  40. package/src/core/errors.ts +67 -0
  41. package/src/core/events.ts +85 -0
  42. package/src/core/hooks.test.ts +66 -0
  43. package/src/core/hooks.ts +94 -0
  44. package/src/core/ids.ts +6 -0
  45. package/src/core/instructions.test.ts +49 -0
  46. package/src/core/instructions.ts +44 -0
  47. package/src/core/logger.ts +45 -0
  48. package/src/core/mcp.ts +191 -0
  49. package/src/core/mode.test.ts +63 -0
  50. package/src/core/mode.ts +60 -0
  51. package/src/core/run-turn.test.ts +339 -0
  52. package/src/core/run-turn.ts +487 -0
  53. package/src/core/session.test.ts +203 -0
  54. package/src/core/session.ts +349 -0
  55. package/src/core/stdio-mcp.ts +143 -0
  56. package/src/core/strands.ts +262 -0
  57. package/src/core/usage.test.ts +69 -0
  58. package/src/core/usage.ts +171 -0
  59. package/src/desktop/bridge.test.ts +331 -0
  60. package/src/desktop/bridge.ts +729 -0
  61. package/src/desktop/open-local.test.ts +40 -0
  62. package/src/desktop/open-local.ts +52 -0
  63. package/src/desktop/preview-cache.test.ts +36 -0
  64. package/src/desktop/preview-cache.ts +63 -0
  65. package/src/desktop/secrets.test.ts +44 -0
  66. package/src/desktop/secrets.ts +60 -0
  67. package/src/evals/runner.test.ts +43 -0
  68. package/src/evals/runner.ts +225 -0
  69. package/src/index.ts +132 -0
  70. package/src/init.test.ts +54 -0
  71. package/src/init.ts +117 -0
  72. package/src/integrations/catalog-data.json +424 -0
  73. package/src/integrations/catalog.ts +81 -0
  74. package/src/integrations/connect.ts +231 -0
  75. package/src/integrations/integrations.test.ts +329 -0
  76. package/src/integrations/marks/airtable.svg +1 -0
  77. package/src/integrations/marks/algolia-mcp.svg +1 -0
  78. package/src/integrations/marks/canva.jpg +0 -0
  79. package/src/integrations/marks/cloudflare-mcp.svg +1 -0
  80. package/src/integrations/marks/contentful-mcp.svg +1 -0
  81. package/src/integrations/marks/craft.png +0 -0
  82. package/src/integrations/marks/dinero.png +0 -0
  83. package/src/integrations/marks/figma.svg +1 -0
  84. package/src/integrations/marks/gitlab.svg +1 -0
  85. package/src/integrations/marks/google-calendar.svg +1 -0
  86. package/src/integrations/marks/google-docs.svg +1 -0
  87. package/src/integrations/marks/google-drive.svg +1 -0
  88. package/src/integrations/marks/google-gmail.svg +1 -0
  89. package/src/integrations/marks/google-sheets.svg +1 -0
  90. package/src/integrations/marks/google-slides.svg +1 -0
  91. package/src/integrations/marks/granola.png +0 -0
  92. package/src/integrations/marks/jira.svg +1 -0
  93. package/src/integrations/marks/linear.svg +1 -0
  94. package/src/integrations/marks/microsoft-365.svg +7 -0
  95. package/src/integrations/marks/miro.svg +1 -0
  96. package/src/integrations/marks/mixpanel-mcp.svg +1 -0
  97. package/src/integrations/marks/monday.png +0 -0
  98. package/src/integrations/marks/mux-mcp.png +0 -0
  99. package/src/integrations/marks/neon-mcp.svg +1 -0
  100. package/src/integrations/marks/notion.svg +1 -0
  101. package/src/integrations/marks/paddle-mcp.svg +1 -0
  102. package/src/integrations/marks/posthog-mcp.svg +1 -0
  103. package/src/integrations/marks/prismic-mcp.svg +1 -0
  104. package/src/integrations/marks/replicate-mcp.svg +1 -0
  105. package/src/integrations/marks/resend-mcp.svg +1 -0
  106. package/src/integrations/marks/sanity-mcp.svg +1 -0
  107. package/src/integrations/marks/sceneplane.png +0 -0
  108. package/src/integrations/marks/sentry-mcp.svg +1 -0
  109. package/src/integrations/marks/stripe-mcp.svg +1 -0
  110. package/src/integrations/marks/supabase-mcp.svg +1 -0
  111. package/src/integrations/marks/upstash-mcp.svg +1 -0
  112. package/src/integrations/marks/vercel.svg +1 -0
  113. package/src/integrations/marks/webflow.svg +1 -0
  114. package/src/integrations/mcp-oauth.test.ts +39 -0
  115. package/src/integrations/mcp-oauth.ts +330 -0
  116. package/src/integrations/oauth-clients.test.ts +77 -0
  117. package/src/integrations/oauth-clients.ts +127 -0
  118. package/src/integrations/oauth.ts +145 -0
  119. package/src/integrations/remote-mcp.ts +307 -0
  120. package/src/integrations/store.ts +149 -0
  121. package/src/media/openrouter-generate.test.ts +80 -0
  122. package/src/media/openrouter-generate.ts +178 -0
  123. package/src/media/prefs.ts +54 -0
  124. package/src/observability/categories.ts +41 -0
  125. package/src/observability/create.test.ts +56 -0
  126. package/src/observability/create.ts +45 -0
  127. package/src/observability/experiments.ts +113 -0
  128. package/src/observability/fake.ts +191 -0
  129. package/src/observability/index.ts +57 -0
  130. package/src/observability/judges.ts +91 -0
  131. package/src/observability/langfuse.ts +275 -0
  132. package/src/observability/noop.ts +33 -0
  133. package/src/observability/observability.test.ts +113 -0
  134. package/src/observability/prompts.ts +98 -0
  135. package/src/observability/regression-items.ts +158 -0
  136. package/src/observability/sanitize.test.ts +26 -0
  137. package/src/observability/sanitize.ts +57 -0
  138. package/src/observability/types.ts +122 -0
  139. package/src/observability/version.ts +41 -0
  140. package/src/product.ts +2 -0
  141. package/src/runtime.test.ts +98 -0
  142. package/src/runtime.ts +438 -0
  143. package/src/skills/author-skill.ts +49 -0
  144. package/src/skills/create-skill.test.ts +108 -0
  145. package/src/skills/create-skill.ts +70 -0
  146. package/src/skills/loader.test.ts +122 -0
  147. package/src/skills/loader.ts +162 -0
  148. package/src/skills/registry.test.ts +190 -0
  149. package/src/skills/registry.ts +402 -0
  150. package/src/skills/skill-command.ts +53 -0
  151. package/src/skills/user-dir.ts +8 -0
  152. package/src/tools/git.test.ts +71 -0
  153. package/src/tools/git.ts +126 -0
  154. package/src/tools/local.ts +258 -0
  155. package/src/tools/paths.test.ts +24 -0
  156. package/src/tools/paths.ts +39 -0
  157. package/src/tools/read-skill.ts +43 -0
  158. package/src/tools/subagent.test.ts +77 -0
  159. package/src/tools/subagent.ts +74 -0
  160. package/src/tools/todo.test.ts +25 -0
  161. package/src/tools/todo.ts +70 -0
@@ -0,0 +1,402 @@
1
+ import { cpSync, existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { listBundledSkills, parseSkillMarkdown } from "./loader.ts";
4
+
5
+ /** Bare names that install more than one catalog folder. */
6
+ export const BUNDLED_PACKS: Record<string, readonly string[]> = {
7
+ copy: ["copywriting", "copy-rmbc", "copy-harry-dry", "copy-editor"],
8
+ copywriting: ["copywriting", "copy-rmbc", "copy-harry-dry", "copy-editor"],
9
+ };
10
+
11
+ const SEARCH_URL = (process.env.SKILLS_API_URL?.trim() || "https://skills.sh").replace(/\/+$/, "");
12
+ const MAX_FILES = 40;
13
+ const MAX_FILE_BYTES = 512 * 1024;
14
+
15
+ export interface RegistryHit {
16
+ name: string;
17
+ source: string;
18
+ installs?: number;
19
+ id: string;
20
+ }
21
+
22
+ export interface ParsedSkillSource {
23
+ owner: string;
24
+ repo: string;
25
+ skill?: string;
26
+ path?: string;
27
+ ref: string;
28
+ }
29
+
30
+ export type FetchLike = (url: string, init?: RequestInit) => Promise<Response>;
31
+
32
+ export function parseSkillSource(
33
+ raw: string,
34
+ ): ParsedSkillSource | { url: string } | { error: string } {
35
+ const value = raw.trim();
36
+ if (!value) return { error: "Source is empty." };
37
+
38
+ const skillsSh = /^https?:\/\/(?:www\.)?skills\.sh\/([^?#]+)$/i.exec(value);
39
+ if (skillsSh?.[1]?.includes("/")) {
40
+ return parseSkillSource(skillsSh[1].replace(/\/+$/, ""));
41
+ }
42
+
43
+ if (/^https?:\/\//i.test(value)) {
44
+ const github =
45
+ /^https?:\/\/github\.com\/([^/]+)\/([^/]+)(?:\/(?:tree|blob)\/([^/]+)(?:\/(.*))?)?/i.exec(
46
+ value,
47
+ );
48
+ if (github) {
49
+ const path = github[4]?.replace(/\/SKILL\.md$/i, "").replace(/\/+$/, "");
50
+ return {
51
+ owner: github[1] ?? "",
52
+ repo: (github[2] ?? "").replace(/\.git$/, ""),
53
+ ref: github[3] || "HEAD",
54
+ ...(path ? { path } : {}),
55
+ ...(path ? { skill: path.split("/").pop() } : {}),
56
+ };
57
+ }
58
+ const rawGh = /^https?:\/\/raw\.githubusercontent\.com\/([^/]+)\/([^/]+)\/([^/]+)\/(.*)$/i.exec(
59
+ value,
60
+ );
61
+ if (rawGh) {
62
+ const path = (rawGh[4] ?? "").replace(/\/SKILL\.md$/i, "");
63
+ return {
64
+ owner: rawGh[1] ?? "",
65
+ repo: rawGh[2] ?? "",
66
+ ref: rawGh[3] || "HEAD",
67
+ ...(path ? { path } : {}),
68
+ };
69
+ }
70
+ return { url: value };
71
+ }
72
+
73
+ const at = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)@([A-Za-z0-9_./-]+)$/.exec(value);
74
+ if (at) {
75
+ return { owner: at[1] ?? "", repo: at[2] ?? "", skill: at[3], ref: "HEAD" };
76
+ }
77
+ const repo = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:\/(.+))?$/.exec(value);
78
+ if (repo) {
79
+ const path = repo[3]?.replace(/\/+$/, "");
80
+ return {
81
+ owner: repo[1] ?? "",
82
+ repo: repo[2] ?? "",
83
+ ref: "HEAD",
84
+ ...(path ? { path, skill: path.split("/").pop() } : {}),
85
+ };
86
+ }
87
+ return {
88
+ error: "Use a bundled name, owner/repo, owner/repo@skill, or a GitHub / skills.sh URL.",
89
+ };
90
+ }
91
+
92
+ export function parseBundledSkillRef(raw: string): string | undefined {
93
+ const value = raw.trim();
94
+ if (!value) return undefined;
95
+ const tagged = /^(?:bundled[@/])([A-Za-z0-9_.-]+)$/i.exec(value);
96
+ if (tagged?.[1]) return tagged[1];
97
+ if (/^[A-Za-z0-9_.-]+$/.test(value)) return value;
98
+ return undefined;
99
+ }
100
+
101
+ export function bundledInstallNames(name: string): string[] | undefined {
102
+ const key = name.trim().toLowerCase();
103
+ if (!key) return undefined;
104
+ const pack = BUNDLED_PACKS[key];
105
+ if (pack) return [...pack];
106
+ const found = listBundledSkills().find((skill) => skill.name.toLowerCase() === key);
107
+ return found ? [found.name] : undefined;
108
+ }
109
+
110
+ export function bundledRegistryHits(query: string): RegistryHit[] {
111
+ const q = query.trim().toLowerCase();
112
+ const seen = new Set<string>();
113
+ const hits: RegistryHit[] = [];
114
+ for (const pack of Object.keys(BUNDLED_PACKS)) {
115
+ if (pack === "copy") continue;
116
+ const members = BUNDLED_PACKS[pack] ?? [];
117
+ if (
118
+ q &&
119
+ q !== "bundled" &&
120
+ !pack.includes(q) &&
121
+ !members.some((member) => member.includes(q))
122
+ ) {
123
+ continue;
124
+ }
125
+ seen.add(pack);
126
+ hits.push({ id: `bundled/${pack}`, name: pack, source: "bundled" });
127
+ }
128
+ for (const skill of listBundledSkills()) {
129
+ const key = skill.name.toLowerCase();
130
+ if (q && q !== "bundled" && !key.includes(q)) continue;
131
+ if (seen.has(key)) continue;
132
+ seen.add(key);
133
+ hits.push({ id: `bundled/${skill.name}`, name: skill.name, source: "bundled" });
134
+ }
135
+ return hits;
136
+ }
137
+
138
+ export function formatBundledHits(hits: RegistryHit[]): string {
139
+ return hits.map((hit) => `bundled@${hit.name}`).join("\n");
140
+ }
141
+
142
+ export async function searchSkills(query: string, fetchFn: FetchLike = fetch): Promise<string> {
143
+ const bundled = formatBundledHits(bundledRegistryHits(query));
144
+ try {
145
+ const remote = await searchSkillsSh(query, fetchFn);
146
+ const remoteText = remote.length > 0 ? formatRegistryHits(remote) : "";
147
+ return [bundled, remoteText].filter(Boolean).join("\n") || "No matches.";
148
+ } catch (err) {
149
+ if (bundled) return bundled;
150
+ return err instanceof Error ? err.message : String(err);
151
+ }
152
+ }
153
+
154
+ export function installBundledSkills(
155
+ name: string,
156
+ destRoot: string,
157
+ ): { name: string; rel: string; installed: string[] } | { error: string; choices?: string[] } {
158
+ const names = bundledInstallNames(name);
159
+ const catalog = listBundledSkills();
160
+ if (!names) {
161
+ const choices = [
162
+ ...Object.keys(BUNDLED_PACKS).filter((key) => key !== "copy"),
163
+ ...catalog.map((skill) => skill.name),
164
+ ].filter((value, index, all) => all.indexOf(value) === index);
165
+ return { error: `No bundled skill ${JSON.stringify(name)}.`, choices };
166
+ }
167
+ const byName = new Map(catalog.map((skill) => [skill.name.toLowerCase(), skill]));
168
+ const installed: string[] = [];
169
+ for (const entry of names) {
170
+ const skill = byName.get(entry.toLowerCase());
171
+ if (!skill) return { error: `Bundled skill ${entry} is missing from the package.` };
172
+ const slug = skill.name
173
+ .trim()
174
+ .toLowerCase()
175
+ .replace(/[^a-z0-9-]+/g, "-")
176
+ .replace(/^-|-$/g, "");
177
+ if (!slug) return { error: "Skill name is empty." };
178
+ const dest = join(destRoot, slug);
179
+ try {
180
+ rmSync(dest, { recursive: true, force: true });
181
+ cpSync(dirname(skill.path), dest, { recursive: true });
182
+ } catch (err) {
183
+ return { error: err instanceof Error ? err.message : String(err) };
184
+ }
185
+ installed.push(slug);
186
+ }
187
+ const first = installed[0] ?? name;
188
+ return { name: first, rel: `${first}/SKILL.md`, installed };
189
+ }
190
+
191
+ export async function searchSkillsSh(
192
+ query: string,
193
+ fetchFn: FetchLike = fetch,
194
+ ): Promise<RegistryHit[]> {
195
+ const q = query.trim();
196
+ if (!q) return [];
197
+ const url = `${SEARCH_URL}/api/search?${new URLSearchParams({ q, limit: "10" }).toString()}`;
198
+ const res = await fetchFn(url, { headers: { accept: "application/json" } });
199
+ if (!res.ok) throw new Error(`skills.sh search failed (${res.status})`);
200
+ const data = (await res.json()) as {
201
+ skills?: Array<{ id?: string; name?: string; source?: string; installs?: number }>;
202
+ };
203
+ return (data.skills ?? [])
204
+ .map((row) => ({
205
+ id: String(row.id ?? row.name ?? ""),
206
+ name: String(row.name ?? row.id ?? ""),
207
+ source: String(row.source ?? ""),
208
+ ...(typeof row.installs === "number" ? { installs: row.installs } : {}),
209
+ }))
210
+ .filter((row) => row.name && row.source);
211
+ }
212
+
213
+ export function formatRegistryHits(hits: RegistryHit[]): string {
214
+ if (hits.length === 0) return "No skills.sh matches.";
215
+ return hits
216
+ .map((hit) => {
217
+ const count = hit.installs !== undefined ? ` ${hit.installs}` : "";
218
+ return `${hit.source}@${hit.name}${count}`;
219
+ })
220
+ .join("\n");
221
+ }
222
+
223
+ export async function installSkillFromSource(input: {
224
+ source: string;
225
+ skill?: string;
226
+ destRoot: string;
227
+ fetchFn?: FetchLike;
228
+ }): Promise<
229
+ { name: string; rel: string; installed?: string[] } | { error: string; choices?: string[] }
230
+ > {
231
+ const bundledName = parseBundledSkillRef(input.source);
232
+ if (bundledName && !input.skill) {
233
+ return installBundledSkills(bundledName, input.destRoot);
234
+ }
235
+ const parsed = parseSkillSource(input.source);
236
+ if ("error" in parsed) return parsed;
237
+ if ("url" in parsed)
238
+ return installFromDirectUrl(parsed.url, input.destRoot, input.fetchFn ?? fetch);
239
+ const skill = input.skill?.trim() || parsed.skill;
240
+ return installFromGithub({
241
+ ...parsed,
242
+ skill,
243
+ destRoot: input.destRoot,
244
+ fetchFn: input.fetchFn ?? fetch,
245
+ });
246
+ }
247
+
248
+ async function installFromDirectUrl(
249
+ url: string,
250
+ destRoot: string,
251
+ fetchFn: FetchLike,
252
+ ): Promise<{ name: string; rel: string } | { error: string }> {
253
+ const res = await fetchFn(url);
254
+ if (!res.ok) return { error: `Download failed (${res.status})` };
255
+ const markdown = await res.text();
256
+ if (!markdown.includes("name:") || !markdown.includes("---")) {
257
+ return { error: "URL is not a SKILL.md." };
258
+ }
259
+ const parsed = parseSkillMarkdown(markdown, "SKILL.md", ".");
260
+ return writeSkillDir(destRoot, parsed.name, { "SKILL.md": markdown });
261
+ }
262
+
263
+ async function installFromGithub(
264
+ input: ParsedSkillSource & {
265
+ destRoot: string;
266
+ fetchFn: FetchLike;
267
+ skill?: string;
268
+ },
269
+ ): Promise<{ name: string; rel: string } | { error: string; choices?: string[] }> {
270
+ const treeUrl = `https://api.github.com/repos/${input.owner}/${input.repo}/git/trees/${input.ref}?recursive=1`;
271
+ const res = await input.fetchFn(treeUrl, {
272
+ headers: {
273
+ accept: "application/vnd.github+json",
274
+ "user-agent": "caelence-harness",
275
+ },
276
+ });
277
+ if (!res.ok)
278
+ return { error: `GitHub tree failed (${res.status}) for ${input.owner}/${input.repo}` };
279
+ const data = (await res.json()) as { tree?: Array<{ path?: string; type?: string }> };
280
+ const skillFiles = (data.tree ?? [])
281
+ .map((node) => node.path ?? "")
282
+ .filter((path) => path.endsWith("/SKILL.md") || path === "SKILL.md")
283
+ .filter(
284
+ (path) => !path.split("/").some((part) => part === "node_modules" || part === "examples"),
285
+ );
286
+ if (skillFiles.length === 0) return { error: `No SKILL.md in ${input.owner}/${input.repo}` };
287
+
288
+ const wanted = input.skill?.toLowerCase() || input.path?.split("/").pop()?.toLowerCase();
289
+ const matches = wanted
290
+ ? skillFiles.filter((path) => {
291
+ const folder = dirname(path) === "." ? input.repo : dirname(path).split("/").pop();
292
+ return (
293
+ folder?.toLowerCase() === wanted ||
294
+ path.toLowerCase() === `${wanted}/skill.md` ||
295
+ path.toLowerCase().endsWith(`/${wanted}/skill.md`) ||
296
+ (input.path && path.toLowerCase().startsWith(`${input.path.toLowerCase()}/`))
297
+ );
298
+ })
299
+ : skillFiles;
300
+
301
+ if (matches.length === 0) {
302
+ return {
303
+ error: `No skill ${JSON.stringify(input.skill)} in ${input.owner}/${input.repo}.`,
304
+ choices: skillFiles.map((path) =>
305
+ dirname(path) === "." ? input.repo : (dirname(path).split("/").pop() ?? path),
306
+ ),
307
+ };
308
+ }
309
+ if (matches.length > 1 && !wanted) {
310
+ return {
311
+ error: "Repo has several skills. Add @name.",
312
+ choices: matches.map((path) =>
313
+ dirname(path) === "." ? input.repo : (dirname(path).split("/").pop() ?? path),
314
+ ),
315
+ };
316
+ }
317
+
318
+ const skillMd = matches[0] ?? "";
319
+ const root = dirname(skillMd) === "." ? "" : dirname(skillMd);
320
+ const files = (data.tree ?? [])
321
+ .map((node) => node.path ?? "")
322
+ .filter(
323
+ (path) => path && (root ? path === root || path.startsWith(`${root}/`) : path === "SKILL.md"),
324
+ );
325
+ if (files.length > MAX_FILES) return { error: `Skill has more than ${MAX_FILES} files.` };
326
+
327
+ const downloaded: Record<string, string> = {};
328
+ for (const path of files) {
329
+ if (!path.endsWith(".md") && !path.endsWith(".txt") && path !== skillMd) continue;
330
+ const raw = `https://raw.githubusercontent.com/${input.owner}/${input.repo}/${input.ref}/${path}`;
331
+ const file = await input.fetchFn(raw, { headers: { "user-agent": "caelence-harness" } });
332
+ if (!file.ok) continue;
333
+ const text = await file.text();
334
+ if (text.length > MAX_FILE_BYTES) return { error: `File too large: ${path}` };
335
+ const rel = root ? path.slice(root.length + 1) : path;
336
+ if (!rel || rel.includes("..")) continue;
337
+ downloaded[rel] = text;
338
+ }
339
+ const markdown = downloaded["SKILL.md"];
340
+ if (!markdown) return { error: "Could not download SKILL.md." };
341
+ const name = parseSkillMarkdown(markdown, "SKILL.md", ".").name;
342
+ return writeSkillDir(input.destRoot, name, downloaded);
343
+ }
344
+
345
+ function writeSkillDir(
346
+ destRoot: string,
347
+ name: string,
348
+ files: Record<string, string>,
349
+ ): { name: string; rel: string } | { error: string } {
350
+ const slug = name
351
+ .trim()
352
+ .toLowerCase()
353
+ .replace(/[^a-z0-9-]+/g, "-")
354
+ .replace(/^-|-$/g, "");
355
+ if (!slug) return { error: "Skill name is empty." };
356
+ const dest = join(destRoot, slug);
357
+ try {
358
+ rmSync(dest, { recursive: true, force: true });
359
+ mkdirSync(dest, { recursive: true });
360
+ for (const [rel, body] of Object.entries(files)) {
361
+ const abs = join(dest, rel);
362
+ if (!abs.startsWith(dest)) continue;
363
+ mkdirSync(dirname(abs), { recursive: true });
364
+ writeFileSync(abs, body, "utf8");
365
+ }
366
+ } catch (err) {
367
+ return { error: err instanceof Error ? err.message : String(err) };
368
+ }
369
+ return { name: slug, rel: `${slug}/SKILL.md` };
370
+ }
371
+
372
+ export function removeInstalledSkill(
373
+ destRoot: string,
374
+ name: string,
375
+ ): { removed: boolean; reason?: string } {
376
+ const slug = name.trim().toLowerCase();
377
+ if (!slug) return { removed: false, reason: "Name is empty." };
378
+ const dest = join(destRoot, slug);
379
+ if (!existsSync(dest)) return { removed: false, reason: "Not installed." };
380
+ try {
381
+ rmSync(dest, { recursive: true, force: true });
382
+ return { removed: true };
383
+ } catch (err) {
384
+ return { removed: false, reason: err instanceof Error ? err.message : String(err) };
385
+ }
386
+ }
387
+
388
+ export function removeSkillFromRoots(
389
+ name: string,
390
+ roots: string[],
391
+ ): { removed: boolean; reason?: string } {
392
+ const names = bundledInstallNames(name) ?? [name];
393
+ let removed = 0;
394
+ for (const entry of names) {
395
+ for (const root of roots) {
396
+ if (removeInstalledSkill(root, entry).removed) removed += 1;
397
+ }
398
+ }
399
+ if (removed === 0)
400
+ return { removed: false, reason: `Skill ${JSON.stringify(name)} is not installed.` };
401
+ return { removed: true };
402
+ }
@@ -0,0 +1,53 @@
1
+ import { parseSkillNewArgs } from "./create-skill.ts";
2
+
3
+ export const SKILL_COMMAND_USAGE = [
4
+ "/skill find [query]",
5
+ "/skill add <name or owner/repo@skill>",
6
+ "/skill add --project <name or owner/repo@skill>",
7
+ "/skill new <name> <what it should do>",
8
+ "/skill remove <name>",
9
+ ].join("\n");
10
+
11
+ export type SkillCommand =
12
+ | { action: "find"; query: string }
13
+ | { action: "add"; source: string; skill?: string; scope: "user" | "project" }
14
+ | { action: "new"; name: string; brief: string }
15
+ | { action: "remove"; name: string };
16
+
17
+ export function parseSkillCommand(raw: string): SkillCommand | { error: string } {
18
+ const tokens = raw.trim().split(/\s+/).filter(Boolean);
19
+ const verb = tokens[0]?.toLowerCase();
20
+ if (!verb) return { error: SKILL_COMMAND_USAGE };
21
+
22
+ if (verb === "find" || verb === "search") {
23
+ return { action: "find", query: tokens.slice(1).join(" ").trim() };
24
+ }
25
+
26
+ if (verb === "add" || verb === "install") {
27
+ let scope: "user" | "project" = "user";
28
+ const rest: string[] = [];
29
+ for (const token of tokens.slice(1)) {
30
+ if (token === "--project" || token === "-p") scope = "project";
31
+ else if (token === "--user" || token === "-g") scope = "user";
32
+ else rest.push(token);
33
+ }
34
+ const source = rest[0];
35
+ if (!source) return { error: "/skill add <name or owner/repo@skill>" };
36
+ const skill = rest[1];
37
+ return { action: "add", source, scope, ...(skill ? { skill } : {}) };
38
+ }
39
+
40
+ if (verb === "remove" || verb === "rm") {
41
+ const name = tokens[1];
42
+ if (!name) return { error: "/skill remove <name>" };
43
+ return { action: "remove", name };
44
+ }
45
+
46
+ if (verb === "new") {
47
+ const parsed = parseSkillNewArgs(raw);
48
+ if ("error" in parsed) return parsed;
49
+ return { action: "new", name: parsed.name, brief: parsed.brief };
50
+ }
51
+
52
+ return { error: SKILL_COMMAND_USAGE };
53
+ }
@@ -0,0 +1,8 @@
1
+ import { homedir } from "node:os";
2
+ import { resolve } from "node:path";
3
+
4
+ export function userSkillsDir(env: Record<string, string | undefined> = process.env): string {
5
+ const override = env.HARNESS_USER_SKILLS?.trim();
6
+ if (override) return resolve(override);
7
+ return resolve(homedir(), ".harness", "skills");
8
+ }
@@ -0,0 +1,71 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { createMcpServer } from "../core/mcp.ts";
6
+ import { createGitTools } from "./git.ts";
7
+
8
+ async function git(cwd: string, args: string[]): Promise<void> {
9
+ const proc = Bun.spawn(["git", ...args], {
10
+ cwd,
11
+ stdout: "pipe",
12
+ stderr: "pipe",
13
+ env: { ...process.env, GIT_EDITOR: "true", GIT_TERMINAL_PROMPT: "0" },
14
+ });
15
+ const exit = await proc.exited;
16
+ if (exit !== 0) {
17
+ const err = await new Response(proc.stderr).text();
18
+ throw new Error(err || `git ${args.join(" ")} failed`);
19
+ }
20
+ }
21
+
22
+ async function repo(): Promise<string> {
23
+ const cwd = await mkdtemp(join(tmpdir(), "harness-git-"));
24
+ const template = await mkdtemp(join(tmpdir(), "harness-git-template-"));
25
+ try {
26
+ await git(cwd, ["init", `--template=${template}`]);
27
+ } finally {
28
+ await rm(template, { recursive: true, force: true });
29
+ }
30
+ await git(cwd, ["config", "user.email", "harness@example.com"]);
31
+ await git(cwd, ["config", "user.name", "Harness"]);
32
+ return cwd;
33
+ }
34
+
35
+ describe("git tools", () => {
36
+ test("status, diff, log, and path-bound commit", async () => {
37
+ const cwd = await repo();
38
+ try {
39
+ const mcp = createMcpServer(createGitTools(cwd));
40
+ await writeFile(join(cwd, "a.txt"), "one\n", "utf8");
41
+ const status = await mcp.callTool("git_status", {});
42
+ expect(status.isError).toBeFalsy();
43
+ expect(status.content[0]?.text).toContain("a.txt");
44
+
45
+ const denied = await mcp.callTool("git_diff", { path: "../secret" });
46
+ expect(denied.isError).toBe(true);
47
+
48
+ const commitEscape = await mcp.callTool("git_commit", {
49
+ message: "nope",
50
+ paths: ["../secret"],
51
+ });
52
+ expect(commitEscape.isError).toBe(true);
53
+
54
+ const committed = await mcp.callTool("git_commit", {
55
+ message: "add a",
56
+ paths: ["a.txt"],
57
+ });
58
+ expect(committed.isError).toBeFalsy();
59
+ expect(committed.structuredContent).toMatchObject({ committed: true, message: "add a" });
60
+
61
+ await writeFile(join(cwd, "b.txt"), "two\n", "utf8");
62
+ const empty = await mcp.callTool("git_commit", { message: "nothing staged" });
63
+ expect(empty.isError).toBe(true);
64
+
65
+ const log = await mcp.callTool("git_log", { max: 5 });
66
+ expect(log.content[0]?.text).toContain("add a");
67
+ } finally {
68
+ await rm(cwd, { recursive: true, force: true });
69
+ }
70
+ });
71
+ });
@@ -0,0 +1,126 @@
1
+ import { errorResult, jsonResult, type McpToolDefinition, textResult } from "../core/mcp.ts";
2
+ import { resolveUnderCwd } from "./paths.ts";
3
+
4
+ const GIT_TIMEOUT_MS = 30_000;
5
+
6
+ async function git(
7
+ cwd: string,
8
+ args: string[],
9
+ ): Promise<{ exit: number; stdout: string; stderr: string }> {
10
+ const proc = Bun.spawn(["git", ...args], {
11
+ cwd,
12
+ stdout: "pipe",
13
+ stderr: "pipe",
14
+ env: { ...process.env, GIT_EDITOR: "true", GIT_TERMINAL_PROMPT: "0" },
15
+ });
16
+ const timer = setTimeout(() => proc.kill(), GIT_TIMEOUT_MS);
17
+ try {
18
+ const [stdout, stderr, exit] = await Promise.all([
19
+ new Response(proc.stdout).text(),
20
+ new Response(proc.stderr).text(),
21
+ proc.exited,
22
+ ]);
23
+ return { exit, stdout: stdout.slice(0, 32_000), stderr: stderr.slice(0, 8_000) };
24
+ } finally {
25
+ clearTimeout(timer);
26
+ }
27
+ }
28
+
29
+ function asString(value: unknown): string {
30
+ return typeof value === "string" ? value : "";
31
+ }
32
+
33
+ export function createGitTools(cwd: string): McpToolDefinition[] {
34
+ return [
35
+ {
36
+ name: "git_status",
37
+ description: "Show branch and porcelain status. Prefer this over exec git status.",
38
+ inputSchema: { type: "object", properties: {} },
39
+ async handler() {
40
+ const result = await git(cwd, ["status", "--porcelain=v1", "-b"]);
41
+ if (result.exit !== 0) return errorResult(result.stderr.trim() || "git status failed");
42
+ return textResult(result.stdout || "clean");
43
+ },
44
+ },
45
+ {
46
+ name: "git_diff",
47
+ description: "Show the working tree or staged diff. Optional project-relative path.",
48
+ inputSchema: {
49
+ type: "object",
50
+ properties: {
51
+ path: { type: "string" },
52
+ staged: { type: "boolean" },
53
+ },
54
+ },
55
+ async handler(raw) {
56
+ const args = ["diff"];
57
+ if (raw.staged === true) args.push("--cached");
58
+ if (typeof raw.path === "string" && raw.path.trim()) {
59
+ try {
60
+ resolveUnderCwd(cwd, raw.path);
61
+ } catch (err) {
62
+ return errorResult(err instanceof Error ? err.message : String(err));
63
+ }
64
+ args.push("--", raw.path.trim());
65
+ }
66
+ const result = await git(cwd, args);
67
+ if (result.exit !== 0) return errorResult(result.stderr.trim() || "git diff failed");
68
+ return textResult(result.stdout || "no diff");
69
+ },
70
+ },
71
+ {
72
+ name: "git_log",
73
+ description: "Recent commits, oneline. Default 20.",
74
+ inputSchema: {
75
+ type: "object",
76
+ properties: {
77
+ max: { type: "number", description: "Commit cap (default 20, max 50)." },
78
+ },
79
+ },
80
+ async handler(raw) {
81
+ const max =
82
+ typeof raw.max === "number" && Number.isFinite(raw.max)
83
+ ? Math.min(50, Math.max(1, Math.floor(raw.max)))
84
+ : 20;
85
+ const result = await git(cwd, ["log", `-n${max}`, "--oneline"]);
86
+ if (result.exit !== 0) return errorResult(result.stderr.trim() || "git log failed");
87
+ return textResult(result.stdout || "no commits");
88
+ },
89
+ },
90
+ {
91
+ name: "git_commit",
92
+ description:
93
+ "Commit already-staged files, or the listed project-relative paths. Does not push. Requires approval.",
94
+ inputSchema: {
95
+ type: "object",
96
+ properties: {
97
+ message: { type: "string" },
98
+ paths: { type: "array", items: { type: "string" } },
99
+ },
100
+ required: ["message"],
101
+ },
102
+ async handler(raw) {
103
+ const message = asString(raw.message).trim();
104
+ if (!message) return errorResult("message is empty");
105
+ const paths = Array.isArray(raw.paths)
106
+ ? raw.paths.filter((p): p is string => typeof p === "string" && p.trim().length > 0)
107
+ : [];
108
+ for (const path of paths) {
109
+ try {
110
+ resolveUnderCwd(cwd, path);
111
+ } catch (err) {
112
+ return errorResult(err instanceof Error ? err.message : String(err));
113
+ }
114
+ }
115
+ if (paths.length > 0) {
116
+ const add = await git(cwd, ["add", "--", ...paths]);
117
+ if (add.exit !== 0) return errorResult(add.stderr.trim() || "git add failed");
118
+ }
119
+ const result = await git(cwd, ["commit", "-m", message]);
120
+ if (result.exit !== 0)
121
+ return errorResult(result.stderr.trim() || result.stdout.trim() || "git commit failed");
122
+ return jsonResult({ committed: true, message, stdout: result.stdout.trim() });
123
+ },
124
+ },
125
+ ];
126
+ }