@engenty/wizards-runtime 0.12.1 → 0.12.2

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 (91) hide show
  1. package/apps/runtime/dist/agents/studio-assistant.js +17 -1
  2. package/apps/runtime/dist/app.js +4 -2
  3. package/apps/runtime/dist/db/live-triggers.js +13 -3
  4. package/apps/runtime/dist/db/migrations/tenant/0027_space_skill.sql +48 -0
  5. package/apps/runtime/dist/db/migrations/tenant/meta/0027_snapshot.json +4120 -0
  6. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +7 -0
  7. package/apps/runtime/dist/db/schema.js +31 -0
  8. package/apps/runtime/dist/docs/dev/skills.md +116 -0
  9. package/apps/runtime/dist/docs/user-guide/skills.md +85 -0
  10. package/apps/runtime/dist/engine/steps.js +10 -1
  11. package/apps/runtime/dist/harness/model.js +4 -0
  12. package/apps/runtime/dist/live/views.js +2 -0
  13. package/apps/runtime/dist/models.js +4 -0
  14. package/apps/runtime/dist/prompts/goose.md +7 -0
  15. package/apps/runtime/dist/prompts/step.md +19 -1
  16. package/apps/runtime/dist/prompts/tools.md +33 -0
  17. package/apps/runtime/dist/routes/skills.js +84 -0
  18. package/apps/runtime/dist/services/skills-registry.js +209 -0
  19. package/apps/runtime/dist/services/skills.js +478 -0
  20. package/apps/runtime/dist/sync/records.js +81 -1
  21. package/apps/runtime/dist/texts.js +39 -0
  22. package/apps/runtime/dist/tools/index.js +4 -2
  23. package/apps/runtime/dist/tools/net-guard.js +8 -4
  24. package/apps/runtime/dist/tools/skills.js +197 -0
  25. package/apps/web/dist/assets/{AboutDialog-uGYGy2R2.js → AboutDialog-CLgnoYTI.js} +1 -1
  26. package/apps/web/dist/assets/{ChangelogDialog-BWaEdlt3.js → ChangelogDialog-CKLgFL6r.js} +1 -1
  27. package/apps/web/dist/assets/CodeEditor-B3nto_26.js +2 -0
  28. package/apps/web/dist/assets/EditorPage-D9JDdAAI.js +3 -0
  29. package/apps/web/dist/assets/{FlowPreview-DXpzFBRj.js → FlowPreview-zJCtixSi.js} +1 -1
  30. package/apps/web/dist/assets/Marketplace-D4e0Oac9.js +2 -0
  31. package/apps/web/dist/assets/{NewWizardChannels-B5wuTm7J.js → NewWizardChannels-B4N7GIYh.js} +1 -1
  32. package/apps/web/dist/assets/{NewWizardPage-Ci1ZsTJk.js → NewWizardPage-Dpt0Mzk8.js} +1 -1
  33. package/apps/web/dist/assets/{OnboardingPage-QkdluEZk.js → OnboardingPage-CDoYVjRC.js} +1 -1
  34. package/apps/web/dist/assets/PreviewPane-DPB5nEd5.js +10 -0
  35. package/apps/web/dist/assets/ProjectPage-408YOoNa.js +10 -0
  36. package/apps/web/dist/assets/{PublicRunner-Bt8gMxit.js → PublicRunner-BZ66xdRX.js} +1 -1
  37. package/apps/web/dist/assets/{ReadOnly-Cap_e5ke.js → ReadOnly-C9oGMkUB.js} +1 -1
  38. package/apps/web/dist/assets/{SettingsPage-C2rmXm_Q.js → SettingsPage-Dq3AZwJS.js} +2 -2
  39. package/apps/web/dist/assets/{SetupPage-CbqGgFPZ.js → SetupPage-CP3lbyZc.js} +1 -1
  40. package/apps/web/dist/assets/{SharePage-DEeVGatD.js → SharePage-DdMm1Y8K.js} +1 -1
  41. package/apps/web/dist/assets/SkillEditor-b5NMFB90.js +1 -0
  42. package/apps/web/dist/assets/changelog-82-DHogQ.js +1 -0
  43. package/apps/web/dist/assets/code-xml-Hx7YxCg0.js +1 -0
  44. package/apps/web/dist/assets/{dist-BwhPmMDu.js → dist-BdDd1FxP.js} +1 -1
  45. package/apps/web/dist/assets/dist-EBVTpvRr.js +10 -0
  46. package/apps/web/dist/assets/dist-GlRRx9Xl.js +1 -0
  47. package/apps/web/dist/assets/dist-H1UN89OA.js +1 -0
  48. package/apps/web/dist/assets/eye-BkMFLnYu.js +1 -0
  49. package/apps/web/dist/assets/i18n-CKKh3Pn0.js +55 -0
  50. package/apps/web/dist/assets/index-Cy2NHzAx.js +49 -0
  51. package/apps/web/dist/assets/index-wR_-1hfN.css +1 -0
  52. package/apps/web/dist/assets/json-CEsfHdlZ.js +1 -0
  53. package/apps/web/dist/assets/{lock-D-CjMpqn.js → lock-CGXM95Mi.js} +1 -1
  54. package/apps/web/dist/assets/markdown-5-I9_izp.js +29 -0
  55. package/apps/web/dist/assets/{oss-credits-CUpVhKSr.js → oss-credits-DpRWUPjD.js} +1 -1
  56. package/apps/web/dist/assets/{phone-CXSrxw3H.js → phone-DMfwuh9V.js} +1 -1
  57. package/apps/web/dist/assets/{runners-D71NjXtA.js → runners-D5qz6b_s.js} +1 -1
  58. package/apps/web/dist/assets/{session-B2LtqeDq.js → session-DRy0k0nh.js} +1 -1
  59. package/apps/web/dist/assets/{theme-Dab079EV.js → theme-DNPm6r4e.js} +2 -2
  60. package/apps/web/dist/assets/{ui-DQX_CQ7c.js → ui-CwFQAfE-.js} +2 -2
  61. package/apps/web/dist/assets/{upload-hLkuT3Q6.js → upload-DQJwLSGj.js} +1 -1
  62. package/apps/web/dist/assets/{useMutation-C3XBoSVf.js → useMutation-C20c2EH3.js} +1 -1
  63. package/apps/web/dist/assets/{volume-2-DIxdTlaA.js → volume-2-CC5qamYT.js} +1 -1
  64. package/apps/web/dist/index.html +9 -8
  65. package/apps/web/dist/mcp/flow.html +66 -66
  66. package/node_modules/@engenty/wizards/dist/plugin/studio.d.ts +3 -2
  67. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +6 -0
  68. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +6 -0
  69. package/node_modules/@engenty/wizards-shared/dist/live.d.ts +1 -1
  70. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +1 -0
  71. package/node_modules/@engenty/wizards-shared/dist/run.js +2 -0
  72. package/node_modules/@engenty/wizards-shared/dist/skills.d.ts +165 -0
  73. package/node_modules/@engenty/wizards-shared/dist/skills.js +346 -0
  74. package/node_modules/@engenty/wizards-shared/dist/sync.d.ts +4 -2
  75. package/node_modules/@engenty/wizards-shared/dist/sync.js +2 -1
  76. package/package.json +7 -7
  77. package/plugin/.claude-plugin/plugin.json +1 -1
  78. package/plugin/plugin.json +1 -1
  79. package/apps/web/dist/assets/CodeEditor-B5hV1IvK.js +0 -2
  80. package/apps/web/dist/assets/EditorPage-j9BOx5-V.js +0 -3
  81. package/apps/web/dist/assets/Marketplace-DSo6uZF6.js +0 -2
  82. package/apps/web/dist/assets/PreviewPane-swAH89un.js +0 -10
  83. package/apps/web/dist/assets/ProjectPage-Djv5EOYU.js +0 -1
  84. package/apps/web/dist/assets/changelog-DAY6ZEyy.js +0 -1
  85. package/apps/web/dist/assets/dist-DVpDdhG9.js +0 -1
  86. package/apps/web/dist/assets/dist-DzdNG7Sf.js +0 -10
  87. package/apps/web/dist/assets/i18n-B3J2ypKu.js +0 -55
  88. package/apps/web/dist/assets/index-Dxwbli0m.css +0 -1
  89. package/apps/web/dist/assets/index-WY5lJ_-h.js +0 -49
  90. package/apps/web/dist/assets/json-D2GVvTXK.js +0 -1
  91. package/apps/web/dist/assets/markdown-DwdMW7q0.js +0 -29
