@vvedantb/server 0.19.0 → 0.20.1

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 (82) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/ai/errors.d.ts +0 -2
  3. package/dist/ai/errors.js +0 -16
  4. package/dist/ai/serviceTier.d.ts +0 -4
  5. package/dist/ai/serviceTier.js +0 -4
  6. package/dist/artifacts/document.d.ts +0 -2
  7. package/dist/artifacts/document.js +0 -1
  8. package/dist/artifacts/protocol.d.ts +0 -5
  9. package/dist/artifacts/schemas.d.ts +0 -6
  10. package/dist/artifacts/storageShim.js +0 -2
  11. package/dist/convex/authFunctions.d.ts +0 -57
  12. package/dist/convex/clerkBilling.d.ts +2 -18
  13. package/dist/convex/clerkBilling.js +0 -9
  14. package/dist/convex/clerkBillingFunctions.d.ts +0 -35
  15. package/dist/convex/clerkBillingFunctions.js +0 -8
  16. package/dist/convex/clerkBillingNodeFunctions.d.ts +0 -29
  17. package/dist/convex/clerkBillingNodeFunctions.js +0 -1
  18. package/dist/convex/clerkUserAuth.d.ts +0 -18
  19. package/dist/convex/clerkUserAuth.js +0 -14
  20. package/dist/convex/clerkWebhook.d.ts +0 -2
  21. package/dist/convex/convexAdminClient.d.ts +0 -30
  22. package/dist/convex/convexAdminClient.js +0 -34
  23. package/dist/convex/convexQueryLimits.d.ts +0 -8
  24. package/dist/convex/convexQueryLimits.js +0 -8
  25. package/dist/convex/createMcpAuthActions.d.ts +0 -31
  26. package/dist/convex/expoPush.d.ts +0 -24
  27. package/dist/convex/expoPush.js +0 -4
  28. package/dist/convex/homepageRoutes.d.ts +0 -12
  29. package/dist/convex/mcpServerInfo.d.ts +0 -2
  30. package/dist/convex/mcpTokenCache.d.ts +0 -17
  31. package/dist/convex/mcpTokenCache.js +0 -2
  32. package/dist/convex/memoryStore.js +0 -6
  33. package/dist/convex/originAllowlistCors.d.ts +0 -8
  34. package/dist/convex/productEmails.d.ts +0 -4
  35. package/dist/convex/tempId.js +0 -2
  36. package/dist/convex/vPlan.d.ts +0 -4
  37. package/dist/convex/vProModule.d.ts +0 -27
  38. package/dist/convex/vProModule.js +0 -11
  39. package/dist/convex/verifyClerkAccessToken.d.ts +3 -13
  40. package/dist/convex/verifyClerkOAuthJwt.d.ts +0 -18
  41. package/dist/convex/verifyClerkOAuthJwt.js +0 -6
  42. package/dist/crypto/aesGcm.d.ts +0 -2
  43. package/dist/crypto/aesGcm.js +0 -2
  44. package/dist/crypto/encoding.d.ts +0 -8
  45. package/dist/crypto/encoding.js +0 -3
  46. package/dist/generative-ui/catalog.d.ts +0 -17
  47. package/dist/generative-ui/catalog.js +0 -18
  48. package/dist/generative-ui/spec.d.ts +0 -8
  49. package/dist/generative-ui/spec.js +0 -12
  50. package/dist/index.d.ts +1 -0
  51. package/dist/index.js +1 -0
  52. package/dist/mcp/dispatcher.d.ts +0 -7
  53. package/dist/mcp/dispatcher.js +0 -1
  54. package/dist/mcp/explorer.d.ts +0 -21
  55. package/dist/mcp/http.d.ts +3 -30
  56. package/dist/mcp/http.js +14 -0
  57. package/dist/mcp/index.d.ts +1 -1
  58. package/dist/mcp/index.js +1 -1
  59. package/dist/mcp/json.d.ts +0 -1
  60. package/dist/mcp/jsonRpc.d.ts +0 -2
  61. package/dist/mcp/metadata.d.ts +0 -15
  62. package/dist/mcp/routes.d.ts +2 -12
  63. package/dist/mcp/routes.js +6 -2
  64. package/dist/mcp/sdk.d.ts +0 -12
  65. package/dist/mcp/tools.d.ts +0 -18
  66. package/dist/mcp/tools.js +0 -1
  67. package/dist/mcp/zodJsonSchema.d.ts +0 -4
  68. package/dist/mcp/zodJsonSchema.js +0 -5
  69. package/dist/mcp-oauth-client/loopback.d.ts +0 -5
  70. package/dist/mcp-oauth-client/loopback.js +0 -6
  71. package/dist/mcp-oauth-client/oauth.d.ts +0 -14
  72. package/dist/mcp-oauth-client/oauth.js +0 -16
  73. package/dist/mcp-oauth-client/state.d.ts +0 -3
  74. package/dist/sandbox/runtime.d.ts +0 -15
  75. package/dist/sandbox/runtime.js +0 -25
  76. package/dist/skills/githubSkills.d.ts +51 -0
  77. package/dist/skills/githubSkills.js +172 -0
  78. package/dist/skills/index.d.ts +2 -0
  79. package/dist/skills/index.js +2 -0
  80. package/dist/skills/skillRef.d.ts +18 -0
  81. package/dist/skills/skillRef.js +168 -0
  82. package/package.json +1 -1
