@tangle-network/agent-app 0.58.15 → 0.58.16

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 (77) hide show
  1. package/dist/VaultPane-RIJM452Y.js +7 -0
  2. package/dist/assistant/index.js +13 -11
  3. package/dist/assistant/index.js.map +1 -1
  4. package/dist/chat-react/index.js +4 -4
  5. package/dist/chat-routes/index.js +4 -4
  6. package/dist/chat-store/index.js +2 -2
  7. package/dist/chunk-B7CL7ENS.js +118 -0
  8. package/dist/chunk-B7CL7ENS.js.map +1 -0
  9. package/dist/{chunk-POE5UUUT.js → chunk-BDCATWBV.js} +3 -3
  10. package/dist/{chunk-NWR5CERQ.js → chunk-FNRUXPXE.js} +2 -2
  11. package/dist/{chunk-57TTYY6T.js → chunk-GEGCSRYQ.js} +2 -2
  12. package/dist/{chunk-WTGSLW5X.js → chunk-HTAFI247.js} +4 -4
  13. package/dist/{chunk-MLG7YSTS.js → chunk-KSLVMA2D.js} +3 -3
  14. package/dist/{chunk-T5U7LDQW.js → chunk-OFQUM5FP.js} +52 -15
  15. package/dist/chunk-OFQUM5FP.js.map +1 -0
  16. package/dist/chunk-PV33JZKV.js +115 -0
  17. package/dist/chunk-PV33JZKV.js.map +1 -0
  18. package/dist/{chunk-TUNRLEDH.js → chunk-Q3BLSWYP.js} +2 -2
  19. package/dist/{chunk-GIBNG64C.js → chunk-S5MKEU2E.js} +2607 -1438
  20. package/dist/chunk-S5MKEU2E.js.map +1 -0
  21. package/dist/{chunk-EN5CP7T7.js → chunk-T5PPQPOD.js} +5 -111
  22. package/dist/chunk-T5PPQPOD.js.map +1 -0
  23. package/dist/{chunk-DWUBICLW.js → chunk-UGPV7VEW.js} +569 -236
  24. package/dist/chunk-UGPV7VEW.js.map +1 -0
  25. package/dist/{chunk-EXBAVMMK.js → chunk-XOBVWCOA.js} +347 -311
  26. package/dist/chunk-XOBVWCOA.js.map +1 -0
  27. package/dist/{mention-editor-W2GG2NZ7.js → mention-editor-4D32JTDS.js} +2 -2
  28. package/dist/preset-cloudflare/index.js +3 -3
  29. package/dist/profile/index.js +4 -2
  30. package/dist/profile/index.js.map +1 -1
  31. package/dist/profile-editor/index.d.ts +185 -0
  32. package/dist/profile-editor/index.js +18 -0
  33. package/dist/profile-editor/index.js.map +1 -0
  34. package/dist/profile-editor/server.d.ts +112 -0
  35. package/dist/profile-editor/server.js +635 -0
  36. package/dist/profile-editor/server.js.map +1 -0
  37. package/dist/public-consultation/index.js +4 -4
  38. package/dist/skills/frontmatter.d.ts +43 -0
  39. package/dist/skills/index.d.ts +1 -38
  40. package/dist/skills/index.js +4 -2
  41. package/dist/skills-placement/index.js +2 -1
  42. package/dist/skills-placement/index.js.map +1 -1
  43. package/dist/stories/fixtures/profile-editor.d.ts +17 -0
  44. package/dist/studio-react/index.js +3 -3
  45. package/dist/teams/invitations-api.js +3 -3
  46. package/dist/vault/VaultPane.d.ts +4 -4
  47. package/dist/vault/VaultTree.d.ts +39 -0
  48. package/dist/vault/contracts.d.ts +17 -7
  49. package/dist/vault/index.d.ts +5 -4
  50. package/dist/vault/index.js +7 -3
  51. package/dist/vault/lazy.js +1 -1
  52. package/dist/web-react/agent-profile-editor.d.ts +63 -1
  53. package/dist/web-react/agent-profile-files.d.ts +38 -0
  54. package/dist/web-react/agent-profile-form-kit.d.ts +87 -0
  55. package/dist/web-react/agent-profile-github-source.d.ts +35 -0
  56. package/dist/web-react/agent-profile-mcp-servers.d.ts +20 -0
  57. package/dist/web-react/agent-profile-suggest-input.d.ts +31 -0
  58. package/dist/web-react/agent-session-controls.d.ts +51 -0
  59. package/dist/web-react/controls.d.ts +29 -3
  60. package/dist/web-react/index.d.ts +3 -2
  61. package/dist/web-react/index.js +23 -15
  62. package/dist/workspace-react/index.js +4 -4
  63. package/package.json +11 -1
  64. package/dist/VaultPane-SPXE7XAC.js +0 -7
  65. package/dist/chunk-DWUBICLW.js.map +0 -1
  66. package/dist/chunk-EN5CP7T7.js.map +0 -1
  67. package/dist/chunk-EXBAVMMK.js.map +0 -1
  68. package/dist/chunk-GIBNG64C.js.map +0 -1
  69. package/dist/chunk-T5U7LDQW.js.map +0 -1
  70. /package/dist/{VaultPane-SPXE7XAC.js.map → VaultPane-RIJM452Y.js.map} +0 -0
  71. /package/dist/{chunk-POE5UUUT.js.map → chunk-BDCATWBV.js.map} +0 -0
  72. /package/dist/{chunk-NWR5CERQ.js.map → chunk-FNRUXPXE.js.map} +0 -0
  73. /package/dist/{chunk-57TTYY6T.js.map → chunk-GEGCSRYQ.js.map} +0 -0
  74. /package/dist/{chunk-WTGSLW5X.js.map → chunk-HTAFI247.js.map} +0 -0
  75. /package/dist/{chunk-MLG7YSTS.js.map → chunk-KSLVMA2D.js.map} +0 -0
  76. /package/dist/{chunk-TUNRLEDH.js.map → chunk-Q3BLSWYP.js.map} +0 -0
  77. /package/dist/{mention-editor-W2GG2NZ7.js.map → mention-editor-4D32JTDS.js.map} +0 -0