@@ -0,0 +1,209 @@
1
+ import { byteLength, officialSkill, SKILL_REF, } from "@engenty/wizards-shared/skills";
2
+ import { and, eq, isNotNull } from "drizzle-orm";
3
+ import { z } from "zod";
4
+ import { db, schema } from "../db/client.js";
5
+ import { requireWritableProject } from "./access.js";
6
+ import { notFound, ServiceError } from "./errors.js";
7
+ import { ownedProject } from "./projects.js";
8
+ import { asText, blobBytes, checkAlways, checkContent, contentHash, contentOf, insertSkill, keepBlobs, requireSkills, skillBytes, skillRow, } from "./skills.js";
9
+ /**
10
+ * skills.sh, the open directory of skills (docs/plans/skills.md): its search, and a skill read
11
+ * whole from its registry address `/r/<owner>/<repo>/<skill>`, which hands out the `SKILL.md`
12
+ * and the text files of the skill's folder (not fonts or images). A skill added is a copy: it
13
+ * changes only when someone takes an update, and its scripts stay off until someone switches
14
+ * them on.
15
+ */
16
+ const BASE = (process.env.SKILLS_REGISTRY_URL ?? "https://skills.sh").replace(/\/+$/, "");
17
+ /** What a registry answer may weigh: a skill of 1 MB with its JSON around it. */
18
+ const MAX_ANSWER = 5_000_000;
19
+ const down = () => new ServiceError("refused", { server: "skillsRegistryDown" });
20
+ async function getJson(path, signal) {
21
+ let res;
22
+ try {
23
+ res = await fetch(`${BASE}${path}`, {
24
+ redirect: "follow",
25
+ headers: { accept: "application/json", "user-agent": "engenty-wizards" },
26
+ signal: AbortSignal.any([AbortSignal.timeout(15_000), ...(signal ? [signal] : [])]),
27
+ });
28
+ }
29
+ catch {
30
+ throw down();
31
+ }
32
+ if (res.status === 404) {
33
+ return null;
34
+ }
35
+ if (!res.ok) {
36
+ throw down();
37
+ }
38
+ const text = await res.text();
39
+ if (text.length > MAX_ANSWER) {
40
+ throw down();
41
+ }
42
+ try {
43
+ return JSON.parse(text);
44
+ }
45
+ catch {
46
+ throw down();
47
+ }
48
+ }
49
+ const searchAnswer = z.object({
50
+ skills: z
51
+ .array(z.object({
52
+ id: z.string(),
53
+ source: z.string(),
54
+ skillId: z.string().optional(),
55
+ name: z.string(),
56
+ installs: z.number().optional(),
57
+ }))
58
+ .default([]),
59
+ });
60
+ /** Skills on skills.sh for a few words, the space's own marked as added. */
61
+ export async function searchSkills(userId, projectId, query) {
62
+ await requireSkills();
63
+ const project = await ownedProject(userId, projectId);
64
+ const q = query.trim();
65
+ if (q.length < 2) {
66
+ return { hits: [] };
67
+ }
68
+ const answer = searchAnswer.safeParse(await getJson(`/api/search?q=${encodeURIComponent(q.slice(0, 100))}&limit=40`));
69
+ if (!answer.success) {
70
+ throw down();
71
+ }
72
+ const added = new Set((await db
73
+ .select({ origin: schema.spaceSkill.origin })
74
+ .from(schema.spaceSkill)
75
+ .where(and(eq(schema.spaceSkill.projectId, project.id), isNotNull(schema.spaceSkill.origin)))).map((r) => r.origin));
76
+ const hits = answer.data.skills
77
+ .filter((s) => SKILL_REF.test(s.id))
78
+ .map((s) => ({
79
+ ref: s.id,
80
+ name: s.name,
81
+ source: s.source,
82
+ installs: s.installs ?? 0,
83
+ official: officialSkill(s.id),
84
+ added: added.has(s.id),
85
+ }));
86
+ return { hits };
87
+ }
88
+ const registryItem = z.object({
89
+ name: z.string().optional(),
90
+ description: z.string().optional(),
91
+ files: z
92
+ .array(z.object({ path: z.string(), content: z.string().nullish() }))
93
+ .max(2000)
94
+ .default([]),
95
+ });
96
+ /** A skill of skills.sh read whole: its content as the space would keep it, and what was left out. */
97
+ export async function readRegistrySkill(ref) {
98
+ if (!SKILL_REF.test(ref)) {
99
+ throw notFound();
100
+ }
101
+ const item = registryItem.safeParse(await getJson(`/r/${ref.split("/").map(encodeURIComponent).join("/")}`));
102
+ if (!item.success) {
103
+ throw new ServiceError("not_found", { server: "skillsRegistryMissing", params: { ref } });
104
+ }
105
+ const enc = new TextEncoder();
106
+ const read = contentOf(item.data.files.map((f) => {
107
+ // The registry hands out text; a file that is not came as something else (null, empty).
108
+ const data = typeof f.content === "string" ? enc.encode(f.content) : null;
109
+ return {
110
+ path: f.path.replace(/^\.?\//, ""),
111
+ text: data === null ? null : asText(data),
112
+ data,
113
+ };
114
+ }));
115
+ return { ...read, hash: contentHash(read.content) };
116
+ }
117
+ /** A skill of skills.sh to look at before it is added: everything it would bring. */
118
+ export async function previewSkill(userId, projectId, ref) {
119
+ await requireSkills();
120
+ await ownedProject(userId, projectId);
121
+ const read = await readRegistrySkill(ref);
122
+ const preview = {
123
+ ref,
124
+ name: read.content.name,
125
+ description: read.content.description,
126
+ body: read.content.body,
127
+ meta: read.content.meta,
128
+ fileList: read.content.files,
129
+ blobList: read.content.blobFiles.map((f) => ({ path: f.path, bytes: f.bytes })),
130
+ skipped: read.skipped,
131
+ official: officialSkill(ref),
132
+ bytes: skillBytes(read.content) + blobBytes(read.content.blobFiles),
133
+ hash: read.hash,
134
+ };
135
+ // What the space would refuse is said now, before anyone presses Add.
136
+ checkContent(read.content);
137
+ return preview;
138
+ }
139
+ /** Adds a skill of skills.sh to the space, as it is there now. */
140
+ export async function addRegistrySkill(userId, projectId, input) {
141
+ await requireSkills();
142
+ const project = await ownedProject(userId, projectId);
143
+ await requireWritableProject(project.id);
144
+ const read = await readRegistrySkill(input.ref);
145
+ await keepBlobs(read.blobs);
146
+ return insertSkill(project.id, read.content, {
147
+ source: "skills.sh",
148
+ mode: input.mode,
149
+ origin: input.ref,
150
+ originHash: read.hash,
151
+ rename: true,
152
+ });
153
+ }
154
+ /** What skills.sh has now for a skill added from it: null when nothing changed. */
155
+ export async function skillUpdate(userId, id) {
156
+ await requireSkills();
157
+ const row = await skillRow(id);
158
+ if (!row.origin || row.source !== "skills.sh") {
159
+ throw notFound();
160
+ }
161
+ await ownedProject(userId, row.projectId);
162
+ const read = await readRegistrySkill(row.origin);
163
+ if (read.hash === row.originHash) {
164
+ return { update: null };
165
+ }
166
+ return {
167
+ update: {
168
+ description: read.content.description,
169
+ body: read.content.body,
170
+ fileList: [
171
+ ...read.content.files.map((f) => ({ path: f.path, bytes: byteLength(f.text) })),
172
+ ...read.content.blobFiles.map((f) => ({ path: f.path, bytes: f.bytes })),
173
+ ].sort((a, b) => a.path.localeCompare(b.path)),
174
+ skipped: read.skipped,
175
+ hash: read.hash,
176
+ },
177
+ };
178
+ }
179
+ /** Takes what skills.sh has now; the skill keeps its name and when it counts. */
180
+ export async function applySkillUpdate(userId, id, hash) {
181
+ await requireSkills();
182
+ const row = await skillRow(id);
183
+ if (!row.origin || row.source !== "skills.sh") {
184
+ throw notFound();
185
+ }
186
+ await ownedProject(userId, row.projectId);
187
+ await requireWritableProject(row.projectId);
188
+ const read = await readRegistrySkill(row.origin);
189
+ // Taken only as it was shown: a change since the person looked is shown first.
190
+ if (read.hash !== hash) {
191
+ throw new ServiceError("revision_conflict", { server: "skillUpdateChanged" });
192
+ }
193
+ const next = checkContent({ ...read.content, name: row.name });
194
+ await checkAlways(row.projectId, row.id, row.mode, next.body);
195
+ await keepBlobs(read.blobs);
196
+ await db
197
+ .update(schema.spaceSkill)
198
+ .set({
199
+ description: next.description,
200
+ body: next.body,
201
+ meta: next.meta,
202
+ files: next.files,
203
+ blobFiles: next.blobFiles,
204
+ originHash: read.hash,
205
+ updatedAt: new Date(),
206
+ })
207
+ .where(eq(schema.spaceSkill.id, row.id));
208
+ return { ok: true };
209
+ }
@@ -0,0 +1,478 @@
1
+ import { createHash } from "node:crypto";
2
+ import { featureOn } from "@engenty/wizards-shared/features";
3
+ import { byteLength, officialSkill, parseSkillMd, SKILL_LIMITS, SKILL_NAME, SkillMdError, skillMd, skillPathOk, skillTextPath, } from "@engenty/wizards-shared/skills";
4
+ import { and, asc, count, eq, ne } from "drizzle-orm";
5
+ import { unzipSync, zipSync } from "fflate";
6
+ import { nanoid } from "nanoid";
7
+ import { db, schema } from "../db/client.js";
8
+ import { currentFeatures } from "../features.js";
9
+ import { getBlob, putBlob } from "../files/blobs.js";
10
+ import { currentTenant } from "../tenants/tenant.js";
11
+ import { projectWritable, requireWritableProject } from "./access.js";
12
+ import { notFound, ServiceError } from "./errors.js";
13
+ import { ownedProject } from "./projects.js";
14
+ const refuse = (server, params) => new ServiceError("invalid", { server, params });
15
+ export async function skillsOn() {
16
+ return featureOn(await currentFeatures(), "skills");
17
+ }
18
+ /** Skills are behind their switch: while it is off, they are not there. */
19
+ export async function requireSkills() {
20
+ if (!(await skillsOn())) {
21
+ throw notFound();
22
+ }
23
+ }
24
+ // --- checks ---------------------------------------------------------------------------------
25
+ const MD_ERRORS = {
26
+ frontmatter: "skillMdFrontmatter",
27
+ name: "skillMdName",
28
+ description: "skillMdDescription",
29
+ };
30
+ /** A `SKILL.md` read, its failure said in the person's words. */
31
+ export function readSkillMd(text) {
32
+ try {
33
+ return parseSkillMd(text);
34
+ }
35
+ catch (err) {
36
+ if (err instanceof SkillMdError) {
37
+ throw refuse(MD_ERRORS[err.problem]);
38
+ }
39
+ throw err;
40
+ }
41
+ }
42
+ /** The bytes of a skill's text: its `SKILL.md` and its text files. */
43
+ export function skillBytes(c) {
44
+ return byteLength(skillMd(c)) + c.files.reduce((n, f) => n + byteLength(f.text), 0);
45
+ }
46
+ /** The bytes of a skill's files for scripts. */
47
+ export const blobBytes = (files) => files.reduce((n, f) => n + f.bytes, 0);
48
+ /** What a skill may be: a name of the format, a description, files within the limits. */
49
+ export function checkContent(c) {
50
+ const name = c.name.trim();
51
+ const description = c.description.replace(/\s+/g, " ").trim();
52
+ if (name.length > SKILL_LIMITS.name || !SKILL_NAME.test(name)) {
53
+ throw refuse("skillName");
54
+ }
55
+ if (!description || description.length > SKILL_LIMITS.description) {
56
+ throw refuse("skillDescription");
57
+ }
58
+ const seen = new Set();
59
+ for (const f of c.files) {
60
+ if (!skillPathOk(f.path) || f.path === "SKILL.md" || seen.has(f.path)) {
61
+ throw refuse("skillFilePath", { path: f.path.slice(0, 120) });
62
+ }
63
+ if (!skillTextPath(f.path)) {
64
+ throw refuse("skillFileText", { path: f.path });
65
+ }
66
+ seen.add(f.path);
67
+ }
68
+ for (const f of c.blobFiles) {
69
+ if (!skillPathOk(f.path) || f.path === "SKILL.md" || seen.has(f.path)) {
70
+ throw refuse("skillFilePath", { path: f.path.slice(0, 120) });
71
+ }
72
+ seen.add(f.path);
73
+ }
74
+ const out = { ...c, name, description };
75
+ if (byteLength(skillMd(out)) > SKILL_LIMITS.skillMd ||
76
+ c.files.length > SKILL_LIMITS.files ||
77
+ c.files.some((f) => byteLength(f.text) > SKILL_LIMITS.file) ||
78
+ skillBytes(out) > SKILL_LIMITS.total ||
79
+ c.blobFiles.length > SKILL_LIMITS.blobFiles ||
80
+ c.blobFiles.some((f) => f.bytes > SKILL_LIMITS.blobFile) ||
81
+ blobBytes(c.blobFiles) > SKILL_LIMITS.blobTotal) {
82
+ throw refuse("skillTooLarge");
83
+ }
84
+ return out;
85
+ }
86
+ async function nameTaken(projectId, name, except) {
87
+ const row = await db.query.spaceSkill.findFirst({
88
+ where: and(eq(schema.spaceSkill.projectId, projectId), eq(schema.spaceSkill.name, name), ...(except ? [ne(schema.spaceSkill.id, except)] : [])),
89
+ columns: { id: true },
90
+ });
91
+ return Boolean(row);
92
+ }
93
+ /** A name not yet taken in the space: the name itself, else with `-2`, `-3` … */
94
+ async function freeName(projectId, name) {
95
+ if (!(await nameTaken(projectId, name))) {
96
+ return name;
97
+ }
98
+ for (let n = 2; n < 1000; n++) {
99
+ const suffix = `-${n}`;
100
+ const next = `${name.slice(0, SKILL_LIMITS.name - suffix.length).replace(/-+$/, "")}${suffix}`;
101
+ if (!(await nameTaken(projectId, next))) {
102
+ return next;
103
+ }
104
+ }
105
+ return `${name.slice(0, SKILL_LIMITS.name - 9)}-${nanoid(8)
106
+ .toLowerCase()
107
+ .replace(/[^a-z0-9]/g, "x")}`;
108
+ }
109
+ /**
110
+ * At most five skills always on, their instructions 20,000 characters together: each of them
111
+ * is in every AI step of the space.
112
+ */
113
+ export async function checkAlways(projectId, id, mode, body) {
114
+ if (mode !== "always") {
115
+ return;
116
+ }
117
+ const others = await db
118
+ .select({ id: schema.spaceSkill.id, body: schema.spaceSkill.body })
119
+ .from(schema.spaceSkill)
120
+ .where(and(eq(schema.spaceSkill.projectId, projectId), eq(schema.spaceSkill.mode, "always")));
121
+ const rest = others.filter((o) => o.id !== id);
122
+ if (rest.length + 1 > SKILL_LIMITS.always) {
123
+ throw refuse("skillsAlwaysCount");
124
+ }
125
+ const chars = rest.reduce((n, o) => n + o.body.length, 0) + body.length;
126
+ if (chars > SKILL_LIMITS.alwaysChars) {
127
+ throw refuse("skillsAlwaysChars", { n: chars.toLocaleString("en") });
128
+ }
129
+ }
130
+ // --- views ----------------------------------------------------------------------------------
131
+ function summaryOf(row) {
132
+ return {
133
+ id: row.id,
134
+ name: row.name,
135
+ description: row.description,
136
+ mode: row.mode,
137
+ source: row.source,
138
+ origin: row.origin,
139
+ official: row.source === "skills.sh" && officialSkill(row.origin),
140
+ runScripts: row.runScripts,
141
+ files: row.files.length + row.blobFiles.length,
142
+ chars: row.body.length,
143
+ updatedAt: row.updatedAt.toISOString(),
144
+ };
145
+ }
146
+ export async function skillRow(id) {
147
+ const row = await db.query.spaceSkill.findFirst({
148
+ where: and(eq(schema.spaceSkill.id, id), eq(schema.spaceSkill.tenantId, currentTenant())),
149
+ });
150
+ if (!row) {
151
+ throw notFound();
152
+ }
153
+ return row;
154
+ }
155
+ export async function listSkills(userId, projectId) {
156
+ await requireSkills();
157
+ const project = await ownedProject(userId, projectId);
158
+ const rows = await db.query.spaceSkill.findMany({
159
+ where: eq(schema.spaceSkill.projectId, project.id),
160
+ orderBy: [asc(schema.spaceSkill.name)],
161
+ });
162
+ return { skills: rows.map(summaryOf), readOnly: !(await projectWritable(project)) };
163
+ }
164
+ export async function getSkill(userId, id) {
165
+ await requireSkills();
166
+ const row = await skillRow(id);
167
+ const project = await ownedProject(userId, row.projectId);
168
+ return {
169
+ ...summaryOf(row),
170
+ projectId: row.projectId,
171
+ body: row.body,
172
+ meta: row.meta,
173
+ fileList: row.files,
174
+ blobList: row.blobFiles,
175
+ originHash: row.originHash,
176
+ readOnly: !(await projectWritable(project)),
177
+ };
178
+ }
179
+ // --- writes ---------------------------------------------------------------------------------
180
+ /** The hash of a skill's content, as skills.sh had it: an update is offered when it differs. */
181
+ export function contentHash(c) {
182
+ const files = [...c.files].sort((a, b) => a.path.localeCompare(b.path));
183
+ const blobs = [...c.blobFiles].sort((a, b) => a.path.localeCompare(b.path));
184
+ return createHash("sha256")
185
+ .update(JSON.stringify([
186
+ skillMd(c),
187
+ files.map((f) => [f.path, f.text]),
188
+ ...(blobs.length ? [blobs.map((f) => [f.path, f.hash])] : []),
189
+ ]))
190
+ .digest("hex");
191
+ }
192
+ /** Keeps the bytes of a skill's files for scripts, before the skill that names them is written. */
193
+ export async function keepBlobs(blobs) {
194
+ for (const data of blobs) {
195
+ await putBlob(data);
196
+ }
197
+ }
198
+ /** Puts a new skill into the space; its name is the one given, or the next free one. */
199
+ export async function insertSkill(projectId, content, options) {
200
+ const checked = checkContent(content);
201
+ const [{ n }] = await db
202
+ .select({ n: count() })
203
+ .from(schema.spaceSkill)
204
+ .where(eq(schema.spaceSkill.projectId, projectId));
205
+ if (n >= SKILL_LIMITS.perSpace) {
206
+ throw refuse("skillsTooMany");
207
+ }
208
+ const name = options.rename ? await freeName(projectId, checked.name) : checked.name;
209
+ if (!options.rename && (await nameTaken(projectId, name))) {
210
+ throw refuse("skillNameTaken", { name });
211
+ }
212
+ const mode = options.mode ?? "demand";
213
+ await checkAlways(projectId, null, mode, checked.body);
214
+ const id = nanoid(12);
215
+ await db.insert(schema.spaceSkill).values({
216
+ id,
217
+ tenantId: currentTenant(),
218
+ projectId,
219
+ name,
220
+ description: checked.description,
221
+ body: checked.body,
222
+ meta: checked.meta,
223
+ files: checked.files,
224
+ blobFiles: checked.blobFiles,
225
+ mode,
226
+ source: options.source,
227
+ origin: options.origin ?? null,
228
+ originHash: options.originHash ?? null,
229
+ });
230
+ return { id, name };
231
+ }
232
+ /** A skill written in the studio: a name, a description and a first heading. */
233
+ export async function createSkill(userId, projectId, input) {
234
+ await requireSkills();
235
+ const project = await ownedProject(userId, projectId);
236
+ await requireWritableProject(project.id);
237
+ return insertSkill(project.id, {
238
+ name: input.name,
239
+ description: input.description,
240
+ body: input.body ?? "",
241
+ meta: {},
242
+ files: [],
243
+ blobFiles: [],
244
+ }, { source: "own", mode: input.mode, rename: true });
245
+ }
246
+ /**
247
+ * Changes a skill: when it counts and whether its scripts run, always; its content only when it
248
+ * is the space's own, since one from skills.sh stays as it came (an update replaces it whole).
249
+ */
250
+ export async function updateSkill(userId, id, patch) {
251
+ await requireSkills();
252
+ const row = await skillRow(id);
253
+ await ownedProject(userId, row.projectId);
254
+ await requireWritableProject(row.projectId);
255
+ const content = { ...patch };
256
+ if (patch.skillMd !== undefined) {
257
+ Object.assign(content, readSkillMd(patch.skillMd));
258
+ }
259
+ const touches = ["name", "description", "body", "meta", "files"].some((k) => content[k] !== undefined);
260
+ if (touches && row.source === "skills.sh") {
261
+ throw refuse("skillReadOnly");
262
+ }
263
+ const next = checkContent({
264
+ name: content.name ?? row.name,
265
+ description: content.description ?? row.description,
266
+ body: content.body ?? row.body,
267
+ meta: content.meta ?? row.meta,
268
+ files: content.files ?? row.files,
269
+ blobFiles: row.blobFiles,
270
+ });
271
+ if (next.name !== row.name && (await nameTaken(row.projectId, next.name, row.id))) {
272
+ throw refuse("skillNameTaken", { name: next.name });
273
+ }
274
+ const mode = patch.mode ?? row.mode;
275
+ await checkAlways(row.projectId, row.id, mode, next.body);
276
+ await db
277
+ .update(schema.spaceSkill)
278
+ .set({ ...next, mode, runScripts: patch.runScripts ?? row.runScripts, updatedAt: new Date() })
279
+ .where(eq(schema.spaceSkill.id, row.id));
280
+ return { updatedAt: new Date().toISOString() };
281
+ }
282
+ export async function deleteSkill(userId, id) {
283
+ await requireSkills();
284
+ const row = await skillRow(id);
285
+ await ownedProject(userId, row.projectId);
286
+ await requireWritableProject(row.projectId);
287
+ await db.delete(schema.spaceSkill).where(eq(schema.spaceSkill.id, row.id));
288
+ }
289
+ /**
290
+ * A skill as the space's own: a copy to change, on demand until someone switches it on, its
291
+ * scripts off until someone switches them on for the copy.
292
+ */
293
+ export async function copySkill(userId, id) {
294
+ await requireSkills();
295
+ const row = await skillRow(id);
296
+ await ownedProject(userId, row.projectId);
297
+ await requireWritableProject(row.projectId);
298
+ return insertSkill(row.projectId, {
299
+ name: row.name,
300
+ description: row.description,
301
+ body: row.body,
302
+ meta: row.meta,
303
+ files: row.files,
304
+ blobFiles: row.blobFiles,
305
+ }, { source: "own", mode: row.mode === "always" ? "demand" : row.mode, rename: true });
306
+ }
307
+ // --- files: a SKILL.md, a zip ---------------------------------------------------------------
308
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
309
+ /** Bytes as text, or null when they are not text: not UTF-8, or a NUL among them. */
310
+ export function asText(data) {
311
+ try {
312
+ const text = utf8.decode(data);
313
+ return text.includes("\u0000") ? null : text.replace(/^/, "");
314
+ }
315
+ catch {
316
+ return null;
317
+ }
318
+ }
319
+ /**
320
+ * The files of a skill's folder as the space keeps them: its `SKILL.md` read; text a model reads
321
+ * in the skill's row while it fits; any other file, and text beyond what fits, as a file for
322
+ * scripts (bytes for the blob store); the rest named as left out.
323
+ */
324
+ export function contentOf(entries) {
325
+ const md = entries.find((e) => e.path === "SKILL.md");
326
+ if (!md || md.text === null) {
327
+ throw refuse("skillNoSkillMd");
328
+ }
329
+ const parsed = readSkillMd(md.text);
330
+ const files = [];
331
+ const blobFiles = [];
332
+ const blobs = [];
333
+ const skipped = [];
334
+ let textBytes = byteLength(skillMd(parsed));
335
+ let blobTotal = 0;
336
+ for (const e of entries) {
337
+ if (e.path === "SKILL.md") {
338
+ continue;
339
+ }
340
+ const bytes = e.data?.length ?? 0;
341
+ if (!skillPathOk(e.path)) {
342
+ skipped.push({ path: e.path, reason: "path" });
343
+ }
344
+ else if (e.text !== null &&
345
+ skillTextPath(e.path) &&
346
+ bytes <= SKILL_LIMITS.file &&
347
+ files.length < SKILL_LIMITS.files &&
348
+ textBytes + bytes <= SKILL_LIMITS.total) {
349
+ files.push({ path: e.path, text: e.text });
350
+ textBytes += bytes;
351
+ }
352
+ else if (e.data === null) {
353
+ skipped.push({ path: e.path, reason: "binary" });
354
+ }
355
+ else if (bytes > SKILL_LIMITS.blobFile || blobTotal + bytes > SKILL_LIMITS.blobTotal) {
356
+ skipped.push({ path: e.path, reason: "size" });
357
+ }
358
+ else if (blobFiles.length >= SKILL_LIMITS.blobFiles) {
359
+ skipped.push({ path: e.path, reason: "count" });
360
+ }
361
+ else {
362
+ blobFiles.push({
363
+ path: e.path,
364
+ hash: createHash("sha256").update(e.data).digest("hex"),
365
+ bytes,
366
+ });
367
+ blobs.push(e.data);
368
+ blobTotal += bytes;
369
+ }
370
+ }
371
+ files.sort((a, b) => a.path.localeCompare(b.path));
372
+ blobFiles.sort((a, b) => a.path.localeCompare(b.path));
373
+ return { content: { ...parsed, files, blobFiles }, skipped, blobs };
374
+ }
375
+ /** Never unpacked: more than this many entries, or an entry larger than a file for scripts. */
376
+ const ZIP_ENTRIES = 500;
377
+ /**
378
+ * A skill from an uploaded zip (a `.skill` is one too): the folder of its shallowest `SKILL.md`,
379
+ * paths taken relative to it. Hidden files and the Mac's resource forks stay out.
380
+ */
381
+ export function unpackSkill(data) {
382
+ let seen = 0;
383
+ let entries;
384
+ try {
385
+ entries = unzipSync(data, {
386
+ filter: (f) => {
387
+ seen++;
388
+ return (seen <= ZIP_ENTRIES && f.originalSize <= SKILL_LIMITS.blobFile && !f.name.endsWith("/"));
389
+ },
390
+ });
391
+ }
392
+ catch {
393
+ throw refuse("skillUploadKind");
394
+ }
395
+ const paths = Object.keys(entries).filter((p) => !p.split("/").some((part) => part.startsWith(".") || part === "__MACOSX"));
396
+ const md = paths
397
+ .filter((p) => p === "SKILL.md" || p.endsWith("/SKILL.md"))
398
+ .sort((a, b) => a.split("/").length - b.split("/").length)[0];
399
+ if (!md) {
400
+ throw refuse("skillNoSkillMd");
401
+ }
402
+ const root = md.slice(0, -"SKILL.md".length);
403
+ return contentOf(paths
404
+ .filter((p) => p.startsWith(root))
405
+ .map((p) => ({
406
+ path: p.slice(root.length),
407
+ text: asText(entries[p]),
408
+ data: entries[p],
409
+ })));
410
+ }
411
+ /** An uploaded `SKILL.md`, `.zip` or `.skill`, as a skill of the space. */
412
+ export async function uploadSkill(userId, projectId, file) {
413
+ await requireSkills();
414
+ const project = await ownedProject(userId, projectId);
415
+ await requireWritableProject(project.id);
416
+ const lower = file.name.toLowerCase();
417
+ let read;
418
+ if (lower.endsWith(".zip") || lower.endsWith(".skill")) {
419
+ read = unpackSkill(file.data);
420
+ }
421
+ else if (lower.endsWith(".md")) {
422
+ const text = asText(file.data);
423
+ if (text === null) {
424
+ throw refuse("skillUploadKind");
425
+ }
426
+ read = { content: { ...readSkillMd(text), files: [], blobFiles: [] }, skipped: [], blobs: [] };
427
+ }
428
+ else {
429
+ throw refuse("skillUploadKind");
430
+ }
431
+ await keepBlobs(read.blobs);
432
+ const made = await insertSkill(project.id, read.content, { source: "upload", rename: true });
433
+ return { ...made, skipped: read.skipped };
434
+ }
435
+ /** A skill as a zip: its folder, named by the skill, as other tools take it. */
436
+ export async function skillZip(userId, id) {
437
+ await requireSkills();
438
+ const row = await skillRow(id);
439
+ await ownedProject(userId, row.projectId);
440
+ const enc = new TextEncoder();
441
+ const files = {
442
+ [`${row.name}/SKILL.md`]: enc.encode(skillMd(row)),
443
+ };
444
+ for (const f of row.files) {
445
+ files[`${row.name}/${f.path}`] = enc.encode(f.text);
446
+ }
447
+ for (const f of row.blobFiles) {
448
+ files[`${row.name}/${f.path}`] = new Uint8Array(await getBlob(f.hash));
449
+ }
450
+ return { name: `${row.name}.zip`, data: zipSync(files, { level: 6 }) };
451
+ }
452
+ // --- for steps and Goose ----------------------------------------------------------------------
453
+ /** Every skill of the space, off ones too, by name: what Goose is told the space has. */
454
+ export async function skillList(projectId) {
455
+ return db
456
+ .select({
457
+ name: schema.spaceSkill.name,
458
+ description: schema.spaceSkill.description,
459
+ mode: schema.spaceSkill.mode,
460
+ })
461
+ .from(schema.spaceSkill)
462
+ .where(eq(schema.spaceSkill.projectId, projectId))
463
+ .orderBy(asc(schema.spaceSkill.name));
464
+ }
465
+ /** The space's skills that count, by mode: none while the switch is off. */
466
+ export async function activeSkills(projectId) {
467
+ if (!(await skillsOn())) {
468
+ return { always: [], demand: [] };
469
+ }
470
+ const rows = await db.query.spaceSkill.findMany({
471
+ where: and(eq(schema.spaceSkill.projectId, projectId), ne(schema.spaceSkill.mode, "off")),
472
+ orderBy: [asc(schema.spaceSkill.name)],
473
+ });
474
+ return {
475
+ always: rows.filter((r) => r.mode === "always"),
476
+ demand: rows.filter((r) => r.mode === "demand").slice(0, SKILL_LIMITS.listed),
477
+ };
478
+ }