Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(skills): generate importable skill drafts from an OpenAPI spec or GitHub repo
nirholasd7bcabdcc42a
diff --git a/api/_lib/migrations/20261015130000_openapi_skill_imports.sql b/api/_lib/migrations/20261015130000_openapi_skill_imports.sqlnew file mode 100644index 000000000..67aca889c--- /dev/null+++ b/api/_lib/migrations/20261015130000_openapi_skill_imports.sql@@ -0,0 +1,28 @@+-- Draft skills generated by @three-ws/skill-import (packages/skill-import)+-- from an OpenAPI/Swagger spec or a GitHub repository. This is a different+-- table from skill_import_registries/skill_import_requests (api/skill-imports.js,+-- docs/skill-import.md): that system imports prompt-only SKILL.md text into+-- agent_custom_skills with a scan/approve flow and never executes code. This+-- table holds an executable bundle shape (manifest.json/tools.json/handlers.js,+-- specs/SKILL_SPEC.md) served at runtime by api/skills/import/[id]/[...file].js+-- so src/skills/index.js's SkillRegistry can install it like any hosted bundle.+--+-- `enabled` defaults to false and nothing in api/_lib/openapi-skill-imports.js+-- ever sets it true on create: an import always lands as a draft the owner+-- must deliberately enable.++CREATE TABLE IF NOT EXISTS openapi_skill_imports (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ source_url text NOT NULL,+ kind text NOT NULL CHECK (kind IN ('openapi', 'declarative')),+ manifest jsonb NOT NULL,+ skill_md text NOT NULL,+ tools jsonb,+ handlers_src text,+ enabled boolean NOT NULL DEFAULT false,+ created_at timestamptz NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS openapi_skill_imports_user_recent+ ON openapi_skill_imports (user_id, created_at DESC);diff --git a/api/_lib/openapi-skill-imports.js b/api/_lib/openapi-skill-imports.jsnew file mode 100644index 000000000..ab077bbc4--- /dev/null+++ b/api/_lib/openapi-skill-imports.js@@ -0,0 +1,90 @@+// Draft skills generated by @three-ws/skill-import from an OpenAPI spec or a+// GitHub repo (table openapi_skill_imports). A row here is always a draft:+// `enabled` defaults to false and nothing in this module ever sets it true on+// create, so an imported skill is never live without someone flipping it on+// deliberately through PATCH. Bundle files are served at runtime by+// api/skills/import/[id]/[...file].js so src/skills/index.js's SkillRegistry+// can install them like any other hosted bundle.++import { sql } from './db.js';+import { isUuid } from './validate.js';++export class OpenApiSkillImportError extends Error {+ constructor(status, code, message) {+ super(message);+ this.status = status;+ this.code = code;+ }+}++function present(row) {+ return {+ id: row.id,+ sourceUrl: row.source_url,+ kind: row.kind,+ manifest: row.manifest,+ skillMd: row.skill_md,+ tools: row.tools,+ hasHandlers: Boolean(row.handlers_src),+ enabled: row.enabled,+ createdAt: row.created_at,+ bundleUri: `/api/skills/import/${row.id}/`,+ };+}++export async function createDraft(userId, bundle) {+ const rows = await sql`+ INSERT INTO openapi_skill_imports+ (user_id, source_url, kind, manifest, skill_md, tools, handlers_src, enabled)+ VALUES+ (${userId}, ${bundle.sourceUrl}, ${bundle.tools ? 'openapi' : 'declarative'},+ ${JSON.stringify(bundle.manifest)}::jsonb, ${bundle.skillMd},+ ${bundle.tools ? JSON.stringify(bundle.tools) : null}::jsonb, ${bundle.handlersSrc || null}, false)+ RETURNING *+ `;+ return present(rows[0]);+}++export async function listDrafts(userId) {+ const rows = await sql`+ SELECT * FROM openapi_skill_imports WHERE user_id = ${userId} ORDER BY created_at DESC+ `;+ return rows.map(present);+}++export async function getDraftRow(id, userId) {+ if (!isUuid(id)) throw new OpenApiSkillImportError(400, 'validation_error', 'valid id required');+ const rows = await sql`+ SELECT * FROM openapi_skill_imports WHERE id = ${id} AND user_id = ${userId}+ `;+ if (!rows.length) throw new OpenApiSkillImportError(404, 'not_found', 'import not found');+ return rows[0];+}++export async function getDraft(id, userId) {+ return present(await getDraftRow(id, userId));+}++// Public: served to whatever fetches the bundle (the skill runtime, which has+// no user session). Ownership is checked only on the authoring routes above.+export async function getPublicDraftRow(id) {+ if (!isUuid(id)) throw new OpenApiSkillImportError(400, 'validation_error', 'valid id required');+ const rows = await sql`SELECT * FROM openapi_skill_imports WHERE id = ${id}`;+ if (!rows.length) throw new OpenApiSkillImportError(404, 'not_found', 'import not found');+ return rows[0];+}++export async function setEnabled(id, userId, enabled) {+ await getDraftRow(id, userId);+ const rows = await sql`+ UPDATE openapi_skill_imports SET enabled = ${Boolean(enabled)}+ WHERE id = ${id} AND user_id = ${userId}+ RETURNING *+ `;+ return present(rows[0]);+}++export async function deleteDraft(id, userId) {+ await getDraftRow(id, userId);+ await sql`DELETE FROM openapi_skill_imports WHERE id = ${id} AND user_id = ${userId}`;+}diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 5cf507cc7..1f47989c0 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -2412,6 +2412,10 @@ export const limits = {// runs the Guardian pass, so those are capped per owner.skillImportBrowseIp: (ip) => getLimiter('skill-import:browse:ip', { limit: 120, window: '5 m', local: true }).limit(ip),skillImportScanUser: (userId) => getLimiter('skill-import:scan:user', { limit: 40, window: '10 m' }).limit(userId),+ // OpenAPI/GitHub skill import (api/skills/import.js, packages/skill-import).+ // Each request fetches an owner-supplied upstream spec/README through the+ // SSRF guard and runs codegen, so it is capped per owner like a scan.+ openapiSkillImportUser: (userId) => getLimiter('openapi-skill-import:user', { limit: 20, window: '10 m' }).limit(userId),// Developer plan burst ceiling (api/_lib/dev-plans/quota.js). One sliding// minute per account; the limit comes from the plan config, so each plan// gets its own bucket name and the memo in getLimiter keys on the limit too.diff --git a/api/skills/import.js b/api/skills/import.jsnew file mode 100644index 000000000..e2d28efc6--- /dev/null+++ b/api/skills/import.js@@ -0,0 +1,74 @@+/**+ * POST /api/skills/import { url }: turn an OpenAPI spec or a GitHub repo URL+ * into a skill bundle (packages/skill-import) and save it as a draft.+ * GET /api/skills/import: list the caller's own drafts.+ *+ * A draft is never enabled automatically: `enabled` starts false+ * (api/_lib/openapi-skill-imports.js createDraft) and stays false until an+ * explicit PATCH at /api/skills/import/[id]. This is a different feature from+ * api/skill-imports.js (prompt-only SKILL.md import with a scan/approve flow+ * into agent_custom_skills): this one generates an executable bundle+ * (manifest.json/tools.json/handlers.js) served at+ * /api/skills/import/[id]/[...file].js for src/skills/index.js's+ * SkillRegistry to install.+ *+ * Owner-only: the fetched URL and the generated bundle can embed anything the+ * upstream host chose to write, so nothing here runs with elevated trust and+ * the fetch itself goes through the SSRF guard, pinned-IP variant, since the+ * response is forwarded into generated code.+ */++import { getRequestUser, hasScope } from '../_lib/auth.js';+import { cors, json, wrap, error, readJson } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { requireCsrf } from '../_lib/csrf.js';+import { fetchSafePublicUrlPinned, SsrfBlockedError } from '../_lib/ssrf-guard.js';+import { importFromUrl, OpenApiParseError, GithubDiscoveryError, SkillBundleValidationError } from '@three-ws/skill-import';+import { createDraft, listDrafts, OpenApiSkillImportError } from '../_lib/openapi-skill-imports.js';++const MAX_SPEC_BYTES = 4 * 1024 * 1024;++async function guardedFetch(url, init = {}) {+ return fetchSafePublicUrlPinned(url, init, { maxBytes: MAX_SPEC_BYTES });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;++ const user = await getRequestUser(req, res);+ if (!user) return error(res, 401, 'unauthorized', 'sign in or send a bearer token');+ const write = req.method !== 'GET';+ if (user.source === 'bearer' && !hasScope(user.scope, write ? 'agents:write' : 'agents:read')) {+ return error(res, 403, 'insufficient_scope', `this token needs ${write ? 'agents:write' : 'agents:read'}`);+ }++ if (req.method === 'GET') {+ return json(res, 200, { data: await listDrafts(user.id) });+ }++ if (req.method !== 'POST') return error(res, 405, 'method_not_allowed', 'method not allowed');++ const rl = await limits.openapiSkillImportUser(user.id);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many imports, try again shortly');+ if (!(await requireCsrf(req, res, user.id))) return;++ const body = await readJson(req);+ const url = typeof body?.url === 'string' ? body.url.trim() : '';+ if (!url) return error(res, 400, 'validation_error', 'url is required');++ try {+ const bundle = await importFromUrl(url, {+ fetchUrl: guardedFetch,+ githubToken: process.env.GITHUB_TOKEN || process.env.GH_TOKEN || undefined,+ });+ const draft = await createDraft(user.id, bundle);+ return json(res, 201, { data: draft });+ } catch (err) {+ if (err instanceof SsrfBlockedError) return error(res, 400, 'url_blocked', err.message);+ if (err instanceof OpenApiParseError) return error(res, 400, 'spec_parse_error', err.message);+ if (err instanceof GithubDiscoveryError) return error(res, 400, 'github_error', err.message);+ if (err instanceof SkillBundleValidationError) return error(res, 400, 'invalid_bundle', err.message);+ if (err instanceof OpenApiSkillImportError) return error(res, err.status, err.code, err.message);+ throw err;+ }+});diff --git a/api/skills/import/[id].js b/api/skills/import/[id].jsnew file mode 100644index 000000000..9819833f8--- /dev/null+++ b/api/skills/import/[id].js@@ -0,0 +1,51 @@+/**+ * GET/PATCH/DELETE /api/skills/import/:id: manage one OpenAPI/repo skill+ * draft (api/_lib/openapi-skill-imports.js), owner-scoped.+ *+ * PATCH { enabled } is the only way a draft's `enabled` flag ever changes:+ * createDraft (api/skills/import.js) always hardcodes it false, so a draft+ * stays inert until its owner deliberately flips it here. Enabling does not+ * install the skill onto any agent; it only lets src/skills/index.js's+ * SkillRegistry accept the bundle when an agent's owner later installs it+ * by uri (the disabled check belongs to that install path, not this one).+ */++import { getRequestUser, hasScope } from '../../_lib/auth.js';+import { cors, json, wrap, error, readJson } from '../../_lib/http.js';+import { requireCsrf } from '../../_lib/csrf.js';+import { getDraft, setEnabled, deleteDraft, OpenApiSkillImportError } from '../../_lib/openapi-skill-imports.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,PATCH,DELETE,OPTIONS', credentials: true })) return;++ const user = await getRequestUser(req, res);+ if (!user) return error(res, 401, 'unauthorized', 'sign in or send a bearer token');+ const write = req.method !== 'GET';+ if (user.source === 'bearer' && !hasScope(user.scope, write ? 'agents:write' : 'agents:read')) {+ return error(res, 403, 'insufficient_scope', `this token needs ${write ? 'agents:write' : 'agents:read'}`);+ }++ const id = req.query?.id;++ try {+ if (req.method === 'GET') return json(res, 200, { data: await getDraft(id, user.id) });++ if (req.method === 'PATCH') {+ if (!(await requireCsrf(req, res, user.id))) return;+ const body = await readJson(req);+ if (typeof body?.enabled !== 'boolean') return error(res, 400, 'validation_error', 'enabled (boolean) is required');+ return json(res, 200, { data: await setEnabled(id, user.id, body.enabled) });+ }++ if (req.method === 'DELETE') {+ if (!(await requireCsrf(req, res, user.id))) return;+ await deleteDraft(id, user.id);+ return json(res, 200, { data: { deleted: true, id } });+ }++ return error(res, 405, 'method_not_allowed', 'method not allowed');+ } catch (err) {+ if (err instanceof OpenApiSkillImportError) return error(res, err.status, err.code, err.message);+ throw err;+ }+});diff --git a/api/skills/import/[id]/[...file].js b/api/skills/import/[id]/[...file].jsnew file mode 100644index 000000000..997147cdb--- /dev/null+++ b/api/skills/import/[id]/[...file].js@@ -0,0 +1,51 @@+// GET /api/skills/import/<id>/<manifest.json|SKILL.md|tools.json|handlers.js>+//+// Serves one generated skill bundle (api/_lib/openapi-skill-imports.js) over+// the exact four-file shape specs/SKILL_SPEC.md defines, so+// src/skills/index.js's SkillRegistry can `install({ uri: ".../<id>/" })` it+// like any other hosted bundle. Public and anonymous: whoever embeds the+// agent that installed this skill fetches it with no session, same as any+// other bundle host. The draft itself may still be disabled+// (openapi_skill_imports.enabled); that only gates whether an agent is+// allowed to install it, not whether these bytes can be read once the id is+// known, matching how every other hosted skill bundle in this codebase works.++import { cors, error, json, text, wrap } from '../../../_lib/http.js';+import { getPublicDraftRow, OpenApiSkillImportError } from '../../../_lib/openapi-skill-imports.js';++function joinPath(parts) {+ return Array.isArray(parts) ? parts.join('/') : String(parts || '');+}++export default wrap(async (req, res) => {+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS', credentials: false })) return;+ if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', 'method not allowed');++ const id = req.query?.id;+ const file = joinPath(req.query?.file);++ let row;+ try {+ row = await getPublicDraftRow(id);+ } catch (err) {+ if (err instanceof OpenApiSkillImportError) return error(res, err.status, err.code, err.message);+ throw err;+ }++ res.setHeader('cache-control', 'no-store');++ if (file === 'manifest.json') return json(res, 200, row.manifest);+ if (file === 'SKILL.md') return text(res, 200, row.skill_md, { 'content-type': 'text/markdown; charset=utf-8' });+ if (file === 'tools.json') {+ if (!row.tools) return error(res, 404, 'not_found', 'this skill is declarative-only and has no tools.json');+ return json(res, 200, row.tools);+ }+ // server/index.mjs strips a trailing ".js" from every API path before+ // routing (Vercel's extension-optional convention), so a request for+ // "handlers.js" arrives here as the bare segment "handlers".+ if (file === 'handlers.js' || file === 'handlers') {+ if (!row.handlers_src) return error(res, 404, 'not_found', 'this skill is declarative-only and has no handlers.js');+ return text(res, 200, row.handlers_src, { 'content-type': 'text/javascript; charset=utf-8' });+ }+ return error(res, 404, 'not_found', `unknown bundle file "${file}"`);+});diff --git a/package-lock.json b/package-lock.jsonindex bbcb45bc5..9afb986fb 100644--- a/package-lock.json+++ b/package-lock.json@@ -82,7 +82,8 @@"packages/blender-mcp","packages/ai-sdk","packages/langchain",- "packages/wallet-linkage"+ "packages/wallet-linkage",+ "packages/skill-import"],"dependencies": {"@0xsplits/splits-sdk": "^6.6.0",@@ -162,6 +163,7 @@"@tetsuo-ai/sdk": "^1.4.0","@three-ws/companion": "*","@three-ws/mcp-policy": "*",+ "@three-ws/skill-import": "*","@three-ws/solana-agent": "file:solana-agent-sdk","@upstash/qstash": "^2.11.3","@upstash/ratelimit": "^2.0.5",@@ -8056,7 +8058,6 @@"version": "1.3.0","resolved": "https://registry.npmjs.org/@exodus/schemasafe/-/schemasafe-1.3.0.tgz","integrity": "sha512-5Aap/GaRupgNx/feGBwLLTVv8OQFfv3pq2lPRzPg9R+IOBnDgghTGW7l7EuVXOvg5cc/xSAlRW8rBrjIC3Nvqw==",- "dev": true,"license": "MIT"},"node_modules/@faker-js/faker": {@@ -30080,6 +30081,10 @@"resolved": "packages/signals-mcp","link": true},+ "node_modules/@three-ws/skill-import": {+ "resolved": "packages/skill-import",+ "link": true+ },"node_modules/@three-ws/solana-agent": {"resolved": "solana-agent-sdk","link": true@@ -36912,7 +36917,6 @@"version": "1.0.2","resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.2.tgz","integrity": "sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==",- "dev": true,"license": "MIT"},"node_modules/callsites": {@@ -42465,7 +42469,6 @@"version": "1.3.5","resolved": "https://registry.npmjs.org/http2-client/-/http2-client-1.3.5.tgz","integrity": "sha512-EC2utToWl4RKfs5zd36Mxq7nzHHBuomZboI0yYL6Y0RmBgT7Sgkq4rQ0ezFTYoIsSs7Tm9SJe+o2FcAg6GBhGA==",- "dev": true,"license": "MIT"},"node_modules/https-browserify": {@@ -50895,7 +50898,6 @@"version": "2.3.0","resolved": "https://registry.npmjs.org/node-fetch-h2/-/node-fetch-h2-2.3.0.tgz","integrity": "sha512-ofRW94Ab0T4AOh5Fk8t0h8OBWrmjb0SSB20xh1H8YnPV9EJ+f5AMoYSUQ2zgJ4Iq2HAK0I2l5/Nequ8YzFS3Hg==",- "dev": true,"license": "MIT","dependencies": {"http2-client": "^1.2.5"@@ -51003,7 +51005,6 @@"version": "0.2.0","resolved": "https://registry.npmjs.org/node-readfiles/-/node-readfiles-0.2.0.tgz","integrity": "sha512-SU00ZarexNlE4Rjdm83vglt5Y9yiQ+XI1XpflWlb7q7UTN1JUItm69xMeiQCTxtTfnzt+83T8Cx+vI2ED++VDA==",- "dev": true,"license": "MIT","dependencies": {"es6-promise": "^3.2.1"@@ -51013,7 +51014,6 @@"version": "3.3.1","resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz","integrity": "sha512-SOp9Phqvqn7jtEUxPWdWfWoLmyt2VaJ6MpvP9Comy1MceMXqE6bxvaTu4iaxpYYPzhny28Lc+M87/c2cPK6lDg==",- "dev": true,"license": "MIT"},"node_modules/node-releases": {@@ -51207,7 +51207,6 @@"version": "1.0.8","resolved": "https://registry.npmjs.org/oas-kit-common/-/oas-kit-common-1.0.8.tgz","integrity": "sha512-pJTS2+T0oGIwgjGpw7sIRU8RQMcUoKCDWFLdBqKB2BNmGpbBMH2sdqAaOXUg8OzonZHU0L7vfJu1mJFEiYDWOQ==",- "dev": true,"license": "BSD-3-Clause","dependencies": {"fast-safe-stringify": "^2.0.7"@@ -51217,7 +51216,6 @@"version": "3.2.2","resolved": "https://registry.npmjs.org/oas-linter/-/oas-linter-3.2.2.tgz","integrity": "sha512-KEGjPDVoU5K6swgo9hJVA/qYGlwfbFx+Kg2QB/kd7rzV5N8N5Mg6PlsoCMohVnQmo+pzJap/F610qTodKzecGQ==",- "dev": true,"license": "BSD-3-Clause","dependencies": {"@exodus/schemasafe": "^1.0.0-rc.2",@@ -51232,7 +51230,6 @@"version": "1.10.3","resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz","integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==",- "dev": true,"license": "ISC","engines": {"node": ">= 6"@@ -51242,7 +51239,6 @@"version": "2.5.6","resolved": "https://registry.npmjs.org/oas-resolver/-/oas-resolver-2.5.6.tgz","integrity": "sha512-Yx5PWQNZomfEhPPOphFbZKi9W93CocQj18NlD2Pa4GWZzdZpSJvYwoiuurRI7m3SpcChrnO08hkuQDL3FGsVFQ==",- "dev": true,"license": "BSD-3-Clause","dependencies": {"node-fetch-h2": "^2.3.0",@@ -51293,7 +51289,6 @@"version": "1.10.3","resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz","integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==",- "dev": true,"license": "ISC","engines": {"node": ">= 6"@@ -51303,7 +51298,6 @@"version": "1.1.5","resolved": "https://registry.npmjs.org/oas-schema-walker/-/oas-schema-walker-1.1.5.tgz","integrity": "sha512-2yucenq1a9YPmeNExoUa9Qwrt9RFkjqaMAA1X+U7sbb0AqBeTIdMHky9SQQ6iN94bO5NW0W4TRYXerG+BdAvAQ==",- "dev": true,"license": "BSD-3-Clause","funding": {"url": "https://github.com/Mermade/oas-kit?sponsor=1"@@ -51313,7 +51307,6 @@"version": "5.0.8","resolved": "https://registry.npmjs.org/oas-validator/-/oas-validator-5.0.8.tgz","integrity": "sha512-cu20/HE5N5HKqVygs3dt94eYJfBi0TsZvPVXDhbXQHiEityDN+RROTleefoKRKKJ9dFAF2JBkDHgvWj0sjKGmw==",- "dev": true,"license": "BSD-3-Clause","dependencies": {"call-me-maybe": "^1.0.1",@@ -51333,7 +51326,6 @@"version": "1.10.3","resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz","integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==",- "dev": true,"license": "ISC","engines": {"node": ">= 6"@@ -53626,7 +53618,6 @@"version": "1.1.9","resolved": "https://registry.npmjs.org/reftools/-/reftools-1.1.9.tgz","integrity": "sha512-OVede/NQE13xBQ+ob5CKd5KyeJYU2YInb1bmV4nRoOfquZPkAkxuOXicSe1PvqIuZZ4kD13sPKBbR7UFDmli6w==",- "dev": true,"license": "BSD-3-Clause","funding": {"url": "https://github.com/Mermade/oas-kit?sponsor=1"@@ -55466,7 +55457,6 @@"version": "13.2.3","resolved": "https://registry.npmjs.org/should/-/should-13.2.3.tgz","integrity": "sha512-ggLesLtu2xp+ZxI+ysJTmNjh2U0TsC+rQ/pfED9bUZZ4DKefP27D+7YJVVTvKsmjLpIi9jAa7itwDGkDDmt1GQ==",- "dev": true,"license": "MIT","dependencies": {"should-equal": "^2.0.0",@@ -55480,7 +55470,6 @@"version": "2.0.0","resolved": "https://registry.npmjs.org/should-equal/-/should-equal-2.0.0.tgz","integrity": "sha512-ZP36TMrK9euEuWQYBig9W55WPC7uo37qzAEmbjHz4gfyuXrEUgF8cUvQVO+w+d3OMfPvSRQJ22lSm8MQJ43LTA==",- "dev": true,"license": "MIT","dependencies": {"should-type": "^1.4.0"@@ -55490,7 +55479,6 @@"version": "3.0.3","resolved": "https://registry.npmjs.org/should-format/-/should-format-3.0.3.tgz","integrity": "sha512-hZ58adtulAk0gKtua7QxevgUaXTTXxIi8t41L3zo9AHvjXO1/7sdLECuHeIN2SRtYXpNkmhoUP2pdeWgricQ+Q==",- "dev": true,"license": "MIT","dependencies": {"should-type": "^1.3.0",@@ -55501,14 +55489,12 @@"version": "1.4.0","resolved": "https://registry.npmjs.org/should-type/-/should-type-1.4.0.tgz","integrity": "sha512-MdAsTu3n25yDbIe1NeN69G4n6mUnJGtSJHygX3+oN0ZbO3DTiATnf7XnYJdGT42JCXurTb1JI0qOBR65shvhPQ==",- "dev": true,"license": "MIT"},"node_modules/should-type-adaptors": {"version": "1.1.0","resolved": "https://registry.npmjs.org/should-type-adaptors/-/should-type-adaptors-1.1.0.tgz","integrity": "sha512-JA4hdoLnN+kebEp2Vs8eBe9g7uy0zbRo+RMcU0EsNy+R+k049Ki+N5tT5Jagst2g7EAja+euFuoXFCa8vIklfA==",- "dev": true,"license": "MIT","dependencies": {"should-type": "^1.3.0",@@ -55519,7 +55505,6 @@"version": "1.0.1","resolved": "https://registry.npmjs.org/should-util/-/should-util-1.0.1.tgz","integrity": "sha512-oXF8tfxx5cDk8r2kYqlkUJzZpDBqVY/II2WhvU0n9Y3XYvAYRmeaf1PvvIvTgPnv4KJ+ES5M0PyDq5Jp+Ygy2g==",- "dev": true,"license": "MIT"},"node_modules/side-channel": {@@ -56516,7 +56501,6 @@"version": "7.0.8","resolved": "https://registry.npmjs.org/swagger2openapi/-/swagger2openapi-7.0.8.tgz","integrity": "sha512-upi/0ZGkYgEcLeGieoz8gT74oWHA0E7JivX7aN9mAf+Tc7BQoRBvnIGHoPDw+f9TXTW4s6kGYCZJtauP6OYp7g==",- "dev": true,"license": "BSD-3-Clause","dependencies": {"call-me-maybe": "^1.0.1",@@ -56544,7 +56528,6 @@"version": "1.10.3","resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz","integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==",- "dev": true,"license": "ISC","engines": {"node": ">= 6"@@ -62132,6 +62115,46 @@"node": ">=20"}},+ "packages/skill-import": {+ "name": "@three-ws/skill-import",+ "version": "0.1.0",+ "license": "MIT",+ "dependencies": {+ "js-yaml": "^4.1.1",+ "swagger2openapi": "^7.0.8"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "packages/skill-import/node_modules/argparse": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",+ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",+ "license": "Python-2.0"+ },+ "packages/skill-import/node_modules/js-yaml": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz",+ "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/puzrin"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/nodeca"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "argparse": "^2.0.1"+ },+ "bin": {+ "js-yaml": "bin/js-yaml.js"+ }+ },"packages/solana-memo-media-mcp": {"name": "@three-ws/solana-memo-media-mcp","version": "0.1.0",diff --git a/package.json b/package.jsonindex 1960985a1..ec8c1b19e 100644--- a/package.json+++ b/package.json@@ -139,7 +139,8 @@"packages/blender-mcp","packages/ai-sdk","packages/langchain",- "packages/wallet-linkage"+ "packages/wallet-linkage",+ "packages/skill-import"],"main": "src/app.js","browserslist": [@@ -655,6 +656,7 @@"@tetsuo-ai/sdk": "^1.4.0","@three-ws/companion": "*","@three-ws/mcp-policy": "*",+ "@three-ws/skill-import": "*","@three-ws/solana-agent": "file:solana-agent-sdk","@upstash/qstash": "^2.11.3","@upstash/ratelimit": "^2.0.5",diff --git a/packages/skill-import/README.md b/packages/skill-import/README.mdnew file mode 100644index 000000000..8eaea99d6--- /dev/null+++ b/packages/skill-import/README.md@@ -0,0 +1,65 @@+# @three-ws/skill-import++Turn an OpenAPI spec or a GitHub repository into a three.ws skill bundle+([`specs/SKILL_SPEC.md`](../../specs/SKILL_SPEC.md)): a `manifest.json`, a+`SKILL.md`, a `tools.json` with JSON Schema generated from the spec's+operations, and a `handlers.js` whose exported functions call `ctx.fetch`.++A repository that ships no OpenAPI/Swagger spec falls back to a declarative+bundle built from its README: a `SKILL.md` and `manifest.json` with no+`tools.json` and no `handlers.js` (see "Declarative-only skills" in the spec).++## Usage++```js+import { importFromUrl } from '@three-ws/skill-import';++const bundle = await importFromUrl('https://petstore3.swagger.io/api/v3/openapi.json', {+ fetchUrl: fetch, // supply an SSRF-guarded fetch in production, see api/skills/import.js+});++bundle.manifest; // manifest.json+bundle.skillMd; // SKILL.md text+bundle.tools; // tools.json, or null for a declarative bundle+bundle.handlersSrc; // handlers.js source text, or null for a declarative bundle+```++`fetchUrl` is always caller-supplied: this package never calls the bare+global `fetch`. In `api/skills/import.js` it is wired to+`fetchSafePublicUrlPinned` from `api/_lib/ssrf-guard.js` so a spec URL can+never be used to reach an internal address.++## Auth++Operations that declare an OpenAPI security requirement get a generated+`applyAuth` call reading `ctx.secrets[secretName]` at call time: the secret+name is never baked into the handler, only declared in+`manifest.json#requires.secrets`. The host (the skill runtime, or whatever+backs the agent's skill install) is responsible for populating+`ctx.secrets` from wherever it stores that agent's credentials. Nothing is+ever hardcoded into the generated handler source.++## Modules++| Module | Responsibility |+| --- | --- |+| `openapi.js` | Parse OpenAPI 3.x JSON/YAML; convert Swagger 2.0 via `swagger2openapi`. |+| `operations.js` | Dereference `$ref`s and flatten `paths` into a normalized operation list. |+| `generate-tools.js` | Operations -> `tools.json`. |+| `generate-handlers.js` | Operations -> `handlers.js` source (one generic executor, per-op data embedded as JSON). |+| `generate-manifest.js` | Spec metadata -> `manifest.json`. |+| `generate-skillmd.js` | Spec + operations -> `SKILL.md`. |+| `declarative.js` | README-only repos -> a declarative bundle (Task 2). |+| `github.js` | GitHub repo -> spec discovery or README fallback, via the GitHub REST API. |+| `validate.js` | Structural + no-other-coin validation before a bundle is ever saved. |+| `index.js` | `importFromUrl(url, opts)`, the single entry point. |++## Testing++```+npm test --workspace packages/skill-import+```++`tests/skill-import.test.js` serves a synthetic OpenAPI fixture from a local+HTTP server, generates a bundle, validates it, and loads it into+`src/skills/index.js`'s `SkillRegistry` to call a generated tool end to end.diff --git a/packages/skill-import/package.json b/packages/skill-import/package.jsonnew file mode 100644index 000000000..90923b633--- /dev/null+++ b/packages/skill-import/package.json@@ -0,0 +1,46 @@+{+ "name": "@three-ws/skill-import",+ "version": "0.1.0",+ "description": "Turn an OpenAPI spec or a GitHub repository into a three.ws skill bundle (specs/SKILL_SPEC.md): tools.json schemas generated from operations, handlers.js that call ctx.fetch, a manifest.json, and a SKILL.md. Repos with no spec fall back to a declarative, handler-less bundle built from the README.",+ "keywords": [+ "three.ws",+ "skills",+ "openapi",+ "swagger",+ "mcp",+ "agent-tools",+ "codegen"+ ],+ "author": "three.ws <[email protected]> (https://three.ws)",+ "license": "MIT",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/skill-import"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "private": true,+ "type": "module",+ "main": "./src/index.js",+ "module": "./src/index.js",+ "exports": {+ ".": "./src/index.js"+ },+ "files": [+ "src",+ "README.md"+ ],+ "engines": {+ "node": ">=18"+ },+ "scripts": {+ "test": "vitest run tests"+ },+ "dependencies": {+ "js-yaml": "^4.1.1",+ "swagger2openapi": "^7.0.8"+ }+}diff --git a/packages/skill-import/src/declarative.js b/packages/skill-import/src/declarative.jsnew file mode 100644index 000000000..221f2b9dc--- /dev/null+++ b/packages/skill-import/src/declarative.js@@ -0,0 +1,86 @@+// README-only repos -> a declarative skill: SKILL.md + manifest.json, no+// tools.json and no handlers.js. See specs/SKILL_SPEC.md "Declarative-only skills".++function slugify(text) {+ return (+ String(text || 'imported-skill')+ .toLowerCase()+ .trim()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 64) || 'imported-skill'+ );+}++/** First non-empty, non-heading, non-badge paragraph of a README. */+function firstParagraph(readmeText) {+ const lines = String(readmeText || '').split('\n');+ const buf = [];+ for (const line of lines) {+ const trimmed = line.trim();+ if (!trimmed) {+ if (buf.length) break;+ continue;+ }+ if (trimmed.startsWith('#')) continue;+ if (/^\[!\[/.test(trimmed) || /^\[!\[.*\]\(.*\)\]\(.*\)$/.test(trimmed)) continue;+ buf.push(trimmed.replace(/^>\s*/, ''));+ }+ return buf.join(' ').slice(0, 500);+}++/**+ * @param {{repoName: string, readmeText: string, sourceUrl: string}} input+ * @returns {{manifest: object, skillMd: string}}+ */+export function generateDeclarativeBundle({ repoName, readmeText, sourceUrl }) {+ const name = slugify(repoName);+ const description = firstParagraph(readmeText) || `Imported from ${sourceUrl}`;++ const manifest = {+ spec: 'skill/0.1',+ name,+ version: '0.1.0',+ description,+ author: 'imported',+ license: 'unknown',+ tags: ['imported', 'declarative'],+ requires: {+ rig: ['any'],+ runtime: '>=0.1.0',+ tools: [],+ secrets: [],+ },+ dependencies: {},+ provides: {+ tools: [],+ triggers: ['imported', name],+ },+ source: { type: 'github-readme', url: sourceUrl },+ };++ const skillMd = `---+name: ${name}+description: ${description.replace(/\n/g, ' ')}+triggers:+ - imported+cost: low+---++# ${repoName}++${description}++This skill has no tools: the source repository ships only documentation+(no OpenAPI spec was found), so this bundle carries instructions for the LLM+to reference rather than executable handlers. Full README:++${readmeText || '_No README content was available._'}++## Source++Imported from ${sourceUrl} by @three-ws/skill-import.+`;++ return { manifest, skillMd };+}diff --git a/packages/skill-import/src/generate-handlers.js b/packages/skill-import/src/generate-handlers.jsnew file mode 100644index 000000000..442b85bdb--- /dev/null+++ b/packages/skill-import/src/generate-handlers.js@@ -0,0 +1,142 @@+// Operations -> handlers.js source text.+//+// All per-operation data (path, parameter locations, auth) is embedded as a+// JSON literal, not interpolated into executable code; the only hand-written+// logic is the single generic `callOperation` executor shared by every tool.+// That keeps spec-controlled strings (titles, descriptions, param names) out+// of anything that runs as code.++/** Pick the security scheme that applies to an operation, if any. */+function resolveAuth(op, securitySchemes) {+ for (const requirement of op.security || []) {+ for (const schemeName of Object.keys(requirement)) {+ const scheme = securitySchemes[schemeName];+ if (!scheme) continue;+ const secret = `AUTH_${schemeName}`.toUpperCase().replace(/[^A-Z0-9_]/g, '_');+ if (scheme.type === 'apiKey') {+ return { kind: 'apiKey', in: scheme.in, name: scheme.name, secret };+ }+ if (scheme.type === 'http' && scheme.scheme === 'basic') {+ return { kind: 'basic', secret };+ }+ // http bearer, oauth2, openIdConnect: all resolve to a bearer token+ // the caller obtains out of band and stores under this secret name.+ return { kind: 'bearer', secret };+ }+ }+ return null;+}++/** A server URL can be relative to the document that declared it (common for+ * specs served alongside the API they describe, e.g. Swagger's own demo). */+function resolveBaseUrl(serverUrl, sourceUrl) {+ if (!serverUrl) return sourceUrl ? new URL(sourceUrl).origin : '';+ try {+ return new URL(serverUrl, sourceUrl).toString().replace(/\/$/, '');+ } catch {+ return serverUrl;+ }+}++/**+ * @param {Array} operations from listOperations()+ * @param {object} doc parsed OpenAPI document (for servers + securitySchemes)+ * @param {{sourceUrl?: string}} opts+ * @returns {{ source: string, secrets: string[] }}+ */+export function generateHandlers(operations, doc, opts = {}) {+ const baseUrl = resolveBaseUrl(doc.servers?.[0]?.url, opts.sourceUrl);+ const securitySchemes = doc.components?.securitySchemes || {};+ const secrets = new Set();++ const specs = {};+ for (const op of operations) {+ const auth = resolveAuth(op, securitySchemes);+ if (auth) secrets.add(auth.secret);+ specs[op.operationId] = {+ method: op.method,+ path: op.path,+ parameters: op.parameters.map((p) => ({ name: p.name, in: p.in })),+ hasBody: Boolean(op.requestBody),+ auth,+ };+ }++ const exportedFns = Object.keys(specs)+ .map(+ (name) =>+ `export async function ${name}(args, ctx) {\n\treturn callOperation(OPERATIONS[${JSON.stringify(name)}], args, ctx);\n}`+ )+ .join('\n\n');++ const source = `// Generated by @three-ws/skill-import. Do not hand-edit: regenerate from the source spec instead.++const BASE_URL = ${JSON.stringify(baseUrl)};++const OPERATIONS = ${JSON.stringify(specs, null, '\t')};++function applyAuth(auth, ctx, headers, query) {+ if (!auth) return;+ const secret = ctx?.secrets?.[auth.secret];+ if (!secret) {+ throw new Error(\`missing secret "\${auth.secret}" required by this skill\`);+ }+ if (auth.kind === 'apiKey' && auth.in === 'header') headers[auth.name] = secret;+ else if (auth.kind === 'apiKey' && auth.in === 'query') query[auth.name] = secret;+ else if (auth.kind === 'basic') headers.Authorization = \`Basic \${secret}\`;+ else headers.Authorization = \`Bearer \${secret}\`;+}++async function callOperation(spec, args, ctx) {+ const params = args && typeof args === 'object' ? args : {};+ let path = spec.path;+ const query = {};+ const headers = { Accept: 'application/json' };++ for (const p of spec.parameters) {+ const value = params[p.name];+ if (value === undefined || value === null) continue;+ if (p.in === 'path') path = path.replace(\`{\${p.name}}\`, encodeURIComponent(String(value)));+ else if (p.in === 'query') query[p.name] = value;+ else if (p.in === 'header') headers[p.name] = String(value);+ }++ applyAuth(spec.auth, ctx, headers, query);++ const search = new URLSearchParams();+ for (const [key, value] of Object.entries(query)) search.set(key, String(value));+ const qs = search.toString();+ const url = \`\${BASE_URL}\${path}\${qs ? \`?\${qs}\` : ''}\`;++ const init = { method: spec.method, headers };+ if (spec.hasBody && params.body !== undefined) {+ headers['Content-Type'] = 'application/json';+ init.body = JSON.stringify(params.body);+ }++ const res = await ctx.fetch(url, init);+ const contentType = res.headers?.get?.('content-type') || '';+ const raw = await res.text();+ let body = raw;+ if (contentType.includes('application/json') && raw) {+ // Some real APIs mislabel a plain-text body as application/json; trust+ // the bytes over the header rather than throwing on a boundary we don't+ // control.+ try {+ body = JSON.parse(raw);+ } catch {+ body = raw;+ }+ }+ if (!res.ok) {+ const message = typeof body === 'string' ? body : JSON.stringify(body);+ throw new Error(\`\${spec.method} \${path} failed: \${res.status} \${message}\`);+ }+ return body;+}++${exportedFns}+`;++ return { source, secrets: [...secrets] };+}diff --git a/packages/skill-import/src/generate-manifest.js b/packages/skill-import/src/generate-manifest.jsnew file mode 100644index 000000000..fce112c6d--- /dev/null+++ b/packages/skill-import/src/generate-manifest.js@@ -0,0 +1,45 @@+// Spec metadata + operations -> manifest.json (specs/SKILL_SPEC.md shape).+// `requires.secrets` is an extension this package introduces: it names the+// ctx.secrets keys handlers.js reads for auth, so a host never hardcodes a key.++function slugify(text) {+ return String(text || 'imported-skill')+ .toLowerCase()+ .trim()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 64) || 'imported-skill';+}++/**+ * @param {object} doc parsed OpenAPI document+ * @param {Array} operations from listOperations()+ * @param {string[]} secrets secret names handlers.js needs (from generateHandlers())+ * @param {{sourceUrl?: string}} opts+ */+export function generateManifest(doc, operations, secrets, opts = {}) {+ const info = doc.info || {};+ const name = slugify(info.title);+ const manifest = {+ spec: 'skill/0.1',+ name,+ version: '0.1.0',+ description: (info.description || info.title || 'Imported API skill').slice(0, 500),+ author: info.contact?.name || info.contact?.email || 'imported',+ license: info.license?.name || 'unknown',+ tags: ['imported', 'openapi'],+ requires: {+ rig: ['any'],+ runtime: '>=0.1.0',+ tools: [],+ secrets,+ },+ dependencies: {},+ provides: {+ tools: operations.map((op) => op.operationId),+ triggers: ['imported', name],+ },+ };+ if (opts.sourceUrl) manifest.source = { type: 'openapi', url: opts.sourceUrl };+ return manifest;+}diff --git a/packages/skill-import/src/generate-skillmd.js b/packages/skill-import/src/generate-skillmd.jsnew file mode 100644index 000000000..aed029779--- /dev/null+++ b/packages/skill-import/src/generate-skillmd.js@@ -0,0 +1,46 @@+// Spec + operations -> SKILL.md (frontmatter + prose, specs/SKILL_SPEC.md).++function yamlList(items) {+ if (!items.length) return '[]';+ return `\n${items.map((t) => ` - ${t}`).join('\n')}`;+}++/**+ * @param {object} manifest from generateManifest()+ * @param {object} doc parsed OpenAPI document+ * @param {Array} operations from listOperations()+ */+export function generateSkillMd(manifest, doc, operations) {+ const info = doc.info || {};+ const triggers = manifest.provides.triggers;++ const toolLines = operations+ .map((op) => `- **${op.operationId}** (${op.method} ${op.path}): ${op.description}`)+ .join('\n');++ const secretLines = manifest.requires.secrets.length+ ? `\n## Authentication\n\nThis skill needs the following secrets, provided by the host as \`ctx.secrets\`, never hardcoded:\n\n${manifest.requires.secrets.map((s) => `- \`${s}\``).join('\n')}\n`+ : '';++ const body = `---+name: ${manifest.name}+description: ${manifest.description.replace(/\n/g, ' ')}+triggers:${yamlList(triggers)}+cost: low+---++# ${info.title || manifest.name}++${info.description || `Imported from an OpenAPI spec (version ${info.version || 'unknown'}).`}++## Tools++${toolLines || '_No operations were found in this spec._'}+${secretLines}+## Source++Generated by @three-ws/skill-import from an OpenAPI document. Re-import to pick up spec changes;+this bundle is not hand-maintained.+`;+ return body;+}diff --git a/packages/skill-import/src/generate-tools.js b/packages/skill-import/src/generate-tools.jsnew file mode 100644index 000000000..ad6856612--- /dev/null+++ b/packages/skill-import/src/generate-tools.js@@ -0,0 +1,43 @@+// Operations -> tools.json (Anthropic/OpenAI-style input_schema, see specs/SKILL_SPEC.md).++function paramSchema(parameters) {+ const properties = {};+ const required = [];+ for (const p of parameters) {+ properties[p.name] = {+ ...p.schema,+ description: p.description || p.schema?.description || `${p.in} parameter "${p.name}"`,+ };+ if (p.required) required.push(p.name);+ }+ return { properties, required };+}++/**+ * @param {import('./operations.js').listOperations} operations+ * @returns {{tools: Array<{name: string, description: string, input_schema: object}>}}+ */+export function generateTools(operations) {+ const tools = operations.map((op) => {+ const { properties, required } = paramSchema(op.parameters);++ if (op.requestBody) {+ properties.body = {+ ...op.requestBody.schema,+ description: op.requestBody.description || 'Request body',+ };+ if (op.requestBody.required) required.push('body');+ }++ return {+ name: op.operationId,+ description: op.description || op.summary || `${op.method} ${op.path}`,+ input_schema: {+ type: 'object',+ properties,+ required,+ },+ };+ });+ return { tools };+}diff --git a/packages/skill-import/src/github.js b/packages/skill-import/src/github.jsnew file mode 100644index 000000000..c9a884c51--- /dev/null+++ b/packages/skill-import/src/github.js@@ -0,0 +1,89 @@+// GitHub repo -> either an OpenAPI spec (preferred) or a README fallback.+//+// Reads go through the GitHub REST API and raw.githubusercontent.com only+// (never `git clone`/a codeload tarball at runtime): both are plain HTTPS+// GETs the caller's SSRF-guarded `fetchUrl` can validate per request.++import { looksLikeOpenApi } from './openapi.js';++const SPEC_CANDIDATES = [+ 'openapi.json',+ 'openapi.yaml',+ 'openapi.yml',+ 'swagger.json',+ 'swagger.yaml',+ 'docs/openapi.json',+ 'docs/openapi.yaml',+ 'api/openapi.json',+ 'api/openapi.yaml',+ '.well-known/openapi.json',+];++export class GithubDiscoveryError extends Error {}++/** Parse "owner/repo" out of a github.com URL or an "owner/repo" shorthand. */+export function parseGithubRepo(input) {+ const shorthand = /^([\w.-]+)\/([\w.-]+)$/.exec(input.trim());+ if (shorthand) return { owner: shorthand[1], repo: shorthand[2].replace(/\.git$/, '') };+ let url;+ try {+ url = new URL(input);+ } catch {+ throw new GithubDiscoveryError(`not a URL or "owner/repo": ${input}`);+ }+ if (!/github\.com$/i.test(url.hostname)) {+ throw new GithubDiscoveryError(`not a github.com URL: ${input}`);+ }+ const [owner, repo] = url.pathname.split('/').filter(Boolean);+ if (!owner || !repo) throw new GithubDiscoveryError(`could not parse owner/repo from: ${input}`);+ return { owner, repo: repo.replace(/\.git$/, '') };+}++function authHeaders(githubToken) {+ const headers = { Accept: 'application/vnd.github+json', 'User-Agent': 'three-ws-skill-import' };+ if (githubToken) headers.Authorization = `Bearer ${githubToken}`;+ return headers;+}++/**+ * @param {string} input github.com URL or "owner/repo"+ * @param {{fetchUrl: typeof fetch, githubToken?: string}} opts+ * @returns {Promise<+ * | { kind: 'openapi', text: string, sourceUrl: string, repoName: string }+ * | { kind: 'readme', text: string, sourceUrl: string, repoName: string }+ * >}+ */+export async function discoverGithubSource(input, { fetchUrl, githubToken } = {}) {+ const { owner, repo } = parseGithubRepo(input);+ const headers = authHeaders(githubToken);++ const repoRes = await fetchUrl(`https://api.github.com/repos/${owner}/${repo}`, { headers });+ if (!repoRes.ok) {+ throw new GithubDiscoveryError(`GitHub repo lookup failed: ${repoRes.status} ${owner}/${repo}`);+ }+ const repoInfo = await repoRes.json();+ const branch = repoInfo.default_branch || 'main';++ for (const candidate of SPEC_CANDIDATES) {+ const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/${candidate}`;+ const res = await fetchUrl(rawUrl, { headers: { 'User-Agent': 'three-ws-skill-import' } });+ if (!res.ok) continue;+ const text = await res.text();+ if (looksLikeOpenApi(text)) {+ return { kind: 'openapi', text, sourceUrl: rawUrl, repoName: repoInfo.name };+ }+ }++ const readmeRes = await fetchUrl(`https://api.github.com/repos/${owner}/${repo}/readme`, { headers });+ if (!readmeRes.ok) {+ throw new GithubDiscoveryError(`no OpenAPI spec and no README for ${owner}/${repo}`);+ }+ const readmeJson = await readmeRes.json();+ const text = Buffer.from(readmeJson.content || '', readmeJson.encoding || 'base64').toString('utf8');+ return {+ kind: 'readme',+ text,+ sourceUrl: readmeJson.html_url || `https://github.com/${owner}/${repo}`,+ repoName: repoInfo.name,+ };+}diff --git a/packages/skill-import/src/index.js b/packages/skill-import/src/index.jsnew file mode 100644index 000000000..f92390c35--- /dev/null+++ b/packages/skill-import/src/index.js@@ -0,0 +1,78 @@+// Top-level orchestrator: a URL in, a skill bundle out.+// See README.md and specs/SKILL_SPEC.md.++import { parseOpenApiDocument } from './openapi.js';+import { listOperations } from './operations.js';+import { generateTools } from './generate-tools.js';+import { generateHandlers } from './generate-handlers.js';+import { generateManifest } from './generate-manifest.js';+import { generateSkillMd } from './generate-skillmd.js';+import { generateDeclarativeBundle } from './declarative.js';+import { discoverGithubSource } from './github.js';+import { assertValidBundle } from './validate.js';++export { OpenApiParseError, parseOpenApiDocument, looksLikeOpenApi } from './openapi.js';+export { GithubDiscoveryError, parseGithubRepo, discoverGithubSource } from './github.js';+export { SkillBundleValidationError, validateBundle, assertValidBundle } from './validate.js';+export { listOperations } from './operations.js';+export { generateTools } from './generate-tools.js';+export { generateHandlers } from './generate-handlers.js';+export { generateManifest } from './generate-manifest.js';+export { generateSkillMd } from './generate-skillmd.js';+export { generateDeclarativeBundle } from './declarative.js';++function isGithubRepoUrl(url) {+ try {+ return /(^|\.)github\.com$/i.test(new URL(url).hostname);+ } catch {+ return false;+ }+}++async function buildOpenApiBundle(specText, sourceUrl) {+ const { document } = await parseOpenApiDocument(specText);+ const operations = listOperations(document);+ const tools = generateTools(operations);+ const { source: handlersSrc, secrets } = generateHandlers(operations, document, { sourceUrl });+ const manifest = generateManifest(document, operations, secrets, { sourceUrl });+ const skillMd = generateSkillMd(manifest, document, operations);+ assertValidBundle({ manifest, skillMd, tools, handlersSrc });+ return { manifest, skillMd, tools, handlersSrc, sourceUrl };+}++/**+ * Import a skill bundle from an OpenAPI/Swagger spec URL or a GitHub repo URL.+ *+ * @param {string} url+ * @param {{fetchUrl: typeof fetch, githubToken?: string}} opts+ * `fetchUrl` must be a caller-supplied, SSRF-guarded fetch (the caller+ * decides what "safe" means for its environment; this package never+ * fetches with the bare global `fetch`).+ * @returns {Promise<{+ * manifest: object, skillMd: string,+ * tools: object | null, handlersSrc: string | null,+ * sourceUrl: string,+ * }>}+ */+export async function importFromUrl(url, { fetchUrl, githubToken } = {}) {+ if (typeof fetchUrl !== 'function') throw new Error('importFromUrl requires opts.fetchUrl');++ if (isGithubRepoUrl(url)) {+ const discovered = await discoverGithubSource(url, { fetchUrl, githubToken });+ if (discovered.kind === 'openapi') {+ return buildOpenApiBundle(discovered.text, discovered.sourceUrl);+ }+ const { manifest, skillMd } = generateDeclarativeBundle({+ repoName: discovered.repoName,+ readmeText: discovered.text,+ sourceUrl: discovered.sourceUrl,+ });+ assertValidBundle({ manifest, skillMd });+ return { manifest, skillMd, tools: null, handlersSrc: null, sourceUrl: discovered.sourceUrl };+ }++ const res = await fetchUrl(url);+ if (!res.ok) throw new Error(`failed to fetch ${url}: ${res.status}`);+ const text = await res.text();+ return buildOpenApiBundle(text, url);+}diff --git a/packages/skill-import/src/openapi.js b/packages/skill-import/src/openapi.jsnew file mode 100644index 000000000..cd31b98bc--- /dev/null+++ b/packages/skill-import/src/openapi.js@@ -0,0 +1,64 @@+// Parse raw OpenAPI/Swagger bytes into a normalized OpenAPI 3.x document.+//+// Swagger 2.0 documents are never hand-rolled into OpenAPI 3: swagger2openapi+// is a well-maintained converter (also used by Postman, APIMatic, and+// readme.com) and is already a dependency of this package for exactly that+// reason.++import yaml from 'js-yaml';+import { convertObj } from 'swagger2openapi';++export class OpenApiParseError extends Error {}++/** Parse JSON or YAML text into a plain object. Throws OpenApiParseError. */+function parseText(text) {+ const trimmed = String(text).trim();+ if (!trimmed) throw new OpenApiParseError('empty document');+ if (trimmed[0] === '{' || trimmed[0] === '[') {+ try {+ return JSON.parse(trimmed);+ } catch (err) {+ throw new OpenApiParseError(`not valid JSON: ${err.message}`);+ }+ }+ try {+ return yaml.load(trimmed);+ } catch (err) {+ throw new OpenApiParseError(`not valid YAML: ${err.message}`);+ }+}++/**+ * @param {string} text raw spec bytes (JSON or YAML)+ * @returns {Promise<{ document: object, convertedFromSwagger2: boolean }>}+ */+export async function parseOpenApiDocument(text) {+ const doc = parseText(text);+ if (!doc || typeof doc !== 'object') {+ throw new OpenApiParseError('document is not an object');+ }++ if (typeof doc.openapi === 'string') {+ if (!/^3\./.test(doc.openapi)) {+ throw new OpenApiParseError(`unsupported openapi version "${doc.openapi}"`);+ }+ return { document: doc, convertedFromSwagger2: false };+ }++ if (typeof doc.swagger === 'string' && doc.swagger.startsWith('2.')) {+ const { openapi } = await convertObj(doc, { patch: true, warnOnly: true });+ return { document: openapi, convertedFromSwagger2: true };+ }++ throw new OpenApiParseError('document has neither "openapi" (3.x) nor "swagger" (2.x)');+}++/** True when text looks like an OpenAPI/Swagger document, without throwing. */+export function looksLikeOpenApi(text) {+ try {+ const doc = parseText(text);+ return Boolean(doc && typeof doc === 'object' && (doc.openapi || doc.swagger));+ } catch {+ return false;+ }+}diff --git a/packages/skill-import/src/operations.js b/packages/skill-import/src/operations.jsnew file mode 100644index 000000000..0a7d93009--- /dev/null+++ b/packages/skill-import/src/operations.js@@ -0,0 +1,113 @@+// Walk an OpenAPI 3.x document into a flat, resolved list of operations.++const HTTP_METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'];++/** Resolve a local "#/a/b/c" $ref against the document root. Returns undefined if unresolved. */+export function resolveRef(doc, ref) {+ if (typeof ref !== 'string' || !ref.startsWith('#/')) return undefined;+ const path = ref.slice(2).split('/').map((seg) => seg.replace(/~1/g, '/').replace(/~0/g, '~'));+ let node = doc;+ for (const seg of path) {+ if (node == null) return undefined;+ node = node[seg];+ }+ return node;+}++/** Resolve $ref (one hop, then recurse) and merge sibling keys over it, OpenAPI-style. */+function deref(doc, node, seen = new Set()) {+ if (!node || typeof node !== 'object') return node;+ if (!node.$ref) return node;+ if (seen.has(node.$ref)) return {}; // cyclic ref: stop rather than loop forever+ const resolved = resolveRef(doc, node.$ref);+ if (resolved === undefined) return {};+ const next = new Set(seen);+ next.add(node.$ref);+ const { $ref, ...rest } = node;+ return { ...deref(doc, resolved, next), ...rest };+}++/** Recursively dereference every $ref in a schema/object tree, bounded to avoid cycles. */+export function derefDeep(doc, node, depth = 0, seen = new Set()) {+ if (depth > 12 || !node || typeof node !== 'object') return node;+ if (Array.isArray(node)) return node.map((n) => derefDeep(doc, n, depth + 1, seen));+ const resolved = deref(doc, node, seen);+ if (resolved !== node && resolved.$ref) return {}; // unresolved after one hop+ const out = {};+ for (const [k, v] of Object.entries(resolved)) {+ out[k] = v && typeof v === 'object' ? derefDeep(doc, v, depth + 1, seen) : v;+ }+ return out;+}++/**+ * @param {object} doc normalized OpenAPI 3.x document+ * @returns {Array<{+ * operationId: string, method: string, path: string,+ * summary: string, description: string,+ * parameters: Array<{name: string, in: string, required: boolean, schema: object, description: string}>,+ * requestBody: null | { required: boolean, schema: object, description: string },+ * security: Array<object>,+ * }>}+ */+export function listOperations(doc) {+ const paths = doc.paths || {};+ const globalSecurity = doc.security || [];+ const seenIds = new Set();+ const out = [];++ for (const [path, pathItem] of Object.entries(paths)) {+ if (!pathItem || typeof pathItem !== 'object') continue;+ const pathLevelParams = (pathItem.parameters || []).map((p) => deref(doc, p));++ for (const method of HTTP_METHODS) {+ const op = pathItem[method];+ if (!op || typeof op !== 'object') continue;++ const ownParams = (op.parameters || []).map((p) => deref(doc, p));+ const byKey = new Map();+ for (const p of [...pathLevelParams, ...ownParams]) {+ if (p?.name && p?.in) byKey.set(`${p.in}:${p.name}`, p);+ }+ const parameters = [...byKey.values()].map((p) => ({+ name: p.name,+ in: p.in,+ required: Boolean(p.required || p.in === 'path'),+ schema: derefDeep(doc, p.schema || { type: 'string' }),+ description: p.description || '',+ }));++ let requestBody = null;+ const rawBody = op.requestBody ? deref(doc, op.requestBody) : null;+ if (rawBody) {+ const content = rawBody.content || {};+ const mediaType = content['application/json'] || Object.values(content)[0] || null;+ requestBody = {+ required: Boolean(rawBody.required),+ schema: derefDeep(doc, mediaType?.schema || { type: 'object' }),+ description: rawBody.description || '',+ };+ }++ let operationId = op.operationId || `${method}_${path}`;+ operationId = operationId.replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_+|_+$/g, '');+ if (!/^[a-zA-Z_]/.test(operationId)) operationId = `op_${operationId}`;+ let unique = operationId;+ let n = 2;+ while (seenIds.has(unique)) unique = `${operationId}_${n++}`;+ seenIds.add(unique);++ out.push({+ operationId: unique,+ method: method.toUpperCase(),+ path,+ summary: op.summary || '',+ description: op.description || op.summary || `${method.toUpperCase()} ${path}`,+ parameters,+ requestBody,+ security: op.security || globalSecurity,+ });+ }+ }+ return out;+}diff --git a/packages/skill-import/src/validate.js b/packages/skill-import/src/validate.jsnew file mode 100644index 000000000..abed36cda--- /dev/null+++ b/packages/skill-import/src/validate.js@@ -0,0 +1,96 @@+// Validate a generated skill bundle before it is ever saved or served.+//+// community-skills/tools/validate.mjs validates a different, incompatible+// directory shape (SKILL.md + metadata.json only; it rejects any other+// top-level file, so it cannot see a manifest.json/tools.json/handlers.js+// bundle at all). This validator checks the actual bundle shape+// specs/SKILL_SPEC.md defines, structurally mirroring the checks+// tests/src/pump-fun-skill.test.js makes of the built-in pump-fun skill,+// while still reusing registry.mjs's no-other-coin and token-budget+// primitives rather than re-implementing them.++import { spawnSync } from 'node:child_process';+import { writeFileSync, unlinkSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { findTokenReferences, estimateTokens, LIMITS } from '../../../community-skills/tools/registry.mjs';++export class SkillBundleValidationError extends Error {+ constructor(errors) {+ super(`invalid skill bundle:\n- ${errors.join('\n- ')}`);+ this.errors = errors;+ }+}++function checkSyntax(source) {+ const file = join(tmpdir(), `skill-import-${randomUUID()}.mjs`);+ writeFileSync(file, source);+ try {+ const result = spawnSync(process.execPath, ['--check', file], { encoding: 'utf8' });+ if (result.status !== 0) return [`handlers.js has a syntax error: ${result.stderr.trim()}`];+ return [];+ } finally {+ unlinkSync(file);+ }+}++/**+ * @param {{manifest: object, skillMd: string, tools?: object, handlersSrc?: string}} bundle+ * @returns {string[]} errors; empty means valid+ */+export function validateBundle({ manifest, skillMd, tools, handlersSrc }) {+ const errors = [];++ if (!manifest || manifest.spec !== 'skill/0.1') errors.push('manifest.spec must be "skill/0.1"');+ if (!manifest?.name) errors.push('manifest.name is required');+ if (!manifest?.version) errors.push('manifest.version is required');+ if (!manifest?.description) errors.push('manifest.description is required');+ if (!Array.isArray(manifest?.provides?.tools)) errors.push('manifest.provides.tools must be an array');++ if (!skillMd || !/^---\n/.test(skillMd)) errors.push('SKILL.md must start with --- frontmatter');++ const declaredTools = manifest?.provides?.tools || [];+ if (declaredTools.length > 0) {+ if (!tools || !Array.isArray(tools.tools)) {+ errors.push('tools.json is required when manifest.provides.tools is non-empty');+ } else {+ const toolNames = new Set(tools.tools.map((t) => t.name));+ for (const name of declaredTools) {+ if (!toolNames.has(name)) errors.push(`manifest declares tool "${name}" missing from tools.json`);+ }+ for (const tool of tools.tools) {+ if (!tool.description) errors.push(`tool "${tool.name}" has no description`);+ if (tool.input_schema?.type !== 'object') errors.push(`tool "${tool.name}".input_schema.type must be "object"`);+ }+ }+ if (!handlersSrc) {+ errors.push('handlers.js is required when manifest.provides.tools is non-empty');+ } else {+ for (const name of declaredTools) {+ if (!new RegExp(`export\\s+(async\\s+)?function\\s+${name}\\b`).test(handlersSrc)) {+ errors.push(`handlers.js has no exported function for tool "${name}"`);+ }+ }+ errors.push(...checkSyntax(handlersSrc));+ }+ } else if (tools || handlersSrc) {+ errors.push('declarative skill (no provides.tools) must not ship tools.json or handlers.js');+ }++ const allText = [skillMd, JSON.stringify(manifest), tools ? JSON.stringify(tools) : ''].join('\n');+ for (const finding of findTokenReferences(allText, { prose: true })) {+ errors.push(`references another crypto project (${finding}); only $THREE is promoted`);+ }+ if (estimateTokens(skillMd) > LIMITS.bodyMaxChars / 4) {+ errors.push(`SKILL.md is too large (~${estimateTokens(skillMd)} tokens, limit ~${Math.ceil(LIMITS.bodyMaxChars / 4)})`);+ }++ return errors;+}++/** Throws SkillBundleValidationError if the bundle is invalid. */+export function assertValidBundle(bundle) {+ const errors = validateBundle(bundle);+ if (errors.length) throw new SkillBundleValidationError(errors);+}diff --git a/packages/skill-import/tests/fixtures/sample-openapi.json b/packages/skill-import/tests/fixtures/sample-openapi.jsonnew file mode 100644index 000000000..96d15bd0d--- /dev/null+++ b/packages/skill-import/tests/fixtures/sample-openapi.json@@ -0,0 +1,49 @@+{+ "openapi": "3.0.3",+ "info": {+ "title": "Widget API",+ "version": "1.0.0",+ "description": "A tiny synthetic API used only by packages/skill-import's own test suite."+ },+ "security": [{ "apiKey": [] }],+ "components": {+ "securitySchemes": {+ "apiKey": { "type": "apiKey", "in": "header", "name": "x-api-key" }+ },+ "schemas": {+ "Widget": {+ "type": "object",+ "required": ["title"],+ "properties": {+ "id": { "type": "string" },+ "title": { "type": "string", "description": "Display name" }+ }+ }+ }+ },+ "paths": {+ "/widgets": {+ "post": {+ "operationId": "createWidget",+ "summary": "Create a widget",+ "requestBody": {+ "required": true,+ "content": {+ "application/json": { "schema": { "$ref": "#/components/schemas/Widget" } }+ }+ },+ "responses": { "201": { "description": "Created" } }+ }+ },+ "/widgets/{id}": {+ "get": {+ "operationId": "getWidget",+ "summary": "Fetch a widget by id",+ "parameters": [+ { "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }+ ],+ "responses": { "200": { "description": "OK" } }+ }+ }+ }+}diff --git a/packages/skill-import/tests/skill-import.test.js b/packages/skill-import/tests/skill-import.test.jsnew file mode 100644index 000000000..f5f4ac05b--- /dev/null+++ b/packages/skill-import/tests/skill-import.test.js@@ -0,0 +1,152 @@+// Serves a synthetic OpenAPI fixture from a real local HTTP server, generates+// a bundle, validates it, loads it into src/skills/index.js's SkillRegistry+// (the real skill runtime, see specs/SKILL_SPEC.md), and calls a generated+// handler against the same local server to prove ctx.fetch actually works.++import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { createServer } from 'node:http';+import { readFile, writeFile, rm } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';+import { tmpdir } from 'node:os';+import { randomUUID } from 'node:crypto';++import { importFromUrl, validateBundle, generateDeclarativeBundle } from '../src/index.js';+import { SkillRegistry } from '../../../src/skills/index.js';++const __dirname = dirname(fileURLToPath(import.meta.url));+const API_KEY = 'test-key';++let server;+let baseUrl;+let bundle;+const widgets = new Map([['seed-1', { id: 'seed-1', title: 'Widget One' }]]);++function requireApiKey(req, res) {+ if (req.headers['x-api-key'] !== API_KEY) {+ res.writeHead(401, { 'content-type': 'application/json' }).end(JSON.stringify({ error: 'missing or wrong api key' }));+ return false;+ }+ return true;+}++beforeAll(async () => {+ server = createServer(async (req, res) => {+ const url = new URL(req.url, 'http://localhost');++ if (req.method === 'GET' && url.pathname === '/openapi.json') {+ const spec = await readFile(resolve(__dirname, 'fixtures/sample-openapi.json'), 'utf8');+ res.writeHead(200, { 'content-type': 'application/json' }).end(spec);+ return;+ }++ if (url.pathname.startsWith('/bundle/') && bundle) {+ const file = url.pathname.slice('/bundle/'.length);+ const byFile = {+ 'manifest.json': JSON.stringify(bundle.manifest),+ 'SKILL.md': bundle.skillMd,+ 'tools.json': JSON.stringify(bundle.tools),+ 'handlers.js': bundle.handlersSrc,+ };+ if (byFile[file] !== undefined) {+ res.writeHead(200, { 'content-type': 'application/json' }).end(byFile[file]);+ return;+ }+ res.writeHead(404).end();+ return;+ }++ if (req.method === 'POST' && url.pathname === '/widgets') {+ if (!requireApiKey(req, res)) return;+ let raw = '';+ for await (const chunk of req) raw += chunk;+ const data = JSON.parse(raw);+ const id = randomUUID();+ const widget = { id, title: data.title };+ widgets.set(id, widget);+ res.writeHead(201, { 'content-type': 'application/json' }).end(JSON.stringify(widget));+ return;+ }++ const getMatch = req.method === 'GET' && url.pathname.match(/^\/widgets\/([^/]+)$/);+ if (getMatch) {+ if (!requireApiKey(req, res)) return;+ const widget = widgets.get(getMatch[1]);+ if (!widget) {+ res.writeHead(404, { 'content-type': 'application/json' }).end(JSON.stringify({ error: 'not found' }));+ return;+ }+ res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(widget));+ return;+ }++ res.writeHead(404).end();+ });+ await new Promise((resolveListen) => server.listen(0, '127.0.0.1', resolveListen));+ baseUrl = `http://127.0.0.1:${server.address().port}`;+ bundle = await importFromUrl(`${baseUrl}/openapi.json`, { fetchUrl: fetch });+});++afterAll(() => new Promise((resolveClose) => server.close(resolveClose)));++describe('importFromUrl against a synthetic OpenAPI fixture', () => {+ it('generates a manifest, tools.json and handlers.js that pass validation', () => {+ expect(bundle.manifest.spec).toBe('skill/0.1');+ expect(new Set(bundle.manifest.provides.tools)).toEqual(new Set(['createWidget', 'getWidget']));+ expect(bundle.manifest.requires.secrets).toEqual(['AUTH_APIKEY']);++ const toolNames = new Set(bundle.tools.tools.map((t) => t.name));+ expect(toolNames).toEqual(new Set(['createWidget', 'getWidget']));+ for (const tool of bundle.tools.tools) {+ expect(tool.description).toBeTruthy();+ expect(tool.input_schema.type).toBe('object');+ }++ expect(validateBundle(bundle)).toEqual([]);+ });++ it('loads into the real skill runtime (SkillRegistry.install)', async () => {+ const registry = new SkillRegistry();+ const skill = await registry.install({ uri: `${baseUrl}/bundle/` });++ expect(skill.manifest.name).toBe(bundle.manifest.name);+ expect(new Set(skill.tools.map((t) => t.name))).toEqual(new Set(['createWidget', 'getWidget']));+ expect(skill.instructions).toContain('createWidget');+ // Not a trusted-main-thread bundle: handler source is kept as text for the sandbox worker.+ expect(skill.handlersSrc).toBe(bundle.handlersSrc);+ expect(skill.handlers).toEqual({});+ });++ it('generated handlers.js makes real HTTP calls that round-trip through the fixture server', async () => {+ const file = resolve(tmpdir(), `skill-import-handlers-${randomUUID()}.mjs`);+ await writeFile(file, bundle.handlersSrc);+ try {+ const handlers = await import(/* @vite-ignore */ file);+ const ctx = { fetch, secrets: { AUTH_APIKEY: API_KEY } };++ const created = await handlers.createWidget({ body: { title: 'Lamp' } }, ctx);+ expect(created.title).toBe('Lamp');+ expect(created.id).toBeTruthy();++ const fetched = await handlers.getWidget({ id: created.id }, ctx);+ expect(fetched).toEqual(created);++ await expect(handlers.getWidget({ id: created.id }, { fetch, secrets: {} })).rejects.toThrow(/missing secret/);+ } finally {+ await rm(file, { force: true });+ }+ });+});++describe('declarative bundles (README-only repos)', () => {+ it('never produces tools.json or handlers.js', () => {+ const { manifest, skillMd } = generateDeclarativeBundle({+ repoName: 'example-docs',+ readmeText: '# Example\n\nJust documentation, no API.',+ sourceUrl: 'https://github.com/example/example-docs',+ });+ expect(manifest.provides.tools).toEqual([]);+ expect(validateBundle({ manifest, skillMd })).toEqual([]);+ expect(validateBundle({ manifest, skillMd, tools: { tools: [] } })).not.toEqual([]);+ });+});diff --git a/tests/openapi-skill-import.test.js b/tests/openapi-skill-import.test.jsnew file mode 100644index 000000000..1d472661a--- /dev/null+++ b/tests/openapi-skill-import.test.js@@ -0,0 +1,265 @@+// POST/GET /api/skills/import (api/skills/import.js) and the public bundle+// host /api/skills/import/:id/* (api/skills/import/[id]/[...file].js).+//+// The database is an in-memory openapi_skill_imports table that understands+// exactly the statements api/_lib/openapi-skill-imports.js issues. The spec+// fetch runs against a real local HTTP server serving the same synthetic+// fixture packages/skill-import's own suite uses, so the generation path+// under test is the real @three-ws/skill-import code, not a stub; only the+// SSRF guard (which would otherwise refuse a loopback address on purpose) is+// swapped for a passthrough so that real local server is reachable in tests.++import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest';+import { createServer } from 'node:http';+import { readFileSync } from 'node:fs';+import { Readable } from 'node:stream';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const FIXTURE = JSON.parse(+ readFileSync(path.join(__dirname, '../packages/skill-import/tests/fixtures/sample-openapi.json'), 'utf8'),+);++const OWNER = '11111111-1111-4111-8111-111111111111';+const STRANGER = '22222222-2222-4222-8222-222222222222';++const db = { rows: [], seq: 0 };++function nextUuid() {+ db.seq += 1;+ return `bbbbbbbb-bbbb-4bbb-8bbb-${String(db.seq).padStart(12, '0')}`;+}++function query(q, values) {+ if (q.startsWith('insert into openapi_skill_imports')) {+ const [user_id, source_url, kind, manifest, skill_md, tools, handlers_src] = values;+ const row = {+ id: nextUuid(),+ user_id,+ source_url,+ kind,+ manifest: JSON.parse(manifest),+ skill_md,+ tools: tools ? JSON.parse(tools) : null,+ handlers_src,+ enabled: false,+ created_at: new Date().toISOString(),+ };+ db.rows.push(row);+ return [{ ...row }];+ }+ if (q.startsWith('select') && q.includes('from openapi_skill_imports where user_id') && q.includes('order by created_at')) {+ return db.rows.filter((r) => r.user_id === values[0]).map((r) => ({ ...r }));+ }+ if (q.startsWith('select') && q.includes('from openapi_skill_imports where id') && q.includes('and user_id')) {+ return db.rows.filter((r) => r.id === values[0] && r.user_id === values[1]).map((r) => ({ ...r }));+ }+ if (q.startsWith('select') && q.includes('from openapi_skill_imports where id') && !q.includes('and user_id')) {+ return db.rows.filter((r) => r.id === values[0]).map((r) => ({ ...r }));+ }+ if (q.startsWith('update openapi_skill_imports set enabled')) {+ const [enabled, id, user_id] = values;+ const row = db.rows.find((r) => r.id === id && r.user_id === user_id);+ if (row) row.enabled = enabled;+ return row ? [{ ...row }] : [];+ }+ if (q.startsWith('delete from openapi_skill_imports where id') && q.includes('and user_id')) {+ db.rows = db.rows.filter((r) => !(r.id === values[0] && r.user_id === values[1]));+ return [];+ }+ throw new Error(`unexpected query in test: ${q.slice(0, 120)}`);+}++vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn((strings, ...values) => {+ const q = strings.join('?').replace(/\s+/g, ' ').trim().toLowerCase();+ return Promise.resolve().then(() => query(q, values));+ }),+}));++const authState = { user: null };+vi.mock('../api/_lib/auth.js', () => ({+ getRequestUser: vi.fn(async () => authState.user),+ hasScope: (granted, required) => {+ const g = new Set(String(granted || '').split(/\s+/).filter(Boolean));+ return required.split(/\s+/).every((s) => g.has(s));+ },+}));++vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { openapiSkillImportUser: vi.fn(async () => ({ success: true })) },+ clientIp: () => '127.0.0.1',+}));++// Real network call, just not through the pinned-DNS SSRF guard: a loopback+// test server is exactly what that guard exists to refuse in production.+vi.mock('../api/_lib/ssrf-guard.js', async () => {+ const actual = await vi.importActual('../api/_lib/ssrf-guard.js');+ return { ...actual, fetchSafePublicUrlPinned: (url, init) => fetch(url, init) };+});++const { default: importHandler } = await import('../api/skills/import.js');+const { default: draftHandler } = await import('../api/skills/import/[id].js');+const { default: fileHandler } = await import('../api/skills/import/[id]/[...file].js');++function mockRes() {+ return {+ statusCode: 200,+ _headers: {},+ _body: '',+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },+ getHeader(k) { return this._headers[k.toLowerCase()]; },+ end(b) { this._body = b || ''; },+ get headersSent() { return false; },+ get writableEnded() { return false; },+ get json() { try { return JSON.parse(this._body); } catch { return null; } },+ };+}++async function callImport(method, body) {+ const req = Readable.from(body != null ? [Buffer.from(JSON.stringify(body))] : []);+ req.method = method;+ req.url = '/api/skills/import';+ req.headers = { origin: 'http://localhost:3000', 'content-type': 'application/json' };+ const res = mockRes();+ await importHandler(req, res);+ return { status: res.statusCode, body: res.json };+}++async function callDraft(method, id, body) {+ const req = Readable.from(body != null ? [Buffer.from(JSON.stringify(body))] : []);+ req.method = method;+ req.url = `/api/skills/import/${id}`;+ req.headers = { origin: 'http://localhost:3000', 'content-type': 'application/json' };+ req.query = { id };+ const res = mockRes();+ await draftHandler(req, res);+ return { status: res.statusCode, body: res.json };+}++async function callFile(id, file) {+ const req = Readable.from([]);+ req.method = 'GET';+ req.url = `/api/skills/import/${id}/${file}`;+ req.headers = { origin: 'http://localhost:3000' };+ req.query = { id, file: file.split('/') };+ const res = mockRes();+ await fileHandler(req, res);+ return { status: res.statusCode, body: res.json, text: res._body };+}++let server;+let specUrl;++beforeAll(async () => {+ server = createServer((req, res) => {+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify(FIXTURE));+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ specUrl = `http://127.0.0.1:${server.address().port}/openapi.json`;+});++afterAll(async () => {+ await new Promise((resolve) => server.close(resolve));+});++beforeEach(() => {+ db.rows = [];+ db.seq = 0;+ authState.user = { id: OWNER, source: 'session' };+});++describe('POST/GET /api/skills/import', () => {+ it('rejects an anonymous caller and a bearer token without the write scope', async () => {+ authState.user = null;+ expect((await callImport('POST', { url: specUrl })).status).toBe(401);+ authState.user = { id: OWNER, source: 'bearer', scope: 'agents:read' };+ expect((await callImport('POST', { url: specUrl })).body).toMatchObject({ error: 'insufficient_scope' });+ });++ it('requires a url', async () => {+ expect((await callImport('POST', {})).status).toBe(400);+ });++ it('imports a real OpenAPI spec end to end and never enables the draft', async () => {+ const { status, body } = await callImport('POST', { url: specUrl });+ expect(status).toBe(201);+ expect(body.data).toMatchObject({ kind: 'openapi', enabled: false });+ expect(body.data.manifest.spec).toBe('skill/0.1');+ expect(body.data.manifest.provides.tools).toEqual(['createWidget', 'getWidget']);+ expect(body.data.bundleUri).toBe(`/api/skills/import/${body.data.id}/`);++ // The row landed with enabled hardcoded false; nothing in the create path+ // can flip it, since no PATCH/enable route exists yet for this feature.+ expect(db.rows).toHaveLength(1);+ expect(db.rows[0].enabled).toBe(false);+ });++ it('lists only the caller\'s own drafts, each one disabled', async () => {+ await callImport('POST', { url: specUrl });+ authState.user = { id: STRANGER, source: 'session' };+ await callImport('POST', { url: specUrl });++ authState.user = { id: OWNER, source: 'session' };+ const { body } = await callImport('GET');+ expect(body.data).toHaveLength(1);+ expect(body.data.every((d) => d.enabled === false)).toBe(true);+ });+});++describe('GET/PATCH/DELETE /api/skills/import/:id', () => {+ it('is the only path that can ever flip enabled, and it is owner-scoped', async () => {+ const created = await callImport('POST', { url: specUrl });+ const id = created.body.data.id;++ expect((await callDraft('GET', id)).body.data.enabled).toBe(false);++ authState.user = { id: STRANGER, source: 'session' };+ expect((await callDraft('PATCH', id, { enabled: true })).status).toBe(404);+ authState.user = { id: OWNER, source: 'session' };++ const enabled = await callDraft('PATCH', id, { enabled: true });+ expect(enabled.status).toBe(200);+ expect(enabled.body.data.enabled).toBe(true);++ expect((await callDraft('PATCH', id, {})).status).toBe(400);++ const deleted = await callDraft('DELETE', id);+ expect(deleted.body.data).toEqual({ deleted: true, id });+ expect((await callDraft('GET', id)).status).toBe(404);+ });+});++describe('GET /api/skills/import/:id/*', () => {+ it('serves the full bundle anonymously, including handlers.js after the server\'s trailing-.js strip', async () => {+ const created = await callImport('POST', { url: specUrl });+ const id = created.body.data.id;++ const manifest = await callFile(id, 'manifest.json');+ expect(manifest.status).toBe(200);+ expect(manifest.body.provides.tools).toEqual(['createWidget', 'getWidget']);++ const skillMd = await callFile(id, 'SKILL.md');+ expect(skillMd.status).toBe(200);+ expect(skillMd.text).toContain('createWidget');++ const tools = await callFile(id, 'tools.json');+ expect(tools.status).toBe(200);+ expect(tools.body.tools.map((t) => t.name)).toEqual(['createWidget', 'getWidget']);++ // server/index.mjs strips a trailing ".js" from the URL before routing,+ // so the file segment this handler actually receives for "handlers.js"+ // is the bare "handlers".+ const handlers = await callFile(id, 'handlers');+ expect(handlers.status).toBe(200);+ expect(handlers.text).toContain('export async function createWidget');+ });++ it('404s on an unknown id', async () => {+ expect((await callFile('00000000-0000-0000-0000-000000000000', 'manifest.json')).status).toBe(404);+ });+});diff --git a/vercel.json b/vercel.jsonindex 403bd027e..38fe24574 100644--- a/vercel.json+++ b/vercel.json@@ -5936,6 +5936,10 @@"src": "/api/skills/mint","dest": "/api/skills/mint"},+ {+ "src": "/api/skills/import",+ "dest": "/api/skills/import"+ },{"src": "/api/skills/([^/]+)/install","dest": "/api/skills/[id]/install?id=$1"