@@ -0,0 +1,635 @@
1
+ import {
2
+ PROFILE_EDITOR_ROUTES,
3
+ createProfileEditorClient,
4
+ isCommitSha,
5
+ parseGitHubLocation,
6
+ publicHttpsUrlProblem,
7
+ readSkillFrontmatter
8
+ } from "../chunk-B7CL7ENS.js";
9
+ import "../chunk-PV33JZKV.js";
10
+
11
+ // src/profile-editor/server.ts
12
+ import { z } from "zod";
13
+ var GitHubReadError = class extends Error {
14
+ constructor(status, message, rateLimited = false) {
15
+ super(message);
16
+ this.status = status;
17
+ this.rateLimited = rateLimited;
18
+ this.name = "GitHubReadError";
19
+ }
20
+ status;
21
+ rateLimited;
22
+ };
23
+ function decodeBase64(text) {
24
+ const binary = atob(text.replace(/\s+/g, ""));
25
+ const bytes = new Uint8Array(binary.length);
26
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
27
+ return bytes;
28
+ }
29
+ var githubPayload = {
30
+ repository(value) {
31
+ const body = z.object({ full_name: z.string(), private: z.boolean(), default_branch: z.string(), description: z.string().nullish() }).parse(value);
32
+ return { fullName: body.full_name, private: body.private, defaultBranch: body.default_branch, description: body.description };
33
+ },
34
+ repositories(value) {
35
+ return z.array(z.unknown()).parse(value).map((item) => githubPayload.repository(item));
36
+ },
37
+ branch(value) {
38
+ const body = z.object({ commit: z.object({ sha: z.string(), commit: z.object({
39
+ tree: z.object({ sha: z.string() }),
40
+ message: z.string().optional(),
41
+ committer: z.object({ date: z.string().optional() }).nullish()
42
+ }) }) }).parse(value);
43
+ return {
44
+ sha: body.commit.sha,
45
+ treeSha: body.commit.commit.tree.sha,
46
+ committedAt: body.commit.commit.committer?.date,
47
+ message: body.commit.commit.message
48
+ };
49
+ },
50
+ commit(value) {
51
+ const body = z.object({ sha: z.string(), commit: z.object({
52
+ tree: z.object({ sha: z.string() }),
53
+ message: z.string().optional(),
54
+ committer: z.object({ date: z.string().optional() }).nullish()
55
+ }) }).parse(value);
56
+ return { sha: body.sha, treeSha: body.commit.tree.sha, committedAt: body.commit.committer?.date, message: body.commit.message };
57
+ },
58
+ tree(value) {
59
+ const body = z.object({ truncated: z.boolean().optional(), tree: z.array(z.object({
60
+ path: z.string(),
61
+ type: z.enum(["blob", "tree", "commit"]),
62
+ sha: z.string(),
63
+ size: z.number().optional()
64
+ })) }).parse(value);
65
+ return { entries: body.tree, truncated: body.truncated === true };
66
+ },
67
+ blob(value) {
68
+ const body = z.object({ content: z.string(), encoding: z.string() }).parse(value);
69
+ if (body.encoding === "base64") return decodeBase64(body.content);
70
+ if (body.encoding === "utf-8") return new TextEncoder().encode(body.content);
71
+ throw new GitHubReadError(415, `GitHub returned the file in an unsupported encoding (${body.encoding}).`);
72
+ }
73
+ };
74
+ function createGitHubRestReader(options = {}) {
75
+ const base = (options.baseUrl ?? "https://api.github.com").replace(/\/+$/, "");
76
+ const send = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
77
+ const segment = encodeURIComponent;
78
+ async function get(path, signal) {
79
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? 1e4);
80
+ const response = await send(base + path, {
81
+ redirect: "follow",
82
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
83
+ headers: {
84
+ Accept: "application/vnd.github+json",
85
+ "X-GitHub-Api-Version": "2022-11-28",
86
+ "User-Agent": "tangle-agent-app",
87
+ ...options.token ? { Authorization: `Bearer ${options.token}` } : {}
88
+ }
89
+ });
90
+ if (!response.ok) {
91
+ const rateLimited = response.status === 429 || response.status === 403 && response.headers.get("x-ratelimit-remaining") === "0";
92
+ const detail = await response.json().then((body) => body.message ?? "").catch(() => "");
93
+ throw new GitHubReadError(response.status, detail || `GitHub answered HTTP ${response.status}`, rateLimited);
94
+ }
95
+ return response.json();
96
+ }
97
+ return {
98
+ ...options.token ? { listRepositories: async (signal) => githubPayload.repositories(await get("/user/repos?per_page=100&sort=pushed", signal)) } : {},
99
+ getRepository: async (owner, repo, signal) => githubPayload.repository(await get(`/repos/${segment(owner)}/${segment(repo)}`, signal)),
100
+ getBranchHead: async (owner, repo, branch, signal) => githubPayload.branch(await get(`/repos/${segment(owner)}/${segment(repo)}/branches/${branch.split("/").map(segment).join("/")}`, signal)),
101
+ getCommit: async (owner, repo, sha, signal) => githubPayload.commit(await get(`/repos/${segment(owner)}/${segment(repo)}/commits/${segment(sha)}`, signal)),
102
+ getTree: async (owner, repo, sha, signal) => githubPayload.tree(await get(`/repos/${segment(owner)}/${segment(repo)}/git/trees/${segment(sha)}?recursive=1`, signal)),
103
+ getBlob: async (owner, repo, sha, signal) => githubPayload.blob(await get(`/repos/${segment(owner)}/${segment(repo)}/git/blobs/${segment(sha)}`, signal))
104
+ };
105
+ }
106
+ var fail = (problem, message) => ({ ok: false, problem, message });
107
+ function splitRepository(repository) {
108
+ const [owner, repo, ...rest] = repository.split("/");
109
+ if (!owner || !repo || rest.length || !/^[A-Za-z0-9_.-]{1,100}$/.test(owner) || !/^[A-Za-z0-9_.-]{1,100}$/.test(repo)) return null;
110
+ if (owner === "." || owner === ".." || repo === "." || repo === "..") return null;
111
+ return [owner, repo];
112
+ }
113
+ function normalizedRepositoryPath(path) {
114
+ const trimmed = path.trim().replace(/^\.\/+/, "").replace(/\/+$/, "");
115
+ if (!trimmed || trimmed.length > 400 || trimmed.startsWith("/") || trimmed.includes("\\") || /[\u0000-\u001f\u007f]/.test(trimmed)) return null;
116
+ return trimmed.split("/").every((part) => part && part !== "." && part !== "..") ? trimmed : null;
117
+ }
118
+ function summary(record) {
119
+ return {
120
+ fullName: record.fullName,
121
+ private: record.private,
122
+ defaultBranch: record.defaultBranch,
123
+ ...record.description ? { description: record.description } : {}
124
+ };
125
+ }
126
+ function commitSummary(record, branch) {
127
+ return {
128
+ sha: record.sha,
129
+ ...branch ? { branch } : {},
130
+ ...record.committedAt ? { committedAt: record.committedAt } : {},
131
+ ...record.message ? { message: record.message.split("\n")[0] } : {}
132
+ };
133
+ }
134
+ function readFailure(error, step, repository = "") {
135
+ if (!(error instanceof GitHubReadError)) {
136
+ const timedOut = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
137
+ return fail("unavailable", timedOut ? "GitHub did not answer in time. Try again." : "GitHub could not be reached. Try again.");
138
+ }
139
+ if (error.status === "not-connected") return fail("not-connected", "Connect GitHub to this workspace to use its repositories.");
140
+ if (error.status === "unsupported") {
141
+ return fail("unavailable", step === "list" ? "Repository search is not available for this GitHub connection. Type owner/repo instead." : "This GitHub connection cannot read repository contents.");
142
+ }
143
+ if (error.rateLimited || error.status === 429) return fail("rate-limited", "GitHub is rate limiting this connection. Try again in a minute.");
144
+ if (error.status === 401) return fail("no-access", "GitHub rejected this connection. Reconnect GitHub and try again.");
145
+ if (error.status === 403) {
146
+ return fail("no-access", repository ? `Your GitHub connection is not allowed to read ${repository}. Grant it access, or authorize it for the organization's SSO.` : "GitHub refused this connection. Reconnect GitHub and try again.");
147
+ }
148
+ if (error.status === 404 && step === "repository") {
149
+ return fail("repository-not-found", `No repository named ${repository} is visible to your GitHub connection. Check the name, or give the connection access to it.`);
150
+ }
151
+ if ((error.status === 404 || error.status === 422) && step === "commit") return fail("ref-not-found", `That commit is not in ${repository}.`);
152
+ if (error.status === 409) return fail("ref-not-found", `${repository} has no commits yet.`);
153
+ if (error.status === 404 && step === "file") return fail("path-not-found", "That file is not in the selected commit.");
154
+ return fail("unavailable", `GitHub could not complete the request (HTTP ${error.status}). Try again.`);
155
+ }
156
+ function utf8(bytes) {
157
+ try {
158
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
159
+ } catch {
160
+ return null;
161
+ }
162
+ }
163
+ function createGitHubSourceService(reader, options = {}) {
164
+ const maxFileBytes = options.maxFileBytes ?? 256 * 1024;
165
+ const maxFiles = options.maxFiles ?? 5e3;
166
+ const invalidRepository = fail("repository-not-found", "Enter a repository as owner/repo.");
167
+ async function resolveCommit(owner, repo, sha, signal) {
168
+ if (!isCommitSha(sha)) return fail("ref-not-found", "Enter the full 40-character commit SHA.");
169
+ try {
170
+ return { ok: true, value: await reader.getCommit(owner, repo, sha.toLowerCase(), signal) };
171
+ } catch (error) {
172
+ if (error instanceof GitHubReadError && error.status === 404) {
173
+ try {
174
+ await reader.getRepository(owner, repo, signal);
175
+ } catch (repositoryError) {
176
+ return readFailure(repositoryError, "repository", `${owner}/${repo}`);
177
+ }
178
+ }
179
+ return readFailure(error, "commit", `${owner}/${repo}`);
180
+ }
181
+ }
182
+ async function tree(owner, repo, record, signal) {
183
+ try {
184
+ return { ok: true, value: await reader.getTree(owner, repo, record.treeSha, signal) };
185
+ } catch (error) {
186
+ return readFailure(error, "commit", `${owner}/${repo}`);
187
+ }
188
+ }
189
+ return {
190
+ async repositories(signal) {
191
+ if (!reader.listRepositories) return readFailure(new GitHubReadError("unsupported", "listing unsupported"), "list");
192
+ try {
193
+ const repositories = await reader.listRepositories(signal);
194
+ return { ok: true, value: { repositories: repositories.map(summary) } };
195
+ } catch (error) {
196
+ return readFailure(error, "list");
197
+ }
198
+ },
199
+ async latest(repository, signal) {
200
+ const parts = splitRepository(repository);
201
+ if (!parts) return invalidRepository;
202
+ let record;
203
+ try {
204
+ record = await reader.getRepository(parts[0], parts[1], signal);
205
+ } catch (error) {
206
+ return readFailure(error, "repository", repository);
207
+ }
208
+ try {
209
+ const head = await reader.getBranchHead(parts[0], parts[1], record.defaultBranch, signal);
210
+ return { ok: true, value: { repository: summary(record), commit: commitSummary(head, record.defaultBranch) } };
211
+ } catch (error) {
212
+ return readFailure(error, "commit", repository);
213
+ }
214
+ },
215
+ async commit(repository, sha, signal) {
216
+ const parts = splitRepository(repository);
217
+ if (!parts) return invalidRepository;
218
+ const resolved = await resolveCommit(parts[0], parts[1], sha, signal);
219
+ return resolved.ok ? { ok: true, value: commitSummary(resolved.value) } : resolved;
220
+ },
221
+ async files(repository, commit, signal) {
222
+ const parts = splitRepository(repository);
223
+ if (!parts) return invalidRepository;
224
+ const resolved = await resolveCommit(parts[0], parts[1], commit, signal);
225
+ if (!resolved.ok) return resolved;
226
+ const listing2 = await tree(parts[0], parts[1], resolved.value, signal);
227
+ if (!listing2.ok) return listing2;
228
+ const blobs = listing2.value.entries.filter((entry) => entry.type === "blob");
229
+ return { ok: true, value: {
230
+ commit: commitSummary(resolved.value),
231
+ files: blobs.slice(0, maxFiles).map((entry) => ({ path: entry.path, ...entry.size === void 0 ? {} : { size: entry.size } })),
232
+ truncated: listing2.value.truncated || blobs.length > maxFiles
233
+ } };
234
+ },
235
+ async check(request, signal) {
236
+ const parts = splitRepository(request.repository);
237
+ if (!parts) return invalidRepository;
238
+ const path = normalizedRepositoryPath(request.path);
239
+ if (!path) return fail("path-not-found", "Enter a path inside the repository, such as skills/research/SKILL.md.");
240
+ const resolved = await resolveCommit(parts[0], parts[1], request.commit, signal);
241
+ if (!resolved.ok) return resolved;
242
+ const listing2 = await tree(parts[0], parts[1], resolved.value, signal);
243
+ if (!listing2.ok) return listing2;
244
+ const entries = new Map(listing2.value.entries.map((entry2) => [entry2.path, entry2]));
245
+ let entry = entries.get(path);
246
+ let checkedPath = path;
247
+ if (entry?.type === "tree") {
248
+ const skillFile = request.purpose === "skill" ? entries.get(`${path}/SKILL.md`) : void 0;
249
+ if (!skillFile) {
250
+ return fail("not-a-file", request.purpose === "skill" ? `${path} is a folder without a SKILL.md file. Choose the skill's SKILL.md.` : `${path} is a folder. Choose a file inside it.`);
251
+ }
252
+ entry = skillFile;
253
+ checkedPath = `${path}/SKILL.md`;
254
+ }
255
+ if (!entry || entry.type !== "blob") {
256
+ return fail("path-not-found", listing2.value.truncated ? `${path} was not found. This repository is too large to list completely; check the path.` : `${path} is not in ${request.repository} at this commit.`);
257
+ }
258
+ if (entry.size !== void 0 && entry.size > maxFileBytes) {
259
+ return fail("unsupported-file", `${checkedPath} is ${formatBytes(entry.size)}. Files can be up to ${formatBytes(maxFileBytes)}.`);
260
+ }
261
+ let bytes;
262
+ try {
263
+ bytes = await reader.getBlob(parts[0], parts[1], entry.sha, signal);
264
+ } catch (error) {
265
+ return readFailure(error, "file", request.repository);
266
+ }
267
+ if (bytes.byteLength > maxFileBytes) {
268
+ return fail("unsupported-file", `${checkedPath} is ${formatBytes(bytes.byteLength)}. Files can be up to ${formatBytes(maxFileBytes)}.`);
269
+ }
270
+ const content = utf8(bytes);
271
+ if (content === null) return fail("unsupported-file", `${checkedPath} is not a text file.`);
272
+ const check = {
273
+ repository: request.repository,
274
+ path: checkedPath,
275
+ commit: commitSummary(resolved.value),
276
+ size: bytes.byteLength,
277
+ content
278
+ };
279
+ if (request.purpose === "skill") {
280
+ const skill = readSkillFrontmatter(content);
281
+ if (!skill.ok) return fail("not-a-skill", skill.message);
282
+ check.skill = { name: skill.name, description: skill.description };
283
+ }
284
+ return { ok: true, value: check };
285
+ }
286
+ };
287
+ }
288
+ function formatBytes(bytes) {
289
+ if (bytes < 1024) return `${bytes} B`;
290
+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
291
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
292
+ }
293
+ var MCP_PROTOCOL_VERSION = "2025-06-18";
294
+ var MAX_MCP_BODY_BYTES = 2 * 1024 * 1024;
295
+ var McpCheckFailure = class extends Error {
296
+ constructor(problem, message, status) {
297
+ super(message);
298
+ this.problem = problem;
299
+ this.status = status;
300
+ }
301
+ problem;
302
+ status;
303
+ };
304
+ function publicHeaders(server) {
305
+ if (!("headers" in server) || !server.headers) return {};
306
+ const headers = {};
307
+ for (const [name, value] of Object.entries(server.headers)) {
308
+ if (value && typeof value === "object" && value.kind === "public" && typeof value.value === "string") headers[name] = value.value;
309
+ }
310
+ return headers;
311
+ }
312
+ async function* sseEvents(body) {
313
+ const reader = body.getReader();
314
+ const decoder = new TextDecoder();
315
+ let buffer = "";
316
+ let total = 0;
317
+ try {
318
+ for (; ; ) {
319
+ const chunk = await reader.read();
320
+ if (chunk.done) break;
321
+ total += chunk.value.byteLength;
322
+ if (total > MAX_MCP_BODY_BYTES) throw new McpCheckFailure("protocol-error", "The server sent more data than a tool listing needs.");
323
+ buffer += decoder.decode(chunk.value, { stream: true }).replace(/\r\n/g, "\n");
324
+ let boundary = buffer.indexOf("\n\n");
325
+ while (boundary >= 0) {
326
+ const block = buffer.slice(0, boundary);
327
+ buffer = buffer.slice(boundary + 2);
328
+ let event = "message";
329
+ const data = [];
330
+ for (const line of block.split("\n")) {
331
+ if (line.startsWith("event:")) event = line.slice(6).trim();
332
+ else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
333
+ }
334
+ if (data.length) yield { event, data: data.join("\n") };
335
+ boundary = buffer.indexOf("\n\n");
336
+ }
337
+ }
338
+ } finally {
339
+ await reader.cancel().catch(() => void 0);
340
+ }
341
+ }
342
+ async function readJson(response) {
343
+ const text = await response.text();
344
+ if (text.length > MAX_MCP_BODY_BYTES) throw new McpCheckFailure("protocol-error", "The server sent more data than a tool listing needs.");
345
+ try {
346
+ return JSON.parse(text);
347
+ } catch {
348
+ throw new McpCheckFailure("protocol-error", "The server did not answer with MCP JSON-RPC.");
349
+ }
350
+ }
351
+ function rpcResult(message, id) {
352
+ const items = Array.isArray(message) ? message : [message];
353
+ const match = items.find((item) => !!item && typeof item === "object" && item.id === id);
354
+ if (!match) throw new McpCheckFailure("protocol-error", "The server did not answer the MCP request.");
355
+ if (match.error) throw new McpCheckFailure("protocol-error", `The server returned an MCP error: ${match.error.message ?? match.error.code ?? "unknown"}.`);
356
+ return match.result;
357
+ }
358
+ function statusFailure(status) {
359
+ if (status === 401 || status === 403) {
360
+ return new McpCheckFailure("auth-required", "The server needs credentials. Add them as secret references in Advanced JSON.", status);
361
+ }
362
+ if (status === 404 || status === 405) return new McpCheckFailure("protocol-error", `No MCP endpoint answered at this URL (HTTP ${status}).`, status);
363
+ return new McpCheckFailure("unreachable", `The server answered HTTP ${status}.`, status);
364
+ }
365
+ var toolsSchema = z.object({
366
+ tools: z.array(z.object({ name: z.string(), description: z.string().optional() }).passthrough()),
367
+ nextCursor: z.string().optional()
368
+ });
369
+ var initializeSchema = z.object({ serverInfo: z.object({ name: z.string().optional(), version: z.string().optional() }).passthrough().optional() }).passthrough();
370
+ async function checkMcpServer(server, options = {}) {
371
+ const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
372
+ const started = Date.now();
373
+ const failed = (failure) => ({
374
+ ok: false,
375
+ problem: failure.problem,
376
+ message: failure.message,
377
+ ...failure.status === void 0 ? {} : { status: failure.status },
378
+ checkedAt
379
+ });
380
+ if (server.enabled === false) return failed(new McpCheckFailure("not-checkable", "Enable the server to check it."));
381
+ if ("command" in server && server.command) {
382
+ return failed(new McpCheckFailure("not-checkable", "Local servers start inside the agent workspace, so they are checked when the agent runs."));
383
+ }
384
+ const url = "url" in server ? server.url : void 0;
385
+ if (!url) return failed(new McpCheckFailure("invalid-url", "Add the server URL."));
386
+ const urlProblem = (options.urlProblem ?? publicHttpsUrlProblem)(url);
387
+ if (urlProblem) {
388
+ let parsed = true;
389
+ try {
390
+ new URL(url);
391
+ } catch {
392
+ parsed = false;
393
+ }
394
+ return failed(new McpCheckFailure(parsed ? "blocked-url" : "invalid-url", urlProblem));
395
+ }
396
+ const send = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
397
+ const controller = new AbortController();
398
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 8e3);
399
+ const clientInfo = options.clientInfo ?? { name: "tangle-agent-app", version: "1" };
400
+ const headers = publicHeaders(server);
401
+ const initialize = {
402
+ jsonrpc: "2.0",
403
+ id: 1,
404
+ method: "initialize",
405
+ params: { protocolVersion: MCP_PROTOCOL_VERSION, capabilities: {}, clientInfo }
406
+ };
407
+ const initialized = { jsonrpc: "2.0", method: "notifications/initialized" };
408
+ try {
409
+ const result = "transport" in server && server.transport === "sse" ? await checkSse(url, headers, send, controller.signal, initialize, initialized) : await checkStreamableHttp(url, headers, send, controller.signal, initialize, initialized);
410
+ return { ok: true, ...result, latencyMs: Date.now() - started, checkedAt };
411
+ } catch (error) {
412
+ if (error instanceof McpCheckFailure) return failed(error);
413
+ if (controller.signal.aborted) return failed(new McpCheckFailure("timeout", "The server did not answer within 8 seconds."));
414
+ return failed(new McpCheckFailure("unreachable", "Could not connect to the server. Check the URL and that the server is running."));
415
+ } finally {
416
+ clearTimeout(timer);
417
+ }
418
+ }
419
+ function listing(info, pages) {
420
+ const parsedInfo = initializeSchema.safeParse(info);
421
+ const tools = pages.flatMap((page) => {
422
+ const parsed = toolsSchema.safeParse(page);
423
+ if (!parsed.success) throw new McpCheckFailure("protocol-error", "The server returned a tool list MCP clients cannot read.");
424
+ return parsed.data.tools.map((tool) => ({ name: tool.name, ...tool.description ? { description: tool.description } : {} }));
425
+ });
426
+ const serverInfo = parsedInfo.success ? parsedInfo.data.serverInfo : void 0;
427
+ return { tools, ...serverInfo?.name ? { serverName: serverInfo.name } : {}, ...serverInfo?.version ? { serverVersion: serverInfo.version } : {} };
428
+ }
429
+ async function checkStreamableHttp(url, headers, send, signal, initialize, initialized) {
430
+ let session = null;
431
+ let protocol = null;
432
+ async function post(message, id) {
433
+ const response = await send(url, { method: "POST", signal, redirect: "error", body: JSON.stringify(message), headers: {
434
+ ...headers,
435
+ "Content-Type": "application/json",
436
+ Accept: "application/json, text/event-stream",
437
+ ...session ? { "Mcp-Session-Id": session } : {},
438
+ ...protocol ? { "MCP-Protocol-Version": protocol } : {}
439
+ } });
440
+ if (id === void 0) {
441
+ await response.body?.cancel();
442
+ if (!response.ok && response.status !== 202) throw statusFailure(response.status);
443
+ return void 0;
444
+ }
445
+ if (!response.ok) {
446
+ await response.body?.cancel();
447
+ throw statusFailure(response.status);
448
+ }
449
+ session = response.headers.get("mcp-session-id") ?? session;
450
+ const type = response.headers.get("content-type") ?? "";
451
+ if (type.includes("text/event-stream")) {
452
+ if (!response.body) throw new McpCheckFailure("protocol-error", "The server opened an empty event stream.");
453
+ for await (const event of sseEvents(response.body)) {
454
+ if (event.event !== "message") continue;
455
+ let parsed;
456
+ try {
457
+ parsed = JSON.parse(event.data);
458
+ } catch {
459
+ continue;
460
+ }
461
+ const items = Array.isArray(parsed) ? parsed : [parsed];
462
+ if (items.some((item) => item && typeof item === "object" && item.id === id)) return rpcResult(parsed, id);
463
+ }
464
+ throw new McpCheckFailure("protocol-error", "The server closed the stream before answering.");
465
+ }
466
+ if (!type.includes("json")) {
467
+ await response.body?.cancel();
468
+ throw new McpCheckFailure("protocol-error", "The server did not answer with MCP JSON-RPC.");
469
+ }
470
+ return rpcResult(await readJson(response), id);
471
+ }
472
+ const info = await post(initialize, 1);
473
+ const negotiated = initializeSchema.safeParse(info);
474
+ protocol = negotiated.success && typeof negotiated.data.protocolVersion === "string" ? negotiated.data.protocolVersion : MCP_PROTOCOL_VERSION;
475
+ await post(initialized);
476
+ const pages = [];
477
+ let cursor;
478
+ for (let page = 0; page < 5; page++) {
479
+ const result = await post({ jsonrpc: "2.0", id: 2 + page, method: "tools/list", params: cursor ? { cursor } : {} }, 2 + page);
480
+ pages.push(result);
481
+ const next = toolsSchema.safeParse(result);
482
+ cursor = next.success ? next.data.nextCursor : void 0;
483
+ if (!cursor) break;
484
+ }
485
+ if (session) {
486
+ await send(url, { method: "DELETE", signal, headers: { ...headers, "Mcp-Session-Id": session } }).then((response) => response.body?.cancel()).catch(() => void 0);
487
+ }
488
+ return listing(info, pages);
489
+ }
490
+ async function checkSse(url, headers, send, signal, initialize, initialized) {
491
+ const stream = await send(url, { method: "GET", signal, redirect: "error", headers: { ...headers, Accept: "text/event-stream" } });
492
+ if (!stream.ok) {
493
+ await stream.body?.cancel();
494
+ throw statusFailure(stream.status);
495
+ }
496
+ if (!stream.body || !(stream.headers.get("content-type") ?? "").includes("text/event-stream")) {
497
+ await stream.body?.cancel();
498
+ throw new McpCheckFailure("protocol-error", "The server did not open an MCP event stream.");
499
+ }
500
+ const events = sseEvents(stream.body);
501
+ try {
502
+ const first = await events.next();
503
+ if (first.done || first.value.event !== "endpoint") throw new McpCheckFailure("protocol-error", "The server did not announce an MCP message endpoint.");
504
+ const endpoint = new URL(first.value.data.trim(), url);
505
+ if (endpoint.origin !== new URL(url).origin) {
506
+ throw new McpCheckFailure("protocol-error", "The server announced a message endpoint on another address.");
507
+ }
508
+ async function post(message) {
509
+ const response = await send(endpoint.href, {
510
+ method: "POST",
511
+ signal,
512
+ redirect: "error",
513
+ body: JSON.stringify(message),
514
+ headers: { ...headers, "Content-Type": "application/json" }
515
+ });
516
+ await response.body?.cancel();
517
+ if (!response.ok) throw statusFailure(response.status);
518
+ }
519
+ async function answer(id) {
520
+ for (; ; ) {
521
+ const next = await events.next();
522
+ if (next.done) throw new McpCheckFailure("protocol-error", "The server closed the stream before answering.");
523
+ if (next.value.event !== "message") continue;
524
+ let parsed;
525
+ try {
526
+ parsed = JSON.parse(next.value.data);
527
+ } catch {
528
+ continue;
529
+ }
530
+ if (parsed && typeof parsed === "object" && parsed.id === id) return rpcResult(parsed, id);
531
+ }
532
+ }
533
+ await post(initialize);
534
+ const info = await answer(1);
535
+ await post(initialized);
536
+ await post({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} });
537
+ return listing(info, [await answer(2)]);
538
+ } finally {
539
+ await events.return(void 0);
540
+ }
541
+ }
542
+ function createMcpHealthChecker(options = {}) {
543
+ return { check: (server, signal) => {
544
+ if (signal?.aborted) return Promise.resolve({ ok: false, problem: "unavailable", message: "The check was cancelled.", checkedAt: (/* @__PURE__ */ new Date()).toISOString() });
545
+ return checkMcpServer(server, options);
546
+ } };
547
+ }
548
+ var repositoryParam = z.string().trim().min(3).max(201);
549
+ var shaParam = z.string().trim().regex(/^[0-9a-f]{40}$/i);
550
+ var checkBody = z.object({
551
+ repository: repositoryParam,
552
+ path: z.string().min(1).max(400),
553
+ commit: shaParam,
554
+ purpose: z.enum(["skill", "file"])
555
+ }).strict();
556
+ var mcpBody = z.object({ server: z.object({
557
+ enabled: z.boolean().optional(),
558
+ transport: z.enum(["http", "sse", "stdio"]).optional(),
559
+ url: z.string().max(2048).optional(),
560
+ command: z.string().max(2048).optional(),
561
+ headers: z.record(z.string(), z.unknown()).optional()
562
+ }).passthrough() }).strict();
563
+ function json(body, status = 200) {
564
+ return Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
565
+ }
566
+ var MAX_BODY_BYTES = 64 * 1024;
567
+ async function readBody(request) {
568
+ const text = await request.text();
569
+ if (text.length > MAX_BODY_BYTES) throw new Error("Request body is too large");
570
+ return JSON.parse(text);
571
+ }
572
+ async function handleProfileEditorRequest(request, path, options) {
573
+ const route = path.replace(/^\/+|\/+$/g, "");
574
+ const query = new URL(request.url).searchParams;
575
+ const githubRoute = Object.entries(PROFILE_EDITOR_ROUTES).find(([, value]) => value === route)?.[0];
576
+ if (!githubRoute) return json({ error: "Not found" }, 404);
577
+ const expectsPost = githubRoute === "check" || githubRoute === "mcpCheck";
578
+ if (request.method !== (expectsPost ? "POST" : "GET")) return json({ error: "Method not allowed" }, 405);
579
+ const signal = request.signal;
580
+ if (githubRoute === "mcpCheck") {
581
+ if (!options.mcp) return json({ ok: false, problem: "unavailable", message: "This product does not check MCP servers.", checkedAt: (/* @__PURE__ */ new Date()).toISOString() });
582
+ let body;
583
+ try {
584
+ body = mcpBody.parse(await readBody(request));
585
+ } catch {
586
+ return json({ error: "Send { server } with the MCP server to check." }, 400);
587
+ }
588
+ return json(await options.mcp.check(body.server, signal));
589
+ }
590
+ if (!options.github) return json(fail("unavailable", "This product does not offer GitHub sources."));
591
+ const github = options.github;
592
+ switch (githubRoute) {
593
+ case "repositories":
594
+ return json(await github.repositories(signal));
595
+ case "latest": {
596
+ const repository = repositoryParam.safeParse(query.get("repository"));
597
+ if (!repository.success) return json({ error: "repository is required" }, 400);
598
+ return json(await github.latest(repository.data, signal));
599
+ }
600
+ case "commit":
601
+ case "files": {
602
+ const repository = repositoryParam.safeParse(query.get("repository"));
603
+ const sha = shaParam.safeParse(query.get(githubRoute === "commit" ? "sha" : "commit"));
604
+ if (!repository.success) return json({ error: "repository is required" }, 400);
605
+ if (!sha.success) return json(fail("ref-not-found", "Enter the full 40-character commit SHA."));
606
+ return json(githubRoute === "commit" ? await github.commit(repository.data, sha.data, signal) : await github.files(repository.data, sha.data, signal));
607
+ }
608
+ case "check": {
609
+ let body;
610
+ try {
611
+ body = checkBody.parse(await readBody(request));
612
+ } catch {
613
+ return json({ error: "Send repository, path, a 40-character commit, and purpose." }, 400);
614
+ }
615
+ return json(await github.check(body, signal));
616
+ }
617
+ }
618
+ }
619
+ export {
620
+ GitHubReadError,
621
+ PROFILE_EDITOR_ROUTES,
622
+ checkMcpServer,
623
+ createGitHubRestReader,
624
+ createGitHubSourceService,
625
+ createMcpHealthChecker,
626
+ createProfileEditorClient,
627
+ formatBytes,
628
+ githubPayload,
629
+ handleProfileEditorRequest,
630
+ isCommitSha,
631
+ parseGitHubLocation,
632
+ publicHttpsUrlProblem,
633
+ readSkillFrontmatter
634
+ };
635
+ //# sourceMappingURL=server.js.map