@calypsohq/elephant-mcp-server 0.0.0-stage → 1.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 (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +93 -2
  3. package/dist/ElephantMcpServer.js +73 -0
  4. package/dist/auth/ApiKeyStrategy.js +21 -0
  5. package/dist/auth/AuthChallenge.js +53 -0
  6. package/dist/auth/AuthStrategy.js +1 -0
  7. package/dist/auth/BearerAuthenticator.js +30 -0
  8. package/dist/auth/Credential.js +1 -0
  9. package/dist/auth/JwtGrantStrategy.js +58 -0
  10. package/dist/auth/TokenCipher.js +48 -0
  11. package/dist/calypso/AgentCatalog.js +29 -0
  12. package/dist/calypso/AgentCatalogLoader.js +117 -0
  13. package/dist/calypso/AgentResponses.js +94 -0
  14. package/dist/calypso/BatchManifest.js +105 -0
  15. package/dist/calypso/BucketDestination.js +26 -0
  16. package/dist/calypso/CalypsoApi.js +32 -0
  17. package/dist/calypso/CalypsoApiClient.js +44 -0
  18. package/dist/calypso/CalypsoApiConfig.js +9 -0
  19. package/dist/calypso/KnowledgeBatches.js +122 -0
  20. package/dist/calypso/KnowledgeBuckets.js +30 -0
  21. package/dist/calypso/KnowledgeFiles.js +147 -0
  22. package/dist/calypso/KnowledgeInventory.js +68 -0
  23. package/dist/calypso/KnowledgeSearch.js +34 -0
  24. package/dist/calypso/KnowledgeWebsites.js +49 -0
  25. package/dist/calypso/UploadContent.js +33 -0
  26. package/dist/calypso/apiErrors.js +59 -0
  27. package/dist/calypso/bucketList.js +77 -0
  28. package/dist/calypso/coerce.js +31 -0
  29. package/dist/calypso/knowledgeTypes.js +8 -0
  30. package/dist/calypso/polling.js +26 -0
  31. package/dist/calypso/uploadBytes.js +23 -0
  32. package/dist/hatching/HatchingCopy.js +76 -0
  33. package/dist/http/HostedServer.js +50 -0
  34. package/dist/http/HttpConfig.js +72 -0
  35. package/dist/http/HttpServer.js +126 -0
  36. package/dist/http/KnowledgeInventoryCache.js +47 -0
  37. package/dist/http/McpEndpoint.js +83 -0
  38. package/dist/http/ModelCatalogCache.js +45 -0
  39. package/dist/http/ProtectedResourceMetadata.js +40 -0
  40. package/dist/http/RateLimiter.js +56 -0
  41. package/dist/index.js +27 -0
  42. package/dist/presets/ToolPreset.js +40 -0
  43. package/dist/presets/ToolPresetRegistry.js +56 -0
  44. package/dist/stdio/LocalPresets.js +37 -0
  45. package/dist/stdio/StdioOptions.js +61 -0
  46. package/dist/stdio.js +56 -0
  47. package/dist/tools/AddFileTool.js +104 -0
  48. package/dist/tools/AddFilesTool.js +81 -0
  49. package/dist/tools/AddWebsiteTool.js +56 -0
  50. package/dist/tools/AskTool.js +69 -0
  51. package/dist/tools/CreateBucketTool.js +61 -0
  52. package/dist/tools/ElephantTool.js +41 -0
  53. package/dist/tools/ListBucketsTool.js +35 -0
  54. package/dist/tools/OpenSourceTool.js +32 -0
  55. package/dist/tools/SearchTool.js +60 -0
  56. package/dist/tools/ToolContext.js +1 -0
  57. package/dist/tools/ToolLogger.js +29 -0
  58. package/dist/tools/schemaParts.js +46 -0
  59. package/package.json +61 -4
@@ -0,0 +1,105 @@
1
+ import { createHash } from "node:crypto";
2
+ import { bucketFields, hasBucketDestination, } from "./BucketDestination.js";
3
+ import { compactStrings } from "./coerce.js";
4
+ export const BATCH_MAX_FILES = 100;
5
+ const CLIENT_FILE_ID_MAX_LENGTH = 128;
6
+ /**
7
+ * Describes a batch to Calypso before any bytes move.
8
+ *
9
+ * Everything that can be refused without a network call is refused here, so a
10
+ * batch of a hundred files does not fail on item ninety after uploading the
11
+ * rest.
12
+ */
13
+ export function buildKnowledgeBatchManifest(params) {
14
+ if (!Array.isArray(params.items) || params.items.length === 0) {
15
+ throw new Error("Batch upload requires at least one item.");
16
+ }
17
+ if (params.items.length > BATCH_MAX_FILES) {
18
+ throw new Error(`Batch upload supports at most ${BATCH_MAX_FILES} files.`);
19
+ }
20
+ const batchIdempotencyKey = String(params.batchIdempotencyKey || "").trim();
21
+ if (!batchIdempotencyKey) {
22
+ throw new Error("batchIdempotencyKey is required for batch uploads.");
23
+ }
24
+ requireDestinations(params);
25
+ const seen = new Set();
26
+ const clientFileIds = params.items.map((item, index) => clientFileIdFor(item, index, seen));
27
+ return {
28
+ clientFileIds,
29
+ manifest: {
30
+ version: 1,
31
+ batch_idempotency_key: batchIdempotencyKey,
32
+ ...bucketFields(params),
33
+ items: params.items.map((item, index) => manifestItem(item, clientFileIds[index])),
34
+ },
35
+ };
36
+ }
37
+ /** A shared destination covers every item; otherwise each needs its own. */
38
+ function requireDestinations(params) {
39
+ if (hasBucketDestination(params))
40
+ return;
41
+ const missing = params.items
42
+ .map((item, index) => ({ item, index }))
43
+ .filter(({ item }) => !hasBucketDestination(item))
44
+ .map(({ item, index }) => item.clientFileId || item.filename || `item ${index + 1}`);
45
+ if (missing.length > 0) {
46
+ throw new Error(`Batch knowledge uploads require a shared bucket destination or a bucket destination on every item. Missing: ${missing.join(", ")}`);
47
+ }
48
+ }
49
+ function manifestItem(item, clientFileId) {
50
+ const tags = compactStrings(item.tags);
51
+ return {
52
+ client_file_id: clientFileId,
53
+ filename: item.filename,
54
+ ...(item.title?.trim() ? { title: item.title.trim() } : {}),
55
+ ...(tags ? { tags } : {}),
56
+ ...(item.metadata && Object.keys(item.metadata).length > 0
57
+ ? { metadata: item.metadata }
58
+ : {}),
59
+ ...bucketFields(item),
60
+ };
61
+ }
62
+ /**
63
+ * The caller's id when given (validated), otherwise one derived from the file
64
+ * name and position, so retrying the same batch yields the same ids and the
65
+ * API can recognize the replay.
66
+ */
67
+ function clientFileIdFor(item, index, seen) {
68
+ const explicit = String(item.clientFileId || "").trim();
69
+ const id = explicit
70
+ ? validatedClientFileId(explicit, seen)
71
+ : derivedClientFileId(item, index, seen);
72
+ seen.add(id);
73
+ return id;
74
+ }
75
+ function validatedClientFileId(explicit, seen) {
76
+ if (explicit.length > CLIENT_FILE_ID_MAX_LENGTH ||
77
+ explicit.startsWith("__") ||
78
+ !/^[A-Za-z0-9_.-]+$/.test(explicit)) {
79
+ throw new Error("clientFileId must be Firestore-safe.");
80
+ }
81
+ if (seen.has(explicit)) {
82
+ throw new Error("clientFileId values must be unique.");
83
+ }
84
+ return explicit;
85
+ }
86
+ function derivedClientFileId(item, index, seen) {
87
+ const digest = createHash("sha256")
88
+ .update(`${index}:${item.filename}:`)
89
+ .digest("hex")
90
+ .slice(0, 16);
91
+ let candidate = `${safeIdStem(item.filename || "file")}_${digest}`.slice(0, CLIENT_FILE_ID_MAX_LENGTH);
92
+ for (let suffix = 2; seen.has(candidate); suffix += 1) {
93
+ const suffixText = `_${suffix}`;
94
+ candidate = `${candidate.slice(0, CLIENT_FILE_ID_MAX_LENGTH - suffixText.length)}${suffixText}`;
95
+ }
96
+ return candidate;
97
+ }
98
+ function safeIdStem(value) {
99
+ const sanitized = value
100
+ .trim()
101
+ .replace(/[^A-Za-z0-9_.-]+/g, "_")
102
+ .replace(/^_+/, "")
103
+ .slice(0, 80);
104
+ return sanitized || "file";
105
+ }
@@ -0,0 +1,26 @@
1
+ import { compactStrings } from "./coerce.js";
2
+ export function hasBucketDestination(source) {
3
+ return Boolean(compactStrings(source.bucketIds) ||
4
+ compactStrings(source.bucketSlugs) ||
5
+ String(source.bucket || "").trim());
6
+ }
7
+ /** How many destinations were named; a count is safe to log, names are not. */
8
+ export function countBucketTargets(source) {
9
+ return ((source.bucketIds?.length || 0) +
10
+ (source.bucketSlugs?.length || 0) +
11
+ (source.bucket ? 1 : 0));
12
+ }
13
+ /** The destination as the snake_case fields the upload endpoints take. */
14
+ export function bucketFields(source) {
15
+ const bucketIds = compactStrings(source.bucketIds);
16
+ const bucketSlugs = compactStrings(source.bucketSlugs);
17
+ const bucket = String(source.bucket || "").trim();
18
+ return {
19
+ ...(bucketIds ? { bucket_ids: bucketIds } : {}),
20
+ ...(bucketSlugs ? { bucket_slugs: bucketSlugs } : {}),
21
+ ...(bucket ? { bucket } : {}),
22
+ ...(typeof source.createMissingBuckets === "boolean"
23
+ ? { create_missing_buckets: source.createMissingBuckets }
24
+ : {}),
25
+ };
26
+ }
@@ -0,0 +1,32 @@
1
+ import { AgentResponses } from "./AgentResponses.js";
2
+ import { CalypsoApiClient } from "./CalypsoApiClient.js";
3
+ import { KnowledgeBatches } from "./KnowledgeBatches.js";
4
+ import { KnowledgeBuckets } from "./KnowledgeBuckets.js";
5
+ import { KnowledgeFiles } from "./KnowledgeFiles.js";
6
+ import { KnowledgeSearch } from "./KnowledgeSearch.js";
7
+ import { KnowledgeWebsites } from "./KnowledgeWebsites.js";
8
+ /**
9
+ * The Calypso API as one caller sees it, grouped by resource.
10
+ *
11
+ * Tools take this instead of a key and a base URL so that none of them can
12
+ * build a request by hand: everything a tool does to Calypso is a named
13
+ * operation on one of these resources.
14
+ */
15
+ export class CalypsoApi {
16
+ agent;
17
+ batches;
18
+ buckets;
19
+ files;
20
+ search;
21
+ websites;
22
+ /** `userAgent` identifies this server on agent calls. */
23
+ constructor(config, userAgent) {
24
+ const client = new CalypsoApiClient(config);
25
+ this.agent = new AgentResponses(config, userAgent);
26
+ this.batches = new KnowledgeBatches(client);
27
+ this.buckets = new KnowledgeBuckets(client);
28
+ this.files = new KnowledgeFiles(client);
29
+ this.search = new KnowledgeSearch(client);
30
+ this.websites = new KnowledgeWebsites(client);
31
+ }
32
+ }
@@ -0,0 +1,44 @@
1
+ import { formatApiError, readResponseBody } from "./apiErrors.js";
2
+ import { requireApiKey } from "./CalypsoApiConfig.js";
3
+ /**
4
+ * Authenticated JSON transport to the Calypso API for one caller.
5
+ *
6
+ * Every Calypso call goes through `request`, so the bearer header, the URL
7
+ * rule and the error wording exist once instead of once per resource.
8
+ */
9
+ export class CalypsoApiClient {
10
+ config;
11
+ constructor(config) {
12
+ this.config = config;
13
+ }
14
+ /** Absolute URL for a path under the API base, e.g. `/knowledge/buckets`. */
15
+ url(relativePath) {
16
+ const path = relativePath.replace(/^\//, "");
17
+ return new URL(path, `${this.config.apiBaseUrl}/`).toString();
18
+ }
19
+ /** Performs the call and returns the parsed body; throws on a non-2xx. */
20
+ async request(relativePath, request) {
21
+ const response = await fetch(this.url(relativePath), {
22
+ method: request.method,
23
+ headers: this.headersFor(request),
24
+ ...(request.body === undefined
25
+ ? {}
26
+ : { body: JSON.stringify(request.body) }),
27
+ ...(request.signal ? { signal: request.signal } : {}),
28
+ });
29
+ const body = await readResponseBody(response);
30
+ if (!response.ok) {
31
+ throw new Error(formatApiError(response.status, body));
32
+ }
33
+ return body;
34
+ }
35
+ headersFor(request) {
36
+ return {
37
+ Authorization: `Bearer ${requireApiKey(this.config)}`,
38
+ ...(request.body === undefined
39
+ ? {}
40
+ : { "Content-Type": "application/json" }),
41
+ ...request.headers,
42
+ };
43
+ }
44
+ }
@@ -0,0 +1,9 @@
1
+ export const DEFAULT_CALYPSO_API_BASE_URL = "https://api.calypso.so/v1";
2
+ /** The caller's key, or a clear failure when a request carried none. */
3
+ export function requireApiKey(config) {
4
+ const apiKey = String(config.apiKey || "").trim();
5
+ if (!apiKey) {
6
+ throw new Error("A Calypso API key is required to call Calypso, but the request carried none.");
7
+ }
8
+ return apiKey;
9
+ }
@@ -0,0 +1,122 @@
1
+ import { buildKnowledgeBatchManifest, } from "./BatchManifest.js";
2
+ import { pollUntilSettled } from "./polling.js";
3
+ import { DEFAULT_MIME_TYPE, decodeUploadContent, } from "./UploadContent.js";
4
+ import { putUploadBytes } from "./uploadBytes.js";
5
+ const TERMINAL_STATUSES = [
6
+ "active",
7
+ "partially_active",
8
+ "partially_failed",
9
+ "failed",
10
+ ];
11
+ /**
12
+ * Several files added to the team's Calypso knowledge in one request.
13
+ *
14
+ * A batch is its own resource with its own status, so a caller can add a
15
+ * hundred files and follow one id instead of a hundred.
16
+ */
17
+ export class KnowledgeBatches {
18
+ api;
19
+ constructor(api) {
20
+ this.api = api;
21
+ }
22
+ async upload(params) {
23
+ const { manifest, clientFileIds } = buildKnowledgeBatchManifest(params);
24
+ // Decode everything first: a bad item must fail the call before any
25
+ // session exists, not leave a half-uploaded batch behind.
26
+ const contents = params.items.map(decodeUploadContent);
27
+ const sessions = await this.openSessions(manifest, clientFileIds, contents);
28
+ await this.sendBytes(sessions, clientFileIds, contents);
29
+ const finalized = await this.api.request(`/knowledge/files:batch/upload-session/${encodeURIComponent(sessions.batch_id)}/finalize`, { method: "POST", body: { mode: "finalize_uploaded" } });
30
+ return params.waitForBatchReady === true
31
+ ? this.waitUntilReady(finalized.batch_id)
32
+ : summarizeFinalized(finalized);
33
+ }
34
+ /** The batch with its items. */
35
+ async get(batchId) {
36
+ const id = String(batchId || "").trim();
37
+ if (!id) {
38
+ throw new Error("batchId is required.");
39
+ }
40
+ return this.api.request(`/knowledge/batches/${encodeURIComponent(id)}?include_items=true`, { method: "GET" });
41
+ }
42
+ /**
43
+ * Polls until the batch stops changing. Running out of time is reported in
44
+ * the result rather than thrown: the batch was accepted and will finish, so
45
+ * the caller needs its id and progress, not an error.
46
+ */
47
+ async waitUntilReady(batchId) {
48
+ const { last, settled } = await pollUntilSettled(() => this.get(batchId), isTerminal);
49
+ if (settled)
50
+ return last;
51
+ return {
52
+ ...last,
53
+ status: last.status || "timeout",
54
+ message: describeBatchTimeout(batchId, last),
55
+ };
56
+ }
57
+ openSessions(manifest, clientFileIds, contents) {
58
+ const files = contents.map((content, index) => ({
59
+ client_file_id: clientFileIds[index],
60
+ filename: content.filename,
61
+ content_type: content.mimeType || DEFAULT_MIME_TYPE,
62
+ size_bytes: content.bytes.byteLength,
63
+ }));
64
+ return this.api.request("/knowledge/files:batch/upload-session", {
65
+ method: "POST",
66
+ body: { manifest, files },
67
+ });
68
+ }
69
+ /** Items the API rejected have no session and are skipped. */
70
+ async sendBytes(sessions, clientFileIds, contents) {
71
+ const uploadUrls = new Map((sessions.accepted || []).map((item) => [
72
+ item.client_file_id,
73
+ item.upload_url,
74
+ ]));
75
+ for (const [index, clientFileId] of clientFileIds.entries()) {
76
+ const uploadUrl = uploadUrls.get(clientFileId);
77
+ if (uploadUrl)
78
+ await putUploadBytes(uploadUrl, contents[index]);
79
+ }
80
+ }
81
+ }
82
+ function isTerminal(batch) {
83
+ const status = String(batch.status || "")
84
+ .trim()
85
+ .toLowerCase();
86
+ return TERMINAL_STATUSES.includes(status);
87
+ }
88
+ /** What a caller gets back when it does not wait: one row per item. */
89
+ function summarizeFinalized(finalized) {
90
+ const queued = finalized.finalized || [];
91
+ const replayed = finalized.replayed || [];
92
+ const failed = finalized.failed || [];
93
+ return {
94
+ id: finalized.batch_id,
95
+ status: finalized.status,
96
+ accepted: queued.length + replayed.length,
97
+ rejected: failed.length,
98
+ items: [
99
+ ...queued.map((item) => trackedItem(item, "queued")),
100
+ ...replayed.map((item) => trackedItem(item, "replayed")),
101
+ ...(finalized.pending || []).map((item) => ({
102
+ ...item,
103
+ status: "pending",
104
+ })),
105
+ ...failed.map((item) => ({ ...item, status: "failed" })),
106
+ ],
107
+ request_id: finalized.request_id,
108
+ upload_session_finalize: finalized,
109
+ };
110
+ }
111
+ function trackedItem(item, status) {
112
+ return {
113
+ client_file_id: item.client_file_id,
114
+ status,
115
+ knowledgeId: item.knowledge_id,
116
+ taskId: item.task_id,
117
+ };
118
+ }
119
+ function describeBatchTimeout(batchId, batch) {
120
+ const count = (value) => Number(value || 0);
121
+ return `Batch ${batchId} was accepted but did not finish before timeout. Last status: ${String(batch.status || "timeout")}. queued=${count(batch.queued)} indexing=${count(batch.indexing)} active=${count(batch.active)} failed=${count(batch.failed)}. The files may still finish; check the batch again later.`;
122
+ }
@@ -0,0 +1,30 @@
1
+ import { normalizeKnowledgeBucketList, } from "./bucketList.js";
2
+ /** The team's knowledge buckets: the folders its sources are kept in. */
3
+ export class KnowledgeBuckets {
4
+ api;
5
+ constructor(api) {
6
+ this.api = api;
7
+ }
8
+ async list(options = {}) {
9
+ const query = options.includeArchived ? "?include_archived=true" : "";
10
+ const body = await this.api.request(`/knowledge/buckets${query}`, {
11
+ method: "GET",
12
+ });
13
+ return normalizeKnowledgeBucketList(body);
14
+ }
15
+ /** Creates an empty bucket; a slug already in use is refused by the API. */
16
+ async create(input) {
17
+ const body = await this.api.request("/knowledge/buckets", {
18
+ method: "POST",
19
+ headers: input.idempotencyKey
20
+ ? { "Idempotency-Key": input.idempotencyKey }
21
+ : {},
22
+ body: {
23
+ name: input.name,
24
+ ...(input.slug ? { slug: input.slug } : {}),
25
+ ...(input.description ? { description: input.description } : {}),
26
+ },
27
+ });
28
+ return body ?? {};
29
+ }
30
+ }
@@ -0,0 +1,147 @@
1
+ import { bucketFields, hasBucketDestination, } from "./BucketDestination.js";
2
+ import { compactStrings } from "./coerce.js";
3
+ import { pollUntilSettled } from "./polling.js";
4
+ import { DEFAULT_MIME_TYPE, decodeUploadContent, } from "./UploadContent.js";
5
+ import { putUploadBytes } from "./uploadBytes.js";
6
+ const READY_STATUS = "indexed";
7
+ const FAILED_STATUSES = new Set(["failed", "deleted"]);
8
+ const ONE_SOURCE = "Provide exactly one of `contentBase64` or `sourceUrl`.";
9
+ /**
10
+ * Single files in the team's Calypso knowledge: look one up, add one, and
11
+ * wait for one to become answerable.
12
+ */
13
+ export class KnowledgeFiles {
14
+ api;
15
+ constructor(api) {
16
+ this.api = api;
17
+ }
18
+ /** `verify` also asks the index itself, which is slower but authoritative. */
19
+ get(fileId, options = {}) {
20
+ const query = options.verify ? "?verify=gemini" : "";
21
+ return this.api.request(`/knowledge/files/${encodeURIComponent(fileId)}${query}`, { method: "GET" });
22
+ }
23
+ /** Adds one file from inline bytes or from a public link. */
24
+ async upload(params) {
25
+ if (!hasBucketDestination(params)) {
26
+ throw new Error("Knowledge file uploads require bucketIds, bucketSlugs, or bucket.");
27
+ }
28
+ const hasBytes = Boolean(params.contentBase64?.trim());
29
+ if (params.sourceUrl?.trim()) {
30
+ if (hasBytes)
31
+ throw new Error(ONE_SOURCE);
32
+ return this.importFromUrl({ ...params, sourceUrl: params.sourceUrl });
33
+ }
34
+ if (!hasBytes)
35
+ throw new Error(ONE_SOURCE);
36
+ const file = await this.uploadBytes(params, decodeUploadContent(params));
37
+ return params.waitForIndexing === true
38
+ ? this.waitUntilIndexed(file.id, file.task?.id || null)
39
+ : { file, task: file.task || null };
40
+ }
41
+ /**
42
+ * Has Calypso fetch a public file itself (`POST /knowledge/files/import-url`).
43
+ *
44
+ * The bytes never pass through this server, which is why a link is the
45
+ * preferred source for anything already online.
46
+ */
47
+ async importFromUrl(params) {
48
+ if (!hasBucketDestination(params)) {
49
+ throw new Error("Knowledge URL imports require bucketIds, bucketSlugs, or bucket.");
50
+ }
51
+ const tags = compactStrings(params.tags);
52
+ const imported = await this.api.request("/knowledge/files/import-url", {
53
+ method: "POST",
54
+ headers: idempotencyHeader(params.idempotencyKey),
55
+ body: {
56
+ url: params.sourceUrl.trim(),
57
+ ...(params.title?.trim() ? { title: params.title.trim() } : {}),
58
+ // This endpoint takes tags as one comma-separated string.
59
+ ...(tags ? { tags: tags.join(",") } : {}),
60
+ ...bucketFields(params),
61
+ },
62
+ });
63
+ const result = importedFile(imported);
64
+ return params.waitForIndexing === true && result.file.id
65
+ ? this.waitUntilIndexed(result.file.id, result.task?.id)
66
+ : result;
67
+ }
68
+ /** Polls until the file is indexed; throws if indexing fails or stalls. */
69
+ async waitUntilIndexed(fileId, taskId) {
70
+ const { last, settled } = await pollUntilSettled(() => this.read(fileId, taskId), (result) => {
71
+ const status = statusOf(result);
72
+ if (FAILED_STATUSES.has(status)) {
73
+ throw new Error(`Knowledge indexing entered terminal status \`${status}\`.`);
74
+ }
75
+ return status === READY_STATUS;
76
+ });
77
+ if (!settled)
78
+ throw new Error(describeIndexingTimeout(last));
79
+ return last;
80
+ }
81
+ /** Session, bytes, finalize: the three steps of a direct upload. */
82
+ async uploadBytes(params, content) {
83
+ const tags = compactStrings(params.tags);
84
+ const session = await this.api.request("/knowledge/files/upload-session", {
85
+ method: "POST",
86
+ headers: idempotencyHeader(params.idempotencyKey),
87
+ body: {
88
+ filename: content.filename,
89
+ content_type: content.mimeType || DEFAULT_MIME_TYPE,
90
+ size_bytes: content.bytes.byteLength,
91
+ ...(params.title?.trim() ? { title: params.title.trim() } : {}),
92
+ ...(tags ? { tags } : {}),
93
+ ...(params.metadata && Object.keys(params.metadata).length > 0
94
+ ? { metadata: params.metadata }
95
+ : {}),
96
+ ...bucketFields(params),
97
+ },
98
+ });
99
+ await putUploadBytes(session.upload_url, content);
100
+ return this.api.request(`/knowledge/files/upload-session/${encodeURIComponent(session.session_id)}/finalize`, { method: "POST", body: {} });
101
+ }
102
+ async read(fileId, taskId) {
103
+ const file = await this.get(fileId);
104
+ const task = taskId ? await this.getTask(taskId) : file.task || null;
105
+ return { file, task };
106
+ }
107
+ getTask(taskId) {
108
+ return this.api.request(`/knowledge/tasks/${encodeURIComponent(taskId)}`, {
109
+ method: "GET",
110
+ });
111
+ }
112
+ }
113
+ function idempotencyHeader(key) {
114
+ return key?.trim() ? { "Idempotency-Key": key.trim() } : {};
115
+ }
116
+ /** The import endpoint answers flat; tools return the same shape as uploads. */
117
+ function importedFile(imported) {
118
+ const taskId = imported.task_id ? String(imported.task_id) : null;
119
+ return {
120
+ file: {
121
+ id: String(imported.knowledge_id || ""),
122
+ object: "knowledge_file",
123
+ status: imported.ingestion_status,
124
+ title: imported.title,
125
+ filename: imported.filename,
126
+ content_type: imported.mime_type,
127
+ size_bytes: imported.size_bytes,
128
+ request_id: imported.request_id,
129
+ ...(imported.bucket_assignment
130
+ ? { bucket_assignment: imported.bucket_assignment }
131
+ : {}),
132
+ },
133
+ task: taskId ? { id: taskId, status: imported.ingestion_status } : null,
134
+ };
135
+ }
136
+ function statusOf(result) {
137
+ return String(result.file.status || result.task?.status || "")
138
+ .trim()
139
+ .toLowerCase();
140
+ }
141
+ function describeIndexingTimeout(result) {
142
+ const fileId = result.file.id ? ` file_id=${result.file.id}` : "";
143
+ const taskId = result.task?.id ? ` task_id=${result.task.id}` : "";
144
+ const status = statusOf(result);
145
+ const statusText = status ? ` Last status: ${status}.` : "";
146
+ return `Upload accepted but indexing did not start or finish before timeout.${statusText} It may still finish; check the file again later.${fileId}${taskId}`;
147
+ }
@@ -0,0 +1,68 @@
1
+ import { CalypsoApiClient } from "./CalypsoApiClient.js";
2
+ import { KnowledgeBuckets } from "./KnowledgeBuckets.js";
3
+ const EMPTY_SUMMARY = Object.freeze({
4
+ bucketCount: 0,
5
+ readyFileCount: 0,
6
+ bucketNames: [],
7
+ isEmpty: true,
8
+ });
9
+ function isActive(status) {
10
+ return (status ?? "active").toLowerCase() === "active";
11
+ }
12
+ /** Pure: the summary of one bucket list. */
13
+ export function summarizeKnowledge(list) {
14
+ const active = list.buckets.filter((bucket) => isActive(bucket.status));
15
+ const readyFileCount = active.reduce((total, bucket) => total +
16
+ (bucket.retrievableFileCount ??
17
+ bucket.fileCount ??
18
+ bucket.filesCount ??
19
+ bucket.fileIds.length), 0);
20
+ const bucketNames = active
21
+ .map((bucket) => bucket.name?.trim() ?? "")
22
+ .filter((name) => name.length > 0);
23
+ return {
24
+ bucketCount: active.length,
25
+ readyFileCount,
26
+ bucketNames,
27
+ isEmpty: active.length === 0 || readyFileCount === 0,
28
+ };
29
+ }
30
+ // Read on the request path of every cold cache entry: a slow answer must
31
+ // degrade to "unknown" (normal instructions, no short-circuit), not stall.
32
+ const INVENTORY_TIMEOUT_MS = 2000;
33
+ /** Loads the summary for one caller; rejects when the API cannot be reached. */
34
+ export async function loadKnowledgeInventory(config) {
35
+ const buckets = new KnowledgeBuckets(new CalypsoApiClient(config));
36
+ const list = await Promise.race([
37
+ buckets.list(),
38
+ new Promise((_, reject) => setTimeout(() => reject(new Error("Knowledge inventory timed out.")), INVENTORY_TIMEOUT_MS).unref?.()),
39
+ ]);
40
+ return summarizeKnowledge(list);
41
+ }
42
+ /**
43
+ * The inventory as a tool sees it in one request: seeded from the endpoint's
44
+ * cache, re-read once when the seed says "empty" so a source added seconds
45
+ * ago is not missed, and never read at all when there is no seed (the local
46
+ * stdio server and the unit tests keep today's behaviour).
47
+ */
48
+ export class KnowledgeInventory {
49
+ seed;
50
+ reload;
51
+ fresh = null;
52
+ constructor(seed, reload) {
53
+ this.seed = seed;
54
+ this.reload = reload;
55
+ }
56
+ /** The seed when it has knowledge; a fresh read when it is empty; null without a seed. */
57
+ current() {
58
+ if (!this.seed)
59
+ return Promise.resolve(null);
60
+ if (!this.seed.isEmpty)
61
+ return Promise.resolve(this.seed);
62
+ this.fresh ??= this.reload()
63
+ .then(summarizeKnowledge)
64
+ .catch(() => this.seed ?? EMPTY_SUMMARY);
65
+ return this.fresh;
66
+ }
67
+ }
68
+ export { EMPTY_SUMMARY as EMPTY_KNOWLEDGE_INVENTORY };
@@ -0,0 +1,34 @@
1
+ const MAX_RESULTS = 20;
2
+ /**
3
+ * Retrieval without an answer (`POST /search`): the passages and sources an
4
+ * agent would cite, for callers that want the evidence itself.
5
+ */
6
+ export class KnowledgeSearch {
7
+ api;
8
+ constructor(api) {
9
+ this.api = api;
10
+ }
11
+ search(options) {
12
+ const agent = options.agent?.trim();
13
+ const buckets = (options.buckets ?? [])
14
+ .map((item) => String(item || "").trim())
15
+ .filter(Boolean);
16
+ return this.api.request("/search", {
17
+ method: "POST",
18
+ body: {
19
+ query: options.query,
20
+ ...(agent ? { agent } : {}),
21
+ ...(options.buckets?.length ? { buckets } : {}),
22
+ ...maxResultsField(options.maxResults),
23
+ },
24
+ });
25
+ }
26
+ }
27
+ function maxResultsField(maxResults) {
28
+ if (typeof maxResults !== "number" || !Number.isFinite(maxResults)) {
29
+ return {};
30
+ }
31
+ return {
32
+ max_results: Math.max(1, Math.min(MAX_RESULTS, Math.floor(maxResults))),
33
+ };
34
+ }
@@ -0,0 +1,49 @@
1
+ /** Web pages kept as knowledge in the team's buckets. */
2
+ export class KnowledgeWebsites {
3
+ api;
4
+ constructor(api) {
5
+ this.api = api;
6
+ }
7
+ /**
8
+ * Adds a page in one call (`POST /knowledge/websites`): Calypso reads it,
9
+ * writes its title, summary and tags, and files it in the given buckets.
10
+ *
11
+ * The normalized URL identifies the website within a team, so adding the
12
+ * same page twice is a conflict unless the same `Idempotency-Key` is sent,
13
+ * in which case the existing website is returned.
14
+ */
15
+ async add(input) {
16
+ const url = String(input.url || "").trim();
17
+ if (!url) {
18
+ throw new Error("A website `url` is required.");
19
+ }
20
+ const bucketSlugs = slugsOf(input);
21
+ if (!(input.bucketIds?.length || bucketSlugs.length)) {
22
+ throw new Error("Website ingestion requires bucketIds, bucketSlugs, or bucket.");
23
+ }
24
+ const title = input.title?.trim();
25
+ const tagsHint = input.tagsHint?.trim();
26
+ const preferredLanguage = input.preferredLanguage?.trim();
27
+ const idempotencyKey = input.idempotencyKey?.trim();
28
+ return this.api.request("/knowledge/websites", {
29
+ method: "POST",
30
+ headers: idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {},
31
+ body: {
32
+ url,
33
+ ...(title ? { title } : {}),
34
+ ...(tagsHint ? { tags_hint: tagsHint } : {}),
35
+ ...(preferredLanguage ? { preferred_language: preferredLanguage } : {}),
36
+ ...(input.bucketIds?.length ? { bucket_ids: input.bucketIds } : {}),
37
+ ...(bucketSlugs.length ? { bucket_slugs: bucketSlugs } : {}),
38
+ ...(input.createMissingBuckets === true
39
+ ? { create_missing_buckets: true }
40
+ : {}),
41
+ },
42
+ });
43
+ }
44
+ }
45
+ /** This endpoint has no single-bucket field; the shortcut joins the slugs. */
46
+ function slugsOf(input) {
47
+ const bucket = input.bucket?.trim();
48
+ return [...(input.bucketSlugs || []), ...(bucket ? [bucket] : [])].filter((slug) => slug.trim().length > 0);
49
+ }