supertag-ai 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +51 -0
  3. package/dist/chunk-B3EVEGNZ.js +13 -0
  4. package/dist/chunk-B3EVEGNZ.js.map +1 -0
  5. package/dist/chunk-ES42FTPC.js +1068 -0
  6. package/dist/chunk-ES42FTPC.js.map +1 -0
  7. package/dist/chunk-L7S2TKUG.js +656 -0
  8. package/dist/chunk-L7S2TKUG.js.map +1 -0
  9. package/dist/connectors.d.ts +45 -0
  10. package/dist/connectors.js +39 -0
  11. package/dist/connectors.js.map +1 -0
  12. package/dist/core.d.ts +721 -0
  13. package/dist/core.js +3 -0
  14. package/dist/core.js.map +1 -0
  15. package/dist/environments/e2b.d.ts +69 -0
  16. package/dist/environments/e2b.js +268 -0
  17. package/dist/environments/e2b.js.map +1 -0
  18. package/dist/gateway.d.ts +59 -0
  19. package/dist/gateway.js +1215 -0
  20. package/dist/gateway.js.map +1 -0
  21. package/dist/harnesses/claude-code.d.ts +67 -0
  22. package/dist/harnesses/claude-code.js +565 -0
  23. package/dist/harnesses/claude-code.js.map +1 -0
  24. package/dist/harnesses/codex.d.ts +68 -0
  25. package/dist/harnesses/codex.js +690 -0
  26. package/dist/harnesses/codex.js.map +1 -0
  27. package/dist/index.d.ts +100 -0
  28. package/dist/index.js +4 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/resources/github.d.ts +80 -0
  31. package/dist/resources/github.js +374 -0
  32. package/dist/resources/github.js.map +1 -0
  33. package/dist/resources/linear.d.ts +25 -0
  34. package/dist/resources/linear.js +92 -0
  35. package/dist/resources/linear.js.map +1 -0
  36. package/dist/resources/slack.d.ts +25 -0
  37. package/dist/resources/slack.js +98 -0
  38. package/dist/resources/slack.js.map +1 -0
  39. package/dist/resources/teams.d.ts +27 -0
  40. package/dist/resources/teams.js +101 -0
  41. package/dist/resources/teams.js.map +1 -0
  42. package/dist/transport.d.ts +5 -0
  43. package/dist/transport.js +3 -0
  44. package/dist/transport.js.map +1 -0
  45. package/dist/worker.d.ts +634 -0
  46. package/dist/worker.js +3 -0
  47. package/dist/worker.js.map +1 -0
  48. package/package.json +127 -0