@@ -3,33 +3,20 @@ import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js";
3
3
  import type { McpOAuthState } from "./state.js";
4
4
  export type McpOAuthStorage = {
5
5
  load: () => McpOAuthState | undefined;
6
- /** undefined clears everything for the server. */
7
6
  save: (state: McpOAuthState | undefined) => void;
8
7
  };
9
8
  export type McpOAuthProviderOptions = {
10
9
  storage: McpOAuthStorage;
11
- /** `client_name` sent with dynamic client registration. */
12
10
  clientName: string;
13
- /** `scope` sent with registration and, by `authorizeMcpServer` without `connectAs`, with the authorization request. Default: none. */
14
11
  scope?: string;
15
- /** Where the browser comes back to. Set only for the interactive sign-in: without it the provider never starts one. */
16
12
  redirectUrl?: string;
17
- /** Opens the authorization URL. Required with redirectUrl. */
18
13
  redirectToAuthorization?: (url: URL) => void | Promise<void>;
19
- /** Message of the UnauthorizedError thrown when a non-interactive provider would need a browser. */
20
14
  signInRequiredMessage?: string;
21
- /**
22
- * When the provider can save a registered client.
23
- * - `"interactive"` (default): only with redirectUrl and redirectToAuthorization, so a non-interactive 401 stops before any registration request.
24
- * - `"always"`: also when not interactive, so the SDK never throws for want of somewhere to keep the result.
25
- */
26
15
  clientRegistration?: "interactive" | "always";
27
- /** Stamp `obtained_at` (from `now`) on saved tokens, for `isAccessTokenExpiring`. Default true. */
28
16
  stampObtainedAt?: boolean;
29
17
  now?: () => number;
30
18
  };
31
19
  export type McpOAuthProvider = OAuthClientProvider & {
32
- /** The `state` sent with the latest authorization request, for the redirect handler to check. */
33
20
  readonly pendingState: string | undefined;
34
21
  };
35
22
  /** True when tokens are stored, so the server counts as signed in. */