@@ -0,0 +1,374 @@
1
+ import { assertTagActionAllowed } from '../chunk-ES42FTPC.js';
2
+ import { createWriteStream } from 'fs';
3
+ import { mkdir, mkdtemp, rename, rm, access, readdir, lstat } from 'fs/promises';
4
+ import { homedir } from 'os';
5
+ import { join } from 'path';
6
+ import { Readable } from 'stream';
7
+ import { pipeline } from 'stream/promises';
8
+ import { pathToFileURL } from 'url';
9
+ import { extract } from 'tar';
10
+
11
+ var DEFAULT_API_BASE_URL = "https://api.github.com";
12
+ var EnvironmentGitHubCredentialProvider = class {
13
+ #environment;
14
+ constructor(options = {}) {
15
+ this.#environment = options.environment ?? process.env;
16
+ }
17
+ async resolve(connectorAccountId) {
18
+ const expectedAccount = this.#environment["SUPERTAG_WORKER_GITHUB_ACCOUNT_ID"]?.trim();
19
+ if (expectedAccount && expectedAccount !== connectorAccountId) {
20
+ throw new Error(
21
+ `Worker GitHub credential is configured for ${expectedAccount}, not ${connectorAccountId}`
22
+ );
23
+ }
24
+ const token = this.#environment["SUPERTAG_WORKER_GITHUB_TOKEN"]?.trim();
25
+ if (!token) {
26
+ throw new Error(
27
+ "SUPERTAG_WORKER_GITHUB_TOKEN is required for GitHub repository or hosted MCP access"
28
+ );
29
+ }
30
+ const apiBaseUrl = this.#environment["SUPERTAG_WORKER_GITHUB_API_BASE_URL"]?.trim();
31
+ return { token, ...apiBaseUrl ? { apiBaseUrl } : {} };
32
+ }
33
+ };
34
+ var GITHUB_PERMISSION_MCP_TOOLS = {
35
+ "contents:read": ["get_file_contents"],
36
+ "issues:read": ["issue_read"],
37
+ "pull-requests:read": ["pull_request_read"]
38
+ };
39
+ var GitHubMcpToolProvisioner = class {
40
+ provider = "github";
41
+ #credentials;
42
+ #endpoint;
43
+ constructor(options) {
44
+ this.#credentials = options.credentials;
45
+ this.#endpoint = hostedMcpEndpoint(options.endpoint);
46
+ }
47
+ async provision(context) {
48
+ const actionsByAccount = githubMcpActionsByAccount(context);
49
+ if (actionsByAccount.size === 0) return void 0;
50
+ const contributions = [];
51
+ let index = 0;
52
+ for (const [connectorAccountId, actions] of actionsByAccount) {
53
+ const credential = await this.#credentials.resolve(connectorAccountId);
54
+ const toolNames = githubMcpToolNames(actions);
55
+ index += 1;
56
+ contributions.push({
57
+ id: `github-mcp:${connectorAccountId}`,
58
+ kind: "tool",
59
+ required: true,
60
+ transport: "mcp-http",
61
+ configuration: {
62
+ serverName: index === 1 ? "github" : `github_${index}`,
63
+ url: this.#endpoint,
64
+ toolNames
65
+ },
66
+ secretRefs: [`worker://github/${encodeURIComponent(connectorAccountId)}/token`],
67
+ runtimeHeaders: {
68
+ Authorization: `Bearer ${credential.token}`,
69
+ "X-MCP-Tools": toolNames.join(","),
70
+ "X-MCP-Readonly": "true"
71
+ }
72
+ });
73
+ }
74
+ return { provider: this.provider, contributions };
75
+ }
76
+ };
77
+ function githubMcpActionsByAccount(context) {
78
+ const byAccount = /* @__PURE__ */ new Map();
79
+ for (const resource of context.task.authorization.resources) {
80
+ if (resource.provider !== "github" || !resource.sources.includes("permission-set") || !isRepositoryScope(resource.scope)) {
81
+ continue;
82
+ }
83
+ const supported = resource.actions.filter(isGitHubMcpAction);
84
+ if (supported.length === 0) continue;
85
+ const accountActions = byAccount.get(resource.connectorAccountId) ?? /* @__PURE__ */ new Set();
86
+ for (const action of supported) accountActions.add(action);
87
+ byAccount.set(resource.connectorAccountId, accountActions);
88
+ }
89
+ return byAccount;
90
+ }
91
+ function isGitHubMcpAction(action) {
92
+ return action in GITHUB_PERMISSION_MCP_TOOLS;
93
+ }
94
+ function githubMcpToolNames(actions) {
95
+ return [...new Set([...actions].flatMap((action) => [...GITHUB_PERMISSION_MCP_TOOLS[action]]))];
96
+ }
97
+ function hostedMcpEndpoint(value) {
98
+ const endpoint = new URL(value ?? "https://api.githubcopilot.com/mcp/");
99
+ if (endpoint.protocol !== "https:") throw new Error("GitHub MCP endpoint must use HTTPS");
100
+ return endpoint.href;
101
+ }
102
+ var GitHubApiRepositorySource = class {
103
+ #cacheDirectory;
104
+ #request;
105
+ constructor(options = {}) {
106
+ this.#cacheDirectory = options.cacheDirectory ?? join(homedir(), ".supertag", "cache", "github");
107
+ this.#request = options.request ?? fetch;
108
+ }
109
+ async materialize(input) {
110
+ const repositoryId = positiveIntegerText(input.repositoryId, "GitHub repository ID");
111
+ const apiBaseUrl = normalizeApiBaseUrl(input.credential.apiBaseUrl);
112
+ const repository = await this.#json(
113
+ `${apiBaseUrl}/repositories/${repositoryId}`,
114
+ input.credential.token,
115
+ "repository lookup"
116
+ );
117
+ const resolvedId = positiveIntegerText(repository["id"], "GitHub repository response ID");
118
+ if (resolvedId !== repositoryId) {
119
+ throw new Error(
120
+ `GitHub returned repository ${resolvedId} for requested repository ${repositoryId}`
121
+ );
122
+ }
123
+ const fullName = repositoryName(repository["full_name"]);
124
+ const defaultBranch = nonEmptyString(repository["default_branch"], "GitHub default branch");
125
+ const requestedRevision = input.revision?.trim() || defaultBranch;
126
+ const commit = await this.#json(
127
+ `${apiBaseUrl}/repos/${repositoryPath(fullName)}/commits/${encodeURIComponent(requestedRevision)}`,
128
+ input.credential.token,
129
+ "commit resolution"
130
+ );
131
+ const commitSha = commitShaFrom(commit["sha"]);
132
+ const repositoryCache = join(this.#cacheDirectory, repositoryId);
133
+ const workspace = join(repositoryCache, commitSha);
134
+ await mkdir(repositoryCache, { recursive: true });
135
+ if (!await pathExists(workspace)) {
136
+ await this.#downloadWorkspace({
137
+ apiBaseUrl,
138
+ fullName,
139
+ commitSha,
140
+ repositoryCache,
141
+ token: input.credential.token,
142
+ workspace
143
+ });
144
+ }
145
+ return { path: workspace, repositoryId, fullName, commitSha, requestedRevision };
146
+ }
147
+ async #downloadWorkspace(input) {
148
+ const temporary = await mkdtemp(join(input.repositoryCache, ".materializing-"));
149
+ const archivePath = join(temporary, "repository.tar.gz");
150
+ const extractedPath = join(temporary, "workspace");
151
+ try {
152
+ const archiveUrl = `${input.apiBaseUrl}/repos/${repositoryPath(input.fullName)}/tarball/${input.commitSha}`;
153
+ let response = await this.#request(archiveUrl, {
154
+ redirect: "manual",
155
+ headers: githubHeaders(input.token, "application/vnd.github+json")
156
+ });
157
+ if (isRedirect(response.status)) {
158
+ const location = response.headers.get("location");
159
+ if (location === null) {
160
+ throw new Error("GitHub repository archive redirect did not include a location");
161
+ }
162
+ const redirectUrl = safeGitHubArchiveRedirect(archiveUrl, location);
163
+ response = await this.#request(redirectUrl, {
164
+ redirect: "error",
165
+ headers: githubHeaders(input.token, "application/vnd.github+json")
166
+ });
167
+ }
168
+ if (!response.ok || response.body === null) {
169
+ throw new Error(`GitHub repository archive download failed with HTTP ${response.status}`);
170
+ }
171
+ await pipeline(
172
+ Readable.fromWeb(response.body),
173
+ createWriteStream(archivePath, { mode: 384 })
174
+ );
175
+ await mkdir(extractedPath);
176
+ await extract({
177
+ cwd: extractedPath,
178
+ file: archivePath,
179
+ preservePaths: false,
180
+ strict: true,
181
+ strip: 1
182
+ });
183
+ await assertSafeWorkspaceTree(extractedPath);
184
+ try {
185
+ await rename(extractedPath, input.workspace);
186
+ } catch (error) {
187
+ if (!await pathExists(input.workspace)) throw error;
188
+ }
189
+ } finally {
190
+ await rm(temporary, { force: true, recursive: true });
191
+ }
192
+ }
193
+ async #json(url, token, operation) {
194
+ const response = await this.#request(url, {
195
+ redirect: "error",
196
+ headers: githubHeaders(token, "application/vnd.github+json")
197
+ });
198
+ if (!response.ok) {
199
+ throw new Error(`GitHub ${operation} failed with HTTP ${response.status}`);
200
+ }
201
+ const value = await response.json();
202
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
203
+ throw new Error(`GitHub ${operation} returned an invalid response`);
204
+ }
205
+ return value;
206
+ }
207
+ };
208
+ function isRedirect(status) {
209
+ return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
210
+ }
211
+ function safeGitHubArchiveRedirect(requestUrl, location) {
212
+ const source = new URL(requestUrl);
213
+ const destination = new URL(location, source);
214
+ if (destination.protocol !== "https:" || destination.username.length > 0 || destination.password.length > 0) {
215
+ throw new Error("GitHub repository archive redirected to an unsafe URL");
216
+ }
217
+ const officialCodeload = source.hostname === "api.github.com" && destination.hostname === "codeload.github.com";
218
+ if (destination.origin !== source.origin && !officialCodeload) {
219
+ throw new Error(
220
+ `GitHub repository archive redirected to untrusted host ${destination.hostname}`
221
+ );
222
+ }
223
+ return destination.href;
224
+ }
225
+ var GitHubRepositoryWorkspaceMaterializer = class {
226
+ #credentials;
227
+ #source;
228
+ #mountPath;
229
+ constructor(options) {
230
+ this.#credentials = options.credentials;
231
+ this.#source = options.source ?? new GitHubApiRepositorySource();
232
+ this.#mountPath = options.mountPath ?? "workspace";
233
+ }
234
+ async materialize(context) {
235
+ const target = selectRepositoryTarget(context);
236
+ if (target === void 0) return void 0;
237
+ if ("choices" in target) {
238
+ return {
239
+ id: "github-repository-selection-required",
240
+ kind: "instruction",
241
+ required: true,
242
+ scope: "task",
243
+ priority: -100,
244
+ content: `The request does not identify a GitHub repository. Ask the requester to name exactly one of: ${target.choices.join(", ")}. Do not inspect or make claims about a repository until they do.`
245
+ };
246
+ }
247
+ assertTagActionAllowed(context.task, {
248
+ connectorAccountId: target.resource.connectorAccountId,
249
+ scope: target.resource.scope,
250
+ action: "contents:read"
251
+ });
252
+ const credential = await this.#credentials.resolve(target.resource.connectorAccountId);
253
+ const workspace = await this.#source.materialize({
254
+ connectorAccountId: target.resource.connectorAccountId,
255
+ repositoryId: repositoryIdFromScope(target.resource.scope),
256
+ credential
257
+ });
258
+ return {
259
+ id: `github-workspace:${workspace.repositoryId}:${workspace.commitSha}`,
260
+ kind: "workspace",
261
+ required: true,
262
+ source: {
263
+ uri: pathToFileURL(workspace.path).href,
264
+ digest: `git:${workspace.commitSha}`,
265
+ provenance: {
266
+ provider: "github",
267
+ connectorAccountId: target.resource.connectorAccountId,
268
+ repositoryId: workspace.repositoryId,
269
+ repository: workspace.fullName,
270
+ requestedRevision: workspace.requestedRevision,
271
+ commitSha: workspace.commitSha,
272
+ targetSource: target.source
273
+ }
274
+ },
275
+ mountPath: this.#mountPath,
276
+ readOnly: true
277
+ };
278
+ }
279
+ };
280
+ function selectRepositoryTarget(context) {
281
+ const plan = context.task.workspacePlan;
282
+ if (plan.status === "none") return void 0;
283
+ if (plan.status === "unavailable") {
284
+ throw new Error(
285
+ `Tag ${context.task.tag.name} is not allowed to use GitHub repository ${plan.requested.join(", ")}`
286
+ );
287
+ }
288
+ if (plan.status === "selection-required") {
289
+ return {
290
+ choices: plan.choices.filter((choice) => choice.provider === "github").map((choice) => choice.reference ?? choice.scope).sort((left, right) => left.localeCompare(right))
291
+ };
292
+ }
293
+ if (plan.target.provider !== "github") return void 0;
294
+ return { resource: plan.target, source: plan.selectedBy };
295
+ }
296
+ function repositoryIdFromScope(scope) {
297
+ const match = /^repository:(\d+)$/u.exec(scope);
298
+ if (match?.[1] === void 0 || match[1] === "0") {
299
+ throw new Error(`Invalid GitHub repository scope ${scope}`);
300
+ }
301
+ return BigInt(match[1]).toString();
302
+ }
303
+ function isRepositoryScope(scope) {
304
+ return /^repository:[1-9][0-9]*$/u.test(scope);
305
+ }
306
+ function normalizeApiBaseUrl(value) {
307
+ const normalized = (value ?? DEFAULT_API_BASE_URL).trim().replace(/\/+$/u, "");
308
+ const url = new URL(normalized);
309
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && url.hostname === "127.0.0.1")) {
310
+ throw new Error("GitHub API base URL must use HTTPS (or loopback HTTP for tests)");
311
+ }
312
+ return url.toString().replace(/\/+$/u, "");
313
+ }
314
+ function githubHeaders(token, accept) {
315
+ if (!token.trim()) throw new Error("GitHub Worker token must not be empty");
316
+ return {
317
+ accept,
318
+ authorization: `Bearer ${token}`,
319
+ "user-agent": "supertag-worker",
320
+ "x-github-api-version": "2022-11-28"
321
+ };
322
+ }
323
+ function repositoryName(value) {
324
+ const name = nonEmptyString(value, "GitHub repository full name");
325
+ if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(name)) {
326
+ throw new Error("GitHub repository response has an invalid full name");
327
+ }
328
+ return name;
329
+ }
330
+ function repositoryPath(fullName) {
331
+ return fullName.split("/").map(encodeURIComponent).join("/");
332
+ }
333
+ function commitShaFrom(value) {
334
+ const sha = nonEmptyString(value, "GitHub commit SHA").toLowerCase();
335
+ if (!/^[0-9a-f]{40}$/u.test(sha)) throw new Error("GitHub returned an invalid commit SHA");
336
+ return sha;
337
+ }
338
+ function positiveIntegerText(value, label) {
339
+ const normalized = typeof value === "number" ? String(value) : String(value ?? "").trim();
340
+ if (!/^\d+$/u.test(normalized) || normalized === "0")
341
+ throw new Error(`${label} must be positive`);
342
+ return BigInt(normalized).toString();
343
+ }
344
+ function nonEmptyString(value, label) {
345
+ if (typeof value !== "string" || value.trim().length === 0)
346
+ throw new Error(`${label} is required`);
347
+ return value.trim();
348
+ }
349
+ async function pathExists(path) {
350
+ try {
351
+ await access(path);
352
+ return true;
353
+ } catch {
354
+ return false;
355
+ }
356
+ }
357
+ async function assertSafeWorkspaceTree(directory) {
358
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
359
+ const path = join(directory, entry.name);
360
+ const status = await lstat(path);
361
+ if (status.isSymbolicLink()) {
362
+ throw new Error(`GitHub repository archive contains unsupported symbolic link ${entry.name}`);
363
+ }
364
+ if (status.isDirectory()) {
365
+ await assertSafeWorkspaceTree(path);
366
+ } else if (!status.isFile()) {
367
+ throw new Error(`GitHub repository archive contains unsupported entry ${entry.name}`);
368
+ }
369
+ }
370
+ }
371
+
372
+ export { EnvironmentGitHubCredentialProvider, GITHUB_PERMISSION_MCP_TOOLS, GitHubApiRepositorySource, GitHubMcpToolProvisioner, GitHubRepositoryWorkspaceMaterializer };
373
+ //# sourceMappingURL=github.js.map
374
+ //# sourceMappingURL=github.js.map
@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ACrC;AAEA,SAAS,cAAA,CAAe,OAAgB,KAAA,EAAuB;AAC7D,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,CAAM,IAAA,GAAO,MAAA,KAAW,CAAA;AACvD,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,EAAG,KAAK,CAAA,YAAA,CAAc,CAAA;AACxC,EAAA,OAAO,MAAM,IAAA,EAAK;AACpB;AAEA,eAAe,WAAW,IAAA,EAAgC;AACxD,EAAA,IAAI;AACF,IAAA,MAAM,OAAO,IAAI,CAAA;AACjB,IAAA,OAAO,IAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAEA,eAAe,wBAAwB,SAAA,EAAkC;AACvE,EAAA,KAAA,MAAW,KAAA,IAAS,MAAM,OAAA,CAAQ,SAAA,EAAW,EAAE,aAAA,EAAe,IAAA,EAAM,CAAA,EAAG;AACrE,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,SAAA,EAAW,KAAA,CAAM,IAAI,CAAA;AACvC,IAAA,MAAM,MAAA,GAAS,MAAM,KAAA,CAAM,IAAI,CAAA;AAC/B,IAAA,IAAI,MAAA,CAAO,gBAAe,EAAG;AAC3B,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,6DAAA,EAAgE,KAAA,CAAM,IAAI,CAAA,CAAE,CAAA;AAAA,IAC9F;AACA,IAAA,IAAI,MAAA,CAAO,aAAY,EAAG;AACxB,MAAA,MAAM,wBAAwB,IAAI,CAAA;AAAA,IACpC,CAAA,MAAA,IAAW,CAAC,MAAA,CAAO,MAAA,EAAO,EAAG;AAC3B,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,qDAAA,EAAwD,KAAA,CAAM,IAAI,CAAA,CAAE,CAAA;AAAA,IACtF;AAAA,EACF;AACF","file":"github.js","sourcesContent":["import { createWriteStream } from \"node:fs\";\nimport { access, lstat, mkdir, mkdtemp, readdir, rename, rm } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n assertTagActionAllowed,\n type MaterializationContext,\n type ToolBundle,\n type ToolProvisioner,\n type WorkspaceMaterialization,\n type WorkspaceMaterializer,\n} from \"@supertag/worker-sdk\";\nimport { extract } from \"tar\";\n\nconst DEFAULT_API_BASE_URL = \"https://api.github.com\";\n\nexport interface GitHubWorkerCredential {\n readonly token: string;\n readonly apiBaseUrl?: string;\n}\n\nexport interface GitHubWorkerCredentialProvider {\n resolve(connectorAccountId: string): Promise<GitHubWorkerCredential>;\n}\n\nexport interface EnvironmentGitHubCredentialProviderOptions {\n readonly environment?: Readonly<Record<string, string | undefined>>;\n}\n\n/** Resolves a Worker-local GitHub credential without involving the Gateway secret store. */\nexport class EnvironmentGitHubCredentialProvider implements GitHubWorkerCredentialProvider {\n readonly #environment: Readonly<Record<string, string | undefined>>;\n\n constructor(options: EnvironmentGitHubCredentialProviderOptions = {}) {\n this.#environment = options.environment ?? process.env;\n }\n\n async resolve(connectorAccountId: string): Promise<GitHubWorkerCredential> {\n const expectedAccount = this.#environment[\"SUPERTAG_WORKER_GITHUB_ACCOUNT_ID\"]?.trim();\n if (expectedAccount && expectedAccount !== connectorAccountId) {\n throw new Error(\n `Worker GitHub credential is configured for ${expectedAccount}, not ${connectorAccountId}`,\n );\n }\n const token = this.#environment[\"SUPERTAG_WORKER_GITHUB_TOKEN\"]?.trim();\n if (!token) {\n throw new Error(\n \"SUPERTAG_WORKER_GITHUB_TOKEN is required for GitHub repository or hosted MCP access\",\n );\n }\n const apiBaseUrl = this.#environment[\"SUPERTAG_WORKER_GITHUB_API_BASE_URL\"]?.trim();\n return { token, ...(apiBaseUrl ? { apiBaseUrl } : {}) };\n }\n}\n\nexport const GITHUB_PERMISSION_MCP_TOOLS = {\n \"contents:read\": [\"get_file_contents\"],\n \"issues:read\": [\"issue_read\"],\n \"pull-requests:read\": [\"pull_request_read\"],\n} as const;\n\nexport type GitHubMcpAction = keyof typeof GITHUB_PERMISSION_MCP_TOOLS;\n\nexport interface GitHubMcpToolProvisionerOptions {\n readonly credentials: GitHubWorkerCredentialProvider;\n readonly endpoint?: string;\n}\n\n/** Configures GitHub's hosted MCP server from a Task's active Permission Sets. */\nexport class GitHubMcpToolProvisioner implements ToolProvisioner {\n readonly provider = \"github\";\n readonly #credentials: GitHubWorkerCredentialProvider;\n readonly #endpoint: string;\n\n constructor(options: GitHubMcpToolProvisionerOptions) {\n this.#credentials = options.credentials;\n this.#endpoint = hostedMcpEndpoint(options.endpoint);\n }\n\n async provision(context: MaterializationContext): Promise<ToolBundle | undefined> {\n const actionsByAccount = githubMcpActionsByAccount(context);\n if (actionsByAccount.size === 0) return undefined;\n const contributions = [];\n let index = 0;\n for (const [connectorAccountId, actions] of actionsByAccount) {\n const credential = await this.#credentials.resolve(connectorAccountId);\n const toolNames = githubMcpToolNames(actions);\n index += 1;\n contributions.push({\n id: `github-mcp:${connectorAccountId}`,\n kind: \"tool\" as const,\n required: true,\n transport: \"mcp-http\" as const,\n configuration: {\n serverName: index === 1 ? \"github\" : `github_${index}`,\n url: this.#endpoint,\n toolNames,\n },\n secretRefs: [`worker://github/${encodeURIComponent(connectorAccountId)}/token`],\n runtimeHeaders: {\n Authorization: `Bearer ${credential.token}`,\n \"X-MCP-Tools\": toolNames.join(\",\"),\n \"X-MCP-Readonly\": \"true\",\n },\n });\n }\n return { provider: this.provider, contributions };\n }\n}\n\nfunction githubMcpActionsByAccount(\n context: MaterializationContext,\n): Map<string, Set<GitHubMcpAction>> {\n const byAccount = new Map<string, Set<GitHubMcpAction>>();\n for (const resource of context.task.authorization.resources) {\n if (\n resource.provider !== \"github\" ||\n !resource.sources.includes(\"permission-set\") ||\n !isRepositoryScope(resource.scope)\n ) {\n continue;\n }\n const supported = resource.actions.filter(isGitHubMcpAction);\n if (supported.length === 0) continue;\n const accountActions = byAccount.get(resource.connectorAccountId) ?? new Set();\n for (const action of supported) accountActions.add(action);\n byAccount.set(resource.connectorAccountId, accountActions);\n }\n return byAccount;\n}\n\nfunction isGitHubMcpAction(action: string): action is GitHubMcpAction {\n return action in GITHUB_PERMISSION_MCP_TOOLS;\n}\n\nfunction githubMcpToolNames(actions: ReadonlySet<GitHubMcpAction>): readonly string[] {\n return [...new Set([...actions].flatMap((action) => [...GITHUB_PERMISSION_MCP_TOOLS[action]]))];\n}\n\nfunction hostedMcpEndpoint(value: string | undefined): string {\n const endpoint = new URL(value ?? \"https://api.githubcopilot.com/mcp/\");\n if (endpoint.protocol !== \"https:\") throw new Error(\"GitHub MCP endpoint must use HTTPS\");\n return endpoint.href;\n}\n\nexport interface GitHubRepositorySourceInput {\n readonly connectorAccountId: string;\n readonly repositoryId: string;\n readonly revision?: string;\n readonly credential: GitHubWorkerCredential;\n}\n\nexport interface ResolvedGitHubWorkspace {\n readonly path: string;\n readonly repositoryId: string;\n readonly fullName: string;\n readonly commitSha: string;\n readonly requestedRevision: string;\n}\n\nexport interface GitHubRepositorySource {\n materialize(input: GitHubRepositorySourceInput): Promise<ResolvedGitHubWorkspace>;\n}\n\nexport interface GitHubApiRepositorySourceOptions {\n readonly cacheDirectory?: string;\n readonly request?: typeof fetch;\n}\n\n/** Resolves a repository and immutable commit through GitHub, then caches its source archive. */\nexport class GitHubApiRepositorySource implements GitHubRepositorySource {\n readonly #cacheDirectory: string;\n readonly #request: typeof fetch;\n\n constructor(options: GitHubApiRepositorySourceOptions = {}) {\n this.#cacheDirectory =\n options.cacheDirectory ?? join(homedir(), \".supertag\", \"cache\", \"github\");\n this.#request = options.request ?? fetch;\n }\n\n async materialize(input: GitHubRepositorySourceInput): Promise<ResolvedGitHubWorkspace> {\n const repositoryId = positiveIntegerText(input.repositoryId, \"GitHub repository ID\");\n const apiBaseUrl = normalizeApiBaseUrl(input.credential.apiBaseUrl);\n const repository = await this.#json(\n `${apiBaseUrl}/repositories/${repositoryId}`,\n input.credential.token,\n \"repository lookup\",\n );\n const resolvedId = positiveIntegerText(repository[\"id\"], \"GitHub repository response ID\");\n if (resolvedId !== repositoryId) {\n throw new Error(\n `GitHub returned repository ${resolvedId} for requested repository ${repositoryId}`,\n );\n }\n const fullName = repositoryName(repository[\"full_name\"]);\n const defaultBranch = nonEmptyString(repository[\"default_branch\"], \"GitHub default branch\");\n const requestedRevision = input.revision?.trim() || defaultBranch;\n const commit = await this.#json(\n `${apiBaseUrl}/repos/${repositoryPath(fullName)}/commits/${encodeURIComponent(requestedRevision)}`,\n input.credential.token,\n \"commit resolution\",\n );\n const commitSha = commitShaFrom(commit[\"sha\"]);\n const repositoryCache = join(this.#cacheDirectory, repositoryId);\n const workspace = join(repositoryCache, commitSha);\n await mkdir(repositoryCache, { recursive: true });\n if (!(await pathExists(workspace))) {\n await this.#downloadWorkspace({\n apiBaseUrl,\n fullName,\n commitSha,\n repositoryCache,\n token: input.credential.token,\n workspace,\n });\n }\n return { path: workspace, repositoryId, fullName, commitSha, requestedRevision };\n }\n\n async #downloadWorkspace(input: {\n readonly apiBaseUrl: string;\n readonly fullName: string;\n readonly commitSha: string;\n readonly repositoryCache: string;\n readonly token: string;\n readonly workspace: string;\n }): Promise<void> {\n const temporary = await mkdtemp(join(input.repositoryCache, \".materializing-\"));\n const archivePath = join(temporary, \"repository.tar.gz\");\n const extractedPath = join(temporary, \"workspace\");\n try {\n const archiveUrl = `${input.apiBaseUrl}/repos/${repositoryPath(input.fullName)}/tarball/${input.commitSha}`;\n let response = await this.#request(archiveUrl, {\n redirect: \"manual\",\n headers: githubHeaders(input.token, \"application/vnd.github+json\"),\n });\n if (isRedirect(response.status)) {\n const location = response.headers.get(\"location\");\n if (location === null) {\n throw new Error(\"GitHub repository archive redirect did not include a location\");\n }\n const redirectUrl = safeGitHubArchiveRedirect(archiveUrl, location);\n response = await this.#request(redirectUrl, {\n redirect: \"error\",\n headers: githubHeaders(input.token, \"application/vnd.github+json\"),\n });\n }\n if (!response.ok || response.body === null) {\n throw new Error(`GitHub repository archive download failed with HTTP ${response.status}`);\n }\n await pipeline(\n Readable.fromWeb(response.body as import(\"node:stream/web\").ReadableStream),\n createWriteStream(archivePath, { mode: 0o600 }),\n );\n await mkdir(extractedPath);\n await extract({\n cwd: extractedPath,\n file: archivePath,\n preservePaths: false,\n strict: true,\n strip: 1,\n });\n await assertSafeWorkspaceTree(extractedPath);\n try {\n await rename(extractedPath, input.workspace);\n } catch (error) {\n if (!(await pathExists(input.workspace))) throw error;\n }\n } finally {\n await rm(temporary, { force: true, recursive: true });\n }\n }\n\n async #json(url: string, token: string, operation: string): Promise<Record<string, unknown>> {\n const response = await this.#request(url, {\n redirect: \"error\",\n headers: githubHeaders(token, \"application/vnd.github+json\"),\n });\n if (!response.ok) {\n throw new Error(`GitHub ${operation} failed with HTTP ${response.status}`);\n }\n const value: unknown = await response.json();\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`GitHub ${operation} returned an invalid response`);\n }\n return value as Record<string, unknown>;\n }\n}\n\nfunction isRedirect(status: number): boolean {\n return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;\n}\n\nfunction safeGitHubArchiveRedirect(requestUrl: string, location: string): string {\n const source = new URL(requestUrl);\n const destination = new URL(location, source);\n if (\n destination.protocol !== \"https:\" ||\n destination.username.length > 0 ||\n destination.password.length > 0\n ) {\n throw new Error(\"GitHub repository archive redirected to an unsafe URL\");\n }\n const officialCodeload =\n source.hostname === \"api.github.com\" && destination.hostname === \"codeload.github.com\";\n if (destination.origin !== source.origin && !officialCodeload) {\n throw new Error(\n `GitHub repository archive redirected to untrusted host ${destination.hostname}`,\n );\n }\n return destination.href;\n}\n\nexport interface GitHubRepositoryWorkspaceMaterializerOptions {\n readonly credentials: GitHubWorkerCredentialProvider;\n readonly source?: GitHubRepositorySource;\n readonly mountPath?: string;\n}\n\n/**\n * Materializes one GitHub repository workspace selected by the request or its\n * GitHub origin. Context Sets never participate in this selection: permissions bound\n * the eligible repositories, then this Worker-local extension performs retrieval.\n */\nexport class GitHubRepositoryWorkspaceMaterializer implements WorkspaceMaterializer {\n readonly #credentials: GitHubWorkerCredentialProvider;\n readonly #source: GitHubRepositorySource;\n readonly #mountPath: string;\n\n constructor(options: GitHubRepositoryWorkspaceMaterializerOptions) {\n this.#credentials = options.credentials;\n this.#source = options.source ?? new GitHubApiRepositorySource();\n this.#mountPath = options.mountPath ?? \"workspace\";\n }\n\n async materialize(\n context: MaterializationContext,\n ): Promise<WorkspaceMaterialization | undefined> {\n const target = selectRepositoryTarget(context);\n if (target === undefined) return undefined;\n if (\"choices\" in target) {\n return {\n id: \"github-repository-selection-required\",\n kind: \"instruction\",\n required: true,\n scope: \"task\",\n priority: -100,\n content: `The request does not identify a GitHub repository. Ask the requester to name exactly one of: ${target.choices.join(\", \")}. Do not inspect or make claims about a repository until they do.`,\n };\n }\n assertTagActionAllowed(context.task, {\n connectorAccountId: target.resource.connectorAccountId,\n scope: target.resource.scope,\n action: \"contents:read\",\n });\n const credential = await this.#credentials.resolve(target.resource.connectorAccountId);\n const workspace = await this.#source.materialize({\n connectorAccountId: target.resource.connectorAccountId,\n repositoryId: repositoryIdFromScope(target.resource.scope),\n credential,\n });\n return {\n id: `github-workspace:${workspace.repositoryId}:${workspace.commitSha}`,\n kind: \"workspace\",\n required: true,\n source: {\n uri: pathToFileURL(workspace.path).href,\n digest: `git:${workspace.commitSha}`,\n provenance: {\n provider: \"github\",\n connectorAccountId: target.resource.connectorAccountId,\n repositoryId: workspace.repositoryId,\n repository: workspace.fullName,\n requestedRevision: workspace.requestedRevision,\n commitSha: workspace.commitSha,\n targetSource: target.source,\n },\n },\n mountPath: this.#mountPath,\n readOnly: true,\n };\n }\n}\n\ntype GitHubRepositoryTarget = {\n readonly resource: {\n readonly connectorAccountId: string;\n readonly scope: string;\n readonly reference?: string;\n readonly actions: readonly string[];\n };\n readonly source: \"origin\" | \"request\" | \"default\";\n};\n\ntype GitHubRepositorySelection = GitHubRepositoryTarget | { readonly choices: readonly string[] };\n\nfunction selectRepositoryTarget(\n context: MaterializationContext,\n): GitHubRepositorySelection | undefined {\n const plan = context.task.workspacePlan;\n if (plan.status === \"none\") return undefined;\n if (plan.status === \"unavailable\") {\n throw new Error(\n `Tag ${context.task.tag.name} is not allowed to use GitHub repository ${plan.requested.join(\", \")}`,\n );\n }\n if (plan.status === \"selection-required\") {\n return {\n choices: plan.choices\n .filter((choice) => choice.provider === \"github\")\n .map((choice) => choice.reference ?? choice.scope)\n .sort((left, right) => left.localeCompare(right)),\n };\n }\n if (plan.target.provider !== \"github\") return undefined;\n return { resource: plan.target, source: plan.selectedBy };\n}\n\nfunction repositoryIdFromScope(scope: string): string {\n const match = /^repository:(\\d+)$/u.exec(scope);\n if (match?.[1] === undefined || match[1] === \"0\") {\n throw new Error(`Invalid GitHub repository scope ${scope}`);\n }\n return BigInt(match[1]).toString();\n}\n\nfunction isRepositoryScope(scope: string): boolean {\n return /^repository:[1-9][0-9]*$/u.test(scope);\n}\n\nfunction normalizeApiBaseUrl(value: string | undefined): string {\n const normalized = (value ?? DEFAULT_API_BASE_URL).trim().replace(/\\/+$/u, \"\");\n const url = new URL(normalized);\n if (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && url.hostname === \"127.0.0.1\")) {\n throw new Error(\"GitHub API base URL must use HTTPS (or loopback HTTP for tests)\");\n }\n return url.toString().replace(/\\/+$/u, \"\");\n}\n\nfunction githubHeaders(token: string, accept: string): Record<string, string> {\n if (!token.trim()) throw new Error(\"GitHub Worker token must not be empty\");\n return {\n accept,\n authorization: `Bearer ${token}`,\n \"user-agent\": \"supertag-worker\",\n \"x-github-api-version\": \"2022-11-28\",\n };\n}\n\nfunction repositoryName(value: unknown): string {\n const name = nonEmptyString(value, \"GitHub repository full name\");\n if (!/^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/u.test(name)) {\n throw new Error(\"GitHub repository response has an invalid full name\");\n }\n return name;\n}\n\nfunction repositoryPath(fullName: string): string {\n return fullName.split(\"/\").map(encodeURIComponent).join(\"/\");\n}\n\nfunction commitShaFrom(value: unknown): string {\n const sha = nonEmptyString(value, \"GitHub commit SHA\").toLowerCase();\n if (!/^[0-9a-f]{40}$/u.test(sha)) throw new Error(\"GitHub returned an invalid commit SHA\");\n return sha;\n}\n\nfunction positiveIntegerText(value: unknown, label: string): string {\n const normalized = typeof value === \"number\" ? String(value) : String(value ?? \"\").trim();\n if (!/^\\d+$/u.test(normalized) || normalized === \"0\")\n throw new Error(`${label} must be positive`);\n return BigInt(normalized).toString();\n}\n\nfunction nonEmptyString(value: unknown, label: string): string {\n if (typeof value !== \"string\" || value.trim().length === 0)\n throw new Error(`${label} is required`);\n return value.trim();\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function assertSafeWorkspaceTree(directory: string): Promise<void> {\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n const path = join(directory, entry.name);\n const status = await lstat(path);\n if (status.isSymbolicLink()) {\n throw new Error(`GitHub repository archive contains unsupported symbolic link ${entry.name}`);\n }\n if (status.isDirectory()) {\n await assertSafeWorkspaceTree(path);\n } else if (!status.isFile()) {\n throw new Error(`GitHub repository archive contains unsupported entry ${entry.name}`);\n }\n }\n}\n"]}
@@ -0,0 +1,25 @@
1
+ import { ToolProvisioner, MaterializationContext, ToolBundle } from '../worker.js';
2
+ import '../core.js';
3
+ import 'zod';
4
+
5
+ interface LinearMcpCredential {
6
+ readonly token: string;
7
+ /** Native Linear team scopes this credential is constrained to read. */
8
+ readonly allowedScopes: readonly string[];
9
+ }
10
+ interface LinearMcpCredentialProvider {
11
+ resolve(connectorAccountId: string): Promise<LinearMcpCredential>;
12
+ }
13
+ declare class EnvironmentLinearMcpCredentialProvider implements LinearMcpCredentialProvider {
14
+ #private;
15
+ constructor(environment?: Readonly<Record<string, string | undefined>>);
16
+ resolve(connectorAccountId: string): Promise<LinearMcpCredential>;
17
+ }
18
+ declare class LinearMcpToolProvisioner implements ToolProvisioner {
19
+ #private;
20
+ readonly provider = "linear";
21
+ constructor(credentials: LinearMcpCredentialProvider);
22
+ provision(context: MaterializationContext): Promise<ToolBundle | undefined>;
23
+ }
24
+
25
+ export { EnvironmentLinearMcpCredentialProvider, type LinearMcpCredential, type LinearMcpCredentialProvider, LinearMcpToolProvisioner };
@@ -0,0 +1,92 @@
1
+ // ../runtime/resources/linear/src/index.ts
2
+ var LINEAR_READ_ONLY_MCP_ENDPOINT = "https://mcp.linear.app/mcp/readonly";
3
+ var LINEAR_ISSUE_READ_TOOLS = ["list_issues", "get_issue", "list_comments"];
4
+ var EnvironmentLinearMcpCredentialProvider = class {
5
+ #environment;
6
+ constructor(environment = process.env) {
7
+ this.#environment = environment;
8
+ }
9
+ async resolve(connectorAccountId) {
10
+ requireMatch(this.#environment["SUPERTAG_WORKER_LINEAR_ACCOUNT_ID"], connectorAccountId);
11
+ return {
12
+ token: required(
13
+ this.#environment["SUPERTAG_WORKER_LINEAR_MCP_TOKEN"],
14
+ "SUPERTAG_WORKER_LINEAR_MCP_TOKEN"
15
+ ),
16
+ allowedScopes: requiredScopes(this.#environment["SUPERTAG_WORKER_LINEAR_ALLOWED_SCOPES"])
17
+ };
18
+ }
19
+ };
20
+ var LinearMcpToolProvisioner = class {
21
+ provider = "linear";
22
+ #credentials;
23
+ constructor(credentials) {
24
+ this.#credentials = credentials;
25
+ }
26
+ async provision(context) {
27
+ const scopesByAccount = issueReadScopes(context);
28
+ if (scopesByAccount.size === 0) return void 0;
29
+ const contributions = [];
30
+ let index = 0;
31
+ for (const [accountId, scopes] of scopesByAccount) {
32
+ const credential = await this.#credentials.resolve(accountId);
33
+ assertCovers(credential.allowedScopes, scopes);
34
+ index += 1;
35
+ contributions.push({
36
+ id: `linear-mcp:${accountId}`,
37
+ kind: "tool",
38
+ required: true,
39
+ transport: "mcp-http",
40
+ configuration: {
41
+ serverName: index === 1 ? "linear" : `linear_${index}`,
42
+ url: LINEAR_READ_ONLY_MCP_ENDPOINT,
43
+ toolNames: [...LINEAR_ISSUE_READ_TOOLS],
44
+ authorizedScopes: [...scopes]
45
+ },
46
+ secretRefs: [`worker://linear/${encodeURIComponent(accountId)}/token`],
47
+ runtimeHeaders: { Authorization: `Bearer ${credential.token}` }
48
+ });
49
+ }
50
+ return { provider: this.provider, contributions };
51
+ }
52
+ };
53
+ function issueReadScopes(context) {
54
+ const result = /* @__PURE__ */ new Map();
55
+ for (const resource of context.task.authorization.resources) {
56
+ if (resource.provider !== "linear" || !resource.sources.includes("permission-set") || !resource.actions.includes("issues:read") || !resource.scope.startsWith("team:"))
57
+ continue;
58
+ const scopes = result.get(resource.connectorAccountId) ?? /* @__PURE__ */ new Set();
59
+ scopes.add(resource.scope);
60
+ result.set(resource.connectorAccountId, scopes);
61
+ }
62
+ return result;
63
+ }
64
+ function assertCovers(allowed, scopes) {
65
+ const missing = [...scopes].filter((scope) => !allowed.includes(scope));
66
+ if (missing.length > 0)
67
+ throw new Error(
68
+ `Linear MCP credential does not natively cover authorized scopes: ${missing.join(", ")}`
69
+ );
70
+ }
71
+ function requiredScopes(value) {
72
+ const scopes = value?.split(",").map((scope) => scope.trim()).filter(Boolean) ?? [];
73
+ if (scopes.length === 0)
74
+ throw new Error(
75
+ "SUPERTAG_WORKER_LINEAR_ALLOWED_SCOPES is required to fail closed at the native resource boundary"
76
+ );
77
+ return [...new Set(scopes)];
78
+ }
79
+ function required(value, name) {
80
+ const normalized = value?.trim();
81
+ if (!normalized) throw new Error(`${name} is required`);
82
+ return normalized;
83
+ }
84
+ function requireMatch(configured, actual) {
85
+ const expected = configured?.trim();
86
+ if (expected && expected !== actual)
87
+ throw new Error(`Linear credential is configured for ${expected}, not ${actual}`);
88
+ }
89
+
90
+ export { EnvironmentLinearMcpCredentialProvider, LinearMcpToolProvisioner };
91
+ //# sourceMappingURL=linear.js.map
92
+ //# sourceMappingURL=linear.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../runtime/resources/linear/src/index.ts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CAAM,CAAA,oCAAA,EAAuC,QAAQ,CAAA,MAAA,EAAS,MAAM,CAAA,CAAE,CAAA;AACpF","file":"linear.js","sourcesContent":["import type { MaterializationContext, ToolBundle, ToolProvisioner } from \"@supertag/worker-sdk\";\n\nconst LINEAR_READ_ONLY_MCP_ENDPOINT = \"https://mcp.linear.app/mcp/readonly\";\nconst LINEAR_ISSUE_READ_TOOLS = [\"list_issues\", \"get_issue\", \"list_comments\"] as const;\n\nexport interface LinearMcpCredential {\n readonly token: string;\n /** Native Linear team scopes this credential is constrained to read. */\n readonly allowedScopes: readonly string[];\n}\n\nexport interface LinearMcpCredentialProvider {\n resolve(connectorAccountId: string): Promise<LinearMcpCredential>;\n}\n\nexport class EnvironmentLinearMcpCredentialProvider implements LinearMcpCredentialProvider {\n readonly #environment: Readonly<Record<string, string | undefined>>;\n\n constructor(environment: Readonly<Record<string, string | undefined>> = process.env) {\n this.#environment = environment;\n }\n\n async resolve(connectorAccountId: string): Promise<LinearMcpCredential> {\n requireMatch(this.#environment[\"SUPERTAG_WORKER_LINEAR_ACCOUNT_ID\"], connectorAccountId);\n return {\n token: required(\n this.#environment[\"SUPERTAG_WORKER_LINEAR_MCP_TOKEN\"],\n \"SUPERTAG_WORKER_LINEAR_MCP_TOKEN\",\n ),\n allowedScopes: requiredScopes(this.#environment[\"SUPERTAG_WORKER_LINEAR_ALLOWED_SCOPES\"]),\n };\n }\n}\n\nexport class LinearMcpToolProvisioner implements ToolProvisioner {\n readonly provider = \"linear\";\n readonly #credentials: LinearMcpCredentialProvider;\n\n constructor(credentials: LinearMcpCredentialProvider) {\n this.#credentials = credentials;\n }\n\n async provision(context: MaterializationContext): Promise<ToolBundle | undefined> {\n const scopesByAccount = issueReadScopes(context);\n if (scopesByAccount.size === 0) return undefined;\n const contributions = [];\n let index = 0;\n for (const [accountId, scopes] of scopesByAccount) {\n const credential = await this.#credentials.resolve(accountId);\n assertCovers(credential.allowedScopes, scopes);\n index += 1;\n contributions.push({\n id: `linear-mcp:${accountId}`,\n kind: \"tool\" as const,\n required: true,\n transport: \"mcp-http\" as const,\n configuration: {\n serverName: index === 1 ? \"linear\" : `linear_${index}`,\n url: LINEAR_READ_ONLY_MCP_ENDPOINT,\n toolNames: [...LINEAR_ISSUE_READ_TOOLS],\n authorizedScopes: [...scopes],\n },\n secretRefs: [`worker://linear/${encodeURIComponent(accountId)}/token`],\n runtimeHeaders: { Authorization: `Bearer ${credential.token}` },\n });\n }\n return { provider: this.provider, contributions };\n }\n}\n\nfunction issueReadScopes(context: MaterializationContext): Map<string, Set<string>> {\n const result = new Map<string, Set<string>>();\n for (const resource of context.task.authorization.resources) {\n if (\n resource.provider !== \"linear\" ||\n !resource.sources.includes(\"permission-set\") ||\n !resource.actions.includes(\"issues:read\") ||\n !resource.scope.startsWith(\"team:\")\n )\n continue;\n const scopes = result.get(resource.connectorAccountId) ?? new Set<string>();\n scopes.add(resource.scope);\n result.set(resource.connectorAccountId, scopes);\n }\n return result;\n}\n\nfunction assertCovers(allowed: readonly string[], scopes: ReadonlySet<string>): void {\n const missing = [...scopes].filter((scope) => !allowed.includes(scope));\n if (missing.length > 0)\n throw new Error(\n `Linear MCP credential does not natively cover authorized scopes: ${missing.join(\", \")}`,\n );\n}\n\nfunction requiredScopes(value: string | undefined): readonly string[] {\n const scopes =\n value\n ?.split(\",\")\n .map((scope) => scope.trim())\n .filter(Boolean) ?? [];\n if (scopes.length === 0)\n throw new Error(\n \"SUPERTAG_WORKER_LINEAR_ALLOWED_SCOPES is required to fail closed at the native resource boundary\",\n );\n return [...new Set(scopes)];\n}\n\nfunction required(value: string | undefined, name: string): string {\n const normalized = value?.trim();\n if (!normalized) throw new Error(`${name} is required`);\n return normalized;\n}\n\nfunction requireMatch(configured: string | undefined, actual: string): void {\n const expected = configured?.trim();\n if (expected && expected !== actual)\n throw new Error(`Linear credential is configured for ${expected}, not ${actual}`);\n}\n"]}
@@ -0,0 +1,25 @@
1
+ import { ToolProvisioner, MaterializationContext, ToolBundle } from '../worker.js';
2
+ import '../core.js';
3
+ import 'zod';
4
+
5
+ interface SlackMcpCredential {
6
+ readonly token: string;
7
+ /** Native Slack channel scopes this user credential is constrained to read. */
8
+ readonly allowedScopes: readonly string[];
9
+ }
10
+ interface SlackMcpCredentialProvider {
11
+ resolve(connectorAccountId: string): Promise<SlackMcpCredential>;
12
+ }
13
+ declare class EnvironmentSlackMcpCredentialProvider implements SlackMcpCredentialProvider {
14
+ #private;
15
+ constructor(environment?: Readonly<Record<string, string | undefined>>);
16
+ resolve(connectorAccountId: string): Promise<SlackMcpCredential>;
17
+ }
18
+ declare class SlackMcpToolProvisioner implements ToolProvisioner {
19
+ #private;
20
+ readonly provider = "slack";
21
+ constructor(credentials: SlackMcpCredentialProvider);
22
+ provision(context: MaterializationContext): Promise<ToolBundle | undefined>;
23
+ }
24
+
25
+ export { EnvironmentSlackMcpCredentialProvider, type SlackMcpCredential, type SlackMcpCredentialProvider, SlackMcpToolProvisioner };