@@ -56,7 +43,6 @@ export type McpClientInfo = {
56
43
  export declare function authorizeMcpServer(args: {
57
44
  url: string;
58
45
  provider: McpOAuthProvider;
59
- /** The authorization code from the redirect. Created before the browser opens; it may reject (cancelled, timed out). */
60
46
  code: Promise<string>;
61
47
  fetch?: FetchLike;
62
48
  connectAs?: McpClientInfo;
@@ -1,10 +1,4 @@
1
1
  import { randomToken } from "../crypto/random.js";
2
- // MCP authorization (OAuth 2.1 with PKCE and dynamic client registration) for desktop apps. No Electron imports:
3
- // the app supplies the storage, the redirect and the browser.
4
- // The SDK is an optional peer, imported on first use and never at module load, so the package root stays loadable
5
- // in Convex's V8 runtime without it. Each import() is awaited directly in a try block (not inside Promise.all):
6
- // esbuild (Convex, Electron main) and Metro then treat a missing SDK as optional, and still bundle it when it is
7
- // installed. tests-node/bundle.mjs checks this with Convex's esbuild.
8
2
  const SDK_MISSING = "The MCP client OAuth helpers need the @modelcontextprotocol/sdk package";
9
3
  async function loadSdkAuth() {
10
4
  try {
@@ -24,7 +18,6 @@ async function loadSdkClient() {
24
18
  throw new Error(SDK_MISSING, { cause: error });
25
19
  }
26
20
  }
27
- // The SDK reads "no redirect URL" as a client-credentials flow, so a provider that only refreshes still needs one. It is never sent anywhere.
28
21
  const REFRESH_ONLY_REDIRECT = "http://127.0.0.1/callback";
29
22
  const DEFAULT_SIGN_IN_REQUIRED = "Sign-in required";
30
23
  /** True when tokens are stored, so the server counts as signed in. */
@@ -78,7 +71,6 @@ export function createMcpOAuthProvider(options) {
78
71
  },
79
72
  clientInformation() {
80
73
  const saved = storage.load()?.clientInformation;
81
- // The loopback port changes on every sign-in, so a client registered for another redirect cannot be reused.
82
74
  if (interactive && redirectUrl && saved?.redirect_uris && !saved.redirect_uris.includes(redirectUrl))
83
75
  return undefined;
84
76
  return saved;
@@ -98,8 +90,6 @@ export function createMcpOAuthProvider(options) {
98
90
  return verifier;
99
91
  },
100
92
  redirectToAuthorization(url) {
101
- // Rejects rather than throws: the SDK's UnauthorizedError class is only reachable once the SDK is loaded.
102
- // The SDK awaits this call, so its flows see the same error either way.
103
93
  if (!interactive || !redirectToAuthorization) {
104
94
  return loadSdkAuth().then(({ UnauthorizedError }) => {
105
95
  throw new UnauthorizedError(signInRequiredMessage);
@@ -118,7 +108,6 @@ export function createMcpOAuthProvider(options) {
118
108
  verifier = undefined;
119
109
  },
120
110
  };
121
- // Without this the SDK cannot register a client, so a 401 stops before any registration request.
122
111
  if (interactive || options.clientRegistration === "always") {
123
112
  provider.saveClientInformation = (info) => {
124
113
  const registered = "redirect_uris" in info ? info.redirect_uris : undefined;
@@ -135,7 +124,6 @@ export function createMcpOAuthProvider(options) {
135
124
  * same discovery (resource metadata from WWW-Authenticate or the well-known URL), then `code` is exchanged by `finishAuth`.
136
125
  */
137
126
  export async function authorizeMcpServer(args) {
138
- // A rejection that arrives before we await it must not surface as unhandled.
139
127
  args.code.catch(() => undefined);
140
128
  if (args.connectAs)
141
129
  return connectThenAuthorize({ ...args, connectAs: args.connectAs });
@@ -180,7 +168,6 @@ export async function refreshMcpOAuth(args) {
180
168
  return false;
181
169
  }
182
170
  }
183
- // Sign out waits for this at most: a slow authorization server must not hold it up.
184
171
  const REVOKE_TIMEOUT_MS = 3000;
185
172
  /**
186
173
  * Best-effort token revocation (RFC 7009) before the local tokens are cleared. Only when the authorization server advertises a
@@ -195,12 +182,10 @@ export async function revokeMcpOAuth(args) {
195
182
  const fetchFn = (input, init) => (args.fetch ?? fetch)(input, { ...init, signal });
196
183
  try {
197
184
  const { discoverAuthorizationServerMetadata, discoverOAuthServerInfo } = await loadSdkAuth();
198
- // The stored issuer is the server the tokens came from; without one, discover it from the MCP server.
199
185
  const issuer = tokens.issuer ?? clientInformation?.issuer;
200
186
  const metadata = issuer
201
187
  ? await discoverAuthorizationServerMetadata(issuer, { fetchFn })
202
188
  : (await discoverOAuthServerInfo(args.url, { fetchFn })).authorizationServerMetadata;
203
- // The OpenID metadata type has no field for it, though a server may send one.
204
189
  const endpoint = metadata && "revocation_endpoint" in metadata && typeof metadata.revocation_endpoint === "string"
205
190
  ? metadata.revocation_endpoint
206
191
  : undefined;
@@ -219,7 +204,6 @@ export async function revokeMcpOAuth(args) {
219
204
  });
220
205
  return response.ok;
221
206
  };
222
- // The refresh token first: revoking it may also end the access token, and it is the longer-lived one.
223
207
  const outcomes = await Promise.all([...(tokens.refresh_token ? [revoke(tokens.refresh_token, "refresh_token")] : []), revoke(tokens.access_token, "access_token")].map((work) => work.catch(() => false)));
224
208
  return outcomes.some(Boolean);
225
209
  }
@@ -6,9 +6,7 @@ export type McpOAuthTokens = {
6
6
  expires_in?: number;
7
7
  scope?: string;
8
8
  id_token?: string;
9
- /** Stamped by the SDK: the authorization server these tokens came from. */
10
9
  issuer?: string;
11
- /** Stamped by the provider when the tokens are saved (`stampObtainedAt`), because `expires_in` is relative. */
12
10
  obtained_at?: number;
13
11
  [key: string]: unknown;
14
12
  };
@@ -16,7 +14,6 @@ export type McpOAuthClientInformation = {
16
14
  client_id: string;
17
15
  client_secret?: string;
18
16
  redirect_uris?: string[];
19
- /** Stamped by the SDK: the authorization server this client was registered with. */
20
17
  issuer?: string;
21
18
  [key: string]: unknown;
22
19
  };
@@ -1,28 +1,16 @@
1
1
  import { type JsonInput, type JsonValue } from "../mcp/json.js";
2
2
  export type SandboxTool = {
3
3
  readonly name: string;
4
- /** true for tools that change state; counted against `maxMutatingCalls`. */
5
4
  readonly mutating: boolean;
6
- /**
7
- * Receives the JSON text of the single argument object and resolves to the
8
- * JSON text of the result. A rejection's message is what the script sees.
9
- */
10
5
  readonly invoke: (argsJson: string) => Promise<string>;
11
6
  };
12
7
  export type ExecuteLimits = {
13
- /** Wall clock for the whole execution, including time spent in tools. */
14
8
  readonly deadlineMs: number;
15
- /** QuickJS heap cap. */
16
9
  readonly memoryBytes: number;
17
- /** QuickJS stack cap. */
18
10
  readonly stackBytes: number;
19
- /** Total tool calls per execution. */
20
11
  readonly maxCalls: number;
21
- /** Subset cap for tools that change state. */
22
12
  readonly maxMutatingCalls: number;
23
- /** `console` lines kept; the rest are counted in one closing line. */
24
13
  readonly maxLogLines: number;
25
- /** Characters kept per `console` line. */
26
14
  readonly maxLogLineChars: number;
27
15
  };
28
16
  export declare const DEFAULT_EXECUTE_LIMITS: ExecuteLimits;
@@ -30,7 +18,6 @@ export type SandboxCallRecord = {
30
18
  readonly name: string;
31
19
  readonly ms: number;
32
20
  readonly ok: boolean;
33
- /** Set when `onCall` returned a stub, so the tool never ran. */
34
21
  readonly skipped?: true;
35
22
  };
36
23
  type ExecuteTelemetry = {
@@ -66,9 +53,7 @@ export type SandboxCallDecision = {
66
53
  readonly stub: JsonInput;
67
54
  };
68
55
  export type SandboxOptions = {
69
- /** JSON-serialisable values set as VM globals before the script runs, for example `{ args }`. */
70
56
  readonly globals?: Readonly<Record<string, JsonInput>>;
71
- /** Called before each tool call. A throw or rejection refuses the call with its message. */
72
57
  readonly onCall?: (call: SandboxCall) => SandboxCallDecision | Promise<SandboxCallDecision>;
73
58
  };
74
59
  /**
@@ -10,11 +10,6 @@ export const DEFAULT_EXECUTE_LIMITS = {
10
10
  };
11
11
  const QUICKJS_MISSING = "The code sandbox needs the quickjs-emscripten-core and @jitl/quickjs-singlefile-cjs-release-sync packages, in a Node runtime";
12
12
  let modulePromise;
13
- // QuickJS is an optional peer, imported on first use and never at module load, so the package root stays loadable
14
- // without it and V8 bundles of the root carry no WASM. Each import() is awaited directly in a try block, as in
15
- // mcp-oauth-client/oauth.ts. The "browser" field in package.json maps both packages to empty modules for browser-platform
16
- // bundles (Convex V8), whose bundler would otherwise follow the import into the variant's Node built-ins.
17
- // tests-node/bundle.mjs checks both.
18
13
  async function importQuickJs() {
19
14
  try {
20
15
  const core = await import("quickjs-emscripten-core");
@@ -29,10 +24,8 @@ async function importQuickJs() {
29
24
  }
30
25
  async function importModule() {
31
26
  const { core, variant } = await importQuickJs();
32
- // The variant is CommonJS: Node and bundlers nest its default export differently, which the core unwraps.
33
27
  return core.newQuickJSWASMModuleFromVariant(Promise.resolve(variant));
34
28
  }
35
- /** Loads the WASM module once per process; a failed load is retried next call. */
36
29
  function loadModule() {
37
30
  if (modulePromise === undefined) {
38
31
  modulePromise = importModule().catch((err) => {
@@ -42,13 +35,6 @@ function loadModule() {
42
35
  }
43
36
  return modulePromise;
44
37
  }
45
- /**
46
- * Globals the script sees. `tools` is a lazy proxy so any name routes to the
47
- * host without the catalog living inside the VM; `search` is an ordinary tool
48
- * the host supplies. `console` hands lines to the host instead of printing.
49
- * Host `globals` arrive as JSON text and may not replace anything already
50
- * global.
51
- */
52
38
  const PRELUDE = `
53
39
  for (const [name, value] of Object.entries(JSON.parse(globalThis.__globals))) {
54
40
  if (name in globalThis || name === "tools" || name === "console" || name.startsWith("__")) {
@@ -102,7 +88,6 @@ ${code}
102
88
  return json;
103
89
  });`;
104
90
  }
105
- /** Turns a value dumped out of the VM (usually a thrown Error) into one line. */
106
91
  function describeThrown(dumped) {
107
92
  if (isJsonObject(dumped) && typeof dumped.message === "string") {
108
93
  return typeof dumped.name === "string" && dumped.name !== "" ? `${dumped.name}: ${dumped.message}` : dumped.message;
@@ -126,7 +111,6 @@ export async function runSandboxedScript(code, tools, limitOverrides = {}, optio
126
111
  const startedAt = Date.now();
127
112
  const deadline = startedAt + limits.deadlineMs;
128
113
  const calls = [];
129
- // Collected on the host as they are written, so a failed run still returns them.
130
114
  const logs = [];
131
115
  let droppedLogs = 0;
132
116
  const finish = (result) => {
@@ -151,10 +135,7 @@ export async function runSandboxedScript(code, tools, limitOverrides = {}, optio
151
135
  const pending = new Set();
152
136
  let totalCalls = 0;
153
137
  let mutatingCalls = 0;
154
- // Host handlers can settle after this function has returned (a deadline hit
155
- // while a slow tool is still running). Touching the vm then aborts the process.
156
138
  let alive = true;
157
- /** Asks `onCall`, then runs the tool unless it refused or stubbed the call. */
158
139
  const callTool = async (tool, argsJson) => {
159
140
  if (options.onCall !== undefined) {
160
141
  const args = JSON.parse(argsJson);
@@ -197,7 +178,6 @@ export async function runSandboxedScript(code, tools, limitOverrides = {}, optio
197
178
  rejectWith(`Mutating tool call limit (${limits.maxMutatingCalls}) reached`);
198
179
  return deferred.handle;
199
180
  }
200
- // Counted before onCall, so refused and stubbed calls use up the caps like real ones.
201
181
  totalCalls += 1;
202
182
  if (tool.mutating)
203
183
  mutatingCalls += 1;
@@ -226,10 +206,6 @@ export async function runSandboxedScript(code, tools, limitOverrides = {}, optio
226
206
  }
227
207
  const promise = evaluated.value;
228
208
  try {
229
- // Drive the VM: run microtasks, then either finish, wait for the next
230
- // host tool to settle, or give up at the deadline. Jobs are pumped before
231
- // the deadline check so an interrupt or OOM thrown inside the script
232
- // surfaces as its own message rather than the generic deadline one.
233
209
  for (;;) {
234
210
  const jobs = runtime.executePendingJobs();
235
211
  if (jobs.error) {
@@ -249,7 +225,6 @@ export async function runSandboxedScript(code, tools, limitOverrides = {}, optio
249
225
  state.error.dispose();
250
226
  return fail(message);
251
227
  }
252
- // Pending: `state.error` is a plain host Error here, not a handle.
253
228
  if (Date.now() > deadline) {
254
229
  return fail(`Execution exceeded ${limits.deadlineMs}ms`);
255
230
  }
@@ -0,0 +1,51 @@
1
+ import { type SkillRef } from "./skillRef.js";
2
+ export type GithubFetch = (url: string) => Promise<Response>;
3
+ export declare const SKILL_MAX_FILES = 100;
4
+ export declare const SKILL_MAX_TEXT_BYTES: number;
5
+ export declare const SKILL_MAX_BINARY_BYTES: number;
6
+ export declare const SKILL_MAX_TOTAL_BYTES: number;
7
+ export declare const SKILL_CHOOSER_MAX = 25;
8
+ export interface GithubTreeFile {
9
+ path: string;
10
+ sha: string;
11
+ size: number;
12
+ }
13
+ export interface GithubSkillRepo {
14
+ owner: string;
15
+ repo: string;
16
+ ref: string;
17
+ explicitRef: boolean;
18
+ commitSha: string;
19
+ files: GithubTreeFile[];
20
+ }
21
+ export interface SkillCandidate {
22
+ name: string;
23
+ path: string;
24
+ description: string;
25
+ }
26
+ export interface SkillBundleFile {
27
+ path: string;
28
+ kind: "text" | "binary";
29
+ text?: string;
30
+ base64?: string;
31
+ size: number;
32
+ }
33
+ export interface SkillBundle {
34
+ name: string;
35
+ description: string;
36
+ path: string;
37
+ instructions: string;
38
+ contentHash: string;
39
+ files: SkillBundleFile[];
40
+ skipped: string[];
41
+ }
42
+ export declare class GithubSkillError extends Error {
43
+ }
44
+ export declare function resolveGithubSkillRepo(gh: GithubFetch, skillRef: SkillRef): Promise<GithubSkillRepo>;
45
+ export declare function findSkillFolders(repo: GithubSkillRepo, skillRef: SkillRef): string[];
46
+ export declare function readSkillCandidate(gh: GithubFetch, repo: GithubSkillRepo, folder: string): Promise<SkillCandidate & {
47
+ text: string;
48
+ }>;
49
+ export declare function listSkillCandidates(gh: GithubFetch, repo: GithubSkillRepo, folders: string[]): Promise<SkillCandidate[]>;
50
+ export declare function readSkillBundle(gh: GithubFetch, repo: GithubSkillRepo, folder: string): Promise<SkillBundle>;
51
+ export declare function fetchSkillContentHash(gh: GithubFetch, repo: GithubSkillRepo, folder: string): Promise<string | null>;
@@ -0,0 +1,172 @@
1
+ import { bytesToBase64 } from "../crypto/encoding.js";
2
+ import { SKILL_FILE_NAME, discoverSkillFolders, hashSkillText, normalizeSkillText, parseSkillFrontmatter, skillFolderFiles, } from "./skillRef.js";
3
+ export const SKILL_MAX_FILES = 100;
4
+ export const SKILL_MAX_TEXT_BYTES = 256 * 1024;
5
+ export const SKILL_MAX_BINARY_BYTES = 2 * 1024 * 1024;
6
+ export const SKILL_MAX_TOTAL_BYTES = 4 * 1024 * 1024;
7
+ export const SKILL_CHOOSER_MAX = 25;
8
+ const GITHUB_API = "https://api.github.com";
9
+ function isRepoJson(data) {
10
+ return typeof data?.default_branch === "string";
11
+ }
12
+ function isCommitJson(data) {
13
+ return typeof data?.sha === "string";
14
+ }
15
+ function isTreeJson(data) {
16
+ return (Array.isArray(data?.tree) &&
17
+ data.tree.every((entry) => typeof entry.path === "string" &&
18
+ typeof entry.type === "string" &&
19
+ typeof entry.sha === "string"));
20
+ }
21
+ function isBlobJson(data) {
22
+ return typeof data?.content === "string" && typeof data.encoding === "string";
23
+ }
24
+ export class GithubSkillError extends Error {
25
+ }
26
+ async function githubJson(gh, url, isValid, what) {
27
+ const res = await gh(url);
28
+ if (res.status === 404 || res.status === 401 || res.status === 403) {
29
+ throw new GithubSkillError(`${what} not found, private or rate limited (GitHub ${res.status}). For a private repository, connect an authenticated GitHub account and use the MCP install tools.`);
30
+ }
31
+ if (!res.ok) {
32
+ throw new GithubSkillError(`${what} failed (GitHub ${res.status}).`);
33
+ }
34
+ const data = await res.json();
35
+ if (!isValid(data)) {
36
+ throw new GithubSkillError(`${what} returned an unexpected response.`);
37
+ }
38
+ return data;
39
+ }
40
+ function repoUrl(owner, repo, rest) {
41
+ return `${GITHUB_API}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}${rest}`;
42
+ }
43
+ export async function resolveGithubSkillRepo(gh, skillRef) {
44
+ const { owner, repo } = skillRef;
45
+ const ref = skillRef.ref ??
46
+ (await githubJson(gh, repoUrl(owner, repo, ""), isRepoJson, "Repository")).default_branch;
47
+ const commit = await githubJson(gh, repoUrl(owner, repo, `/commits/${encodeURIComponent(ref)}`), isCommitJson, "Commit");
48
+ const tree = await githubJson(gh, repoUrl(owner, repo, `/git/trees/${commit.sha}?recursive=1`), isTreeJson, "Repository tree");
49
+ if (tree.truncated === true) {
50
+ throw new GithubSkillError("Repository is too large to scan. Link to the skill folder or use a smaller repository.");
51
+ }
52
+ return {
53
+ owner,
54
+ repo,
55
+ ref,
56
+ explicitRef: skillRef.ref !== undefined,
57
+ commitSha: commit.sha,
58
+ files: tree.tree
59
+ .filter((entry) => entry.type === "blob")
60
+ .map((entry) => ({
61
+ path: entry.path,
62
+ sha: entry.sha,
63
+ size: entry.size ?? 0,
64
+ })),
65
+ };
66
+ }
67
+ function baseName(path) {
68
+ return path.slice(path.lastIndexOf("/") + 1);
69
+ }
70
+ export function findSkillFolders(repo, skillRef) {
71
+ const folders = discoverSkillFolders(repo.files.map((file) => file.path), skillRef.path);
72
+ if (skillRef.skill === undefined)
73
+ return folders;
74
+ const wanted = skillRef.skill.toLowerCase();
75
+ return folders.filter((folder) => baseName(folder).toLowerCase() === wanted);
76
+ }
77
+ async function fetchBlobBytes(gh, repo, file) {
78
+ const blob = await githubJson(gh, repoUrl(repo.owner, repo.repo, `/git/blobs/${file.sha}`), isBlobJson, `File ${file.path}`);
79
+ if (blob.encoding !== "base64") {
80
+ throw new GithubSkillError(`File ${file.path} has an unknown encoding.`);
81
+ }
82
+ const binary = atob(blob.content.replace(/\s/g, ""));
83
+ const bytes = new Uint8Array(binary.length);
84
+ for (let i = 0; i < binary.length; i += 1)
85
+ bytes[i] = binary.charCodeAt(i);
86
+ return bytes;
87
+ }
88
+ function folderFilePath(folder, relative) {
89
+ return folder === "" ? relative : `${folder}/${relative}`;
90
+ }
91
+ function decodeText(bytes) {
92
+ if (bytes.includes(0))
93
+ return null;
94
+ try {
95
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
96
+ }
97
+ catch {
98
+ return null;
99
+ }
100
+ }
101
+ export async function readSkillCandidate(gh, repo, folder) {
102
+ const file = repo.files.find((entry) => entry.path === folderFilePath(folder, SKILL_FILE_NAME));
103
+ if (file === undefined) {
104
+ throw new GithubSkillError(`No ${SKILL_FILE_NAME} in ${folder}.`);
105
+ }
106
+ const bytes = await fetchBlobBytes(gh, repo, file);
107
+ const text = normalizeSkillText(new TextDecoder().decode(bytes));
108
+ const meta = parseSkillFrontmatter(text, baseName(folder) || repo.repo);
109
+ return { ...meta, path: folder, text };
110
+ }
111
+ export async function listSkillCandidates(gh, repo, folders) {
112
+ const out = [];
113
+ for (const folder of folders.slice(0, SKILL_CHOOSER_MAX)) {
114
+ const { name, path, description } = await readSkillCandidate(gh, repo, folder);
115
+ out.push({ name, path, description });
116
+ }
117
+ return out;
118
+ }
119
+ export async function readSkillBundle(gh, repo, folder) {
120
+ const candidate = await readSkillCandidate(gh, repo, folder);
121
+ const relatives = skillFolderFiles(repo.files.map((file) => file.path), folder).filter((relative) => relative !== SKILL_FILE_NAME);
122
+ if (relatives.length + 1 > SKILL_MAX_FILES) {
123
+ throw new GithubSkillError(`Skill has more than ${SKILL_MAX_FILES} files.`);
124
+ }
125
+ const files = [];
126
+ const skipped = [];
127
+ let total = new TextEncoder().encode(candidate.text).length;
128
+ for (const relative of relatives) {
129
+ const entry = repo.files.find((file) => file.path === folderFilePath(folder, relative));
130
+ if (entry === undefined)
131
+ continue;
132
+ if (entry.size > SKILL_MAX_BINARY_BYTES) {
133
+ skipped.push(relative);
134
+ continue;
135
+ }
136
+ const bytes = await fetchBlobBytes(gh, repo, entry);
137
+ const text = decodeText(bytes);
138
+ const limit = text === null ? SKILL_MAX_BINARY_BYTES : SKILL_MAX_TEXT_BYTES;
139
+ if (bytes.length > limit) {
140
+ skipped.push(relative);
141
+ continue;
142
+ }
143
+ total += bytes.length;
144
+ if (total > SKILL_MAX_TOTAL_BYTES) {
145
+ throw new GithubSkillError("Skill files are larger than 4 MB in total.");
146
+ }
147
+ files.push(text === null
148
+ ? {
149
+ path: relative,
150
+ kind: "binary",
151
+ base64: bytesToBase64(bytes),
152
+ size: bytes.length,
153
+ }
154
+ : { path: relative, kind: "text", text, size: bytes.length });
155
+ }
156
+ return {
157
+ name: candidate.name,
158
+ description: candidate.description,
159
+ path: folder,
160
+ instructions: candidate.text,
161
+ contentHash: await hashSkillText(candidate.text),
162
+ files,
163
+ skipped,
164
+ };
165
+ }
166
+ export async function fetchSkillContentHash(gh, repo, folder) {
167
+ const exists = repo.files.some((entry) => entry.path === folderFilePath(folder, SKILL_FILE_NAME));
168
+ if (!exists)
169
+ return null;
170
+ const { text } = await readSkillCandidate(gh, repo, folder);
171
+ return hashSkillText(text);
172
+ }
@@ -0,0 +1,2 @@
1
+ export { discoverSkillFolders, hashSkillText, normalizeSkillText, parseSkillFrontmatter, parseSkillRef, skillFolderFiles, SKILL_FILE_NAME, type SkillFrontmatter, type SkillRef, } from "./skillRef.js";
2
+ export { GithubSkillError, SKILL_CHOOSER_MAX, SKILL_MAX_BINARY_BYTES, SKILL_MAX_FILES, SKILL_MAX_TEXT_BYTES, SKILL_MAX_TOTAL_BYTES, fetchSkillContentHash, findSkillFolders, listSkillCandidates, readSkillBundle, readSkillCandidate, resolveGithubSkillRepo, type GithubFetch, type GithubSkillRepo, type GithubTreeFile, type SkillCandidate, type SkillBundle, type SkillBundleFile, } from "./githubSkills.js";
@@ -0,0 +1,2 @@
1
+ export { discoverSkillFolders, hashSkillText, normalizeSkillText, parseSkillFrontmatter, parseSkillRef, skillFolderFiles, SKILL_FILE_NAME, } from "./skillRef.js";
2
+ export { GithubSkillError, SKILL_CHOOSER_MAX, SKILL_MAX_BINARY_BYTES, SKILL_MAX_FILES, SKILL_MAX_TEXT_BYTES, SKILL_MAX_TOTAL_BYTES, fetchSkillContentHash, findSkillFolders, listSkillCandidates, readSkillBundle, readSkillCandidate, resolveGithubSkillRepo, } from "./githubSkills.js";
@@ -0,0 +1,18 @@
1
+ export declare const SKILL_FILE_NAME = "SKILL.md";
2
+ export interface SkillRef {
3
+ owner: string;
4
+ repo: string;
5
+ ref?: string;
6
+ path?: string;
7
+ skill?: string;
8
+ }
9
+ export interface SkillFrontmatter {
10
+ name: string;
11
+ description: string;
12
+ }
13
+ export declare function parseSkillRef(input: string): SkillRef | null;
14
+ export declare function normalizeSkillText(text: string): string;
15
+ export declare function hashSkillText(text: string): Promise<string>;
16
+ export declare function parseSkillFrontmatter(text: string, folderName: string): SkillFrontmatter;
17
+ export declare function discoverSkillFolders(filePaths: string[], basePath: string | undefined): string[];
18
+ export declare function skillFolderFiles(filePaths: string[], folder: string): string[];