@hashgraphonline/conversational-agent 0.2.217 → 0.2.218

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.
@@ -1,66 +1,38 @@
1
1
  import { BaseHederaQueryTool } from "hedera-agent-kit";
2
- import { Size, Duration } from "@ethersphere/bee-js";
3
2
  import { z } from "zod";
4
- import { makeDate, errorHasStatus, getErrorMessage, getResponseWithStructuredContent } from "./index62.js";
5
- import { NOT_FOUND_STATUS, GATEWAY_STAMP_ERROR_MESSAGE, BAD_REQUEST_STATUS } from "./index63.js";
6
- const ExtendPostageStampSchema = z.object({
7
- postageBatchId: z.string(),
8
- duration: z.string().optional(),
9
- size: z.number().optional()
3
+ import { errorHasStatus, getBatchSummary, getResponseWithStructuredContent } from "./index62.js";
4
+ import { NOT_FOUND_STATUS, GATEWAY_STAMP_ERROR_MESSAGE } from "./index63.js";
5
+ const GetPostageStampSchema = z.object({
6
+ postageBatchId: z.string()
10
7
  });
11
- class ExtendPostageStampTool extends BaseHederaQueryTool {
8
+ class GetPostageStampTool extends BaseHederaQueryTool {
12
9
  constructor(params) {
13
10
  const { bee, config, ...rest } = params;
14
11
  super(rest);
15
- this.name = "swarm-extend-postage-stamp";
16
- this.description = `Increase the duration (relative to current duration) or size (in megabytes) of a postage stamp.
17
- postageBatchId: The id of the batch for which extend is performed.
18
- size: The storage size in MB (Megabytes). These other size units convert like this to MB: 1 byte = 0.000001 MB, 1 KB = 0.001 MB, 1GB= 1000MB.
19
- duration: Duration for which the data should be stored. Time to live of the postage stamp, e.g. 1d - 1 day, 1w - 1 week, 1month - 1 month.
12
+ this.name = "swarm-get-postage-stamp";
13
+ this.description = `Get a specific postage stamp based on postageBatchId.
14
+ postageBatchId: The id of the stamp which is requested.
20
15
  `;
21
16
  this.namespace = "swarm";
22
- this.specificInputSchema = ExtendPostageStampSchema;
17
+ this.specificInputSchema = GetPostageStampSchema;
23
18
  this.bee = bee;
24
19
  this.config = config;
25
20
  }
26
21
  async executeQuery(input) {
27
- const { postageBatchId, duration, size } = input;
22
+ const { postageBatchId } = input;
28
23
  if (!postageBatchId) {
29
24
  this.logger.error(
30
25
  "Missing required parameter: postageBatchId."
31
26
  );
32
27
  throw new Error("Missing required parameter: postageBatchId.");
33
- } else if (!duration && !size) {
34
- this.logger.error(
35
- "You need at least one parameter from duration and size."
36
- );
37
- throw new Error("You need at least one parameter from duration and size.");
38
- }
39
- const extendSize = !!size ? Size.fromMegabytes(size) : Size.fromBytes(1);
40
- let extendDuration = Duration.ZERO;
41
- try {
42
- if (duration) {
43
- extendDuration = Duration.fromMilliseconds(makeDate(duration));
44
- }
45
- } catch (makeDateError) {
46
- this.logger.error(
47
- "Invalid parameter: duration."
48
- );
49
- throw new Error("Invalid parameter: duration.");
50
28
  }
51
- let extendStorageResponse;
29
+ let rawPostageBatch;
52
30
  try {
53
- extendStorageResponse = await this.bee.extendStorage(
54
- postageBatchId,
55
- extendSize,
56
- extendDuration
57
- );
31
+ rawPostageBatch = await this.bee.getPostageBatch(postageBatchId);
58
32
  } catch (error) {
59
- let errorMessage = "Extend failed.";
33
+ let errorMessage = "Retrieval of postage batch failed.";
60
34
  if (errorHasStatus(error, NOT_FOUND_STATUS)) {
61
35
  errorMessage = GATEWAY_STAMP_ERROR_MESSAGE;
62
- } else if (errorHasStatus(error, BAD_REQUEST_STATUS)) {
63
- errorMessage = getErrorMessage(error);
64
36
  }
65
37
  this.logger.error(
66
38
  errorMessage,
@@ -68,12 +40,19 @@ class ExtendPostageStampTool extends BaseHederaQueryTool {
68
40
  );
69
41
  throw new Error(errorMessage);
70
42
  }
71
- return getResponseWithStructuredContent({
72
- postageBatchId: extendStorageResponse.toHex()
73
- });
43
+ const batch = {
44
+ ...rawPostageBatch,
45
+ batchID: rawPostageBatch.batchID.toHex()
46
+ };
47
+ const batchSummary = getBatchSummary(rawPostageBatch);
48
+ const content = {
49
+ raw: batch,
50
+ summary: batchSummary
51
+ };
52
+ return getResponseWithStructuredContent(content);
74
53
  }
75
54
  }
76
55
  export {
77
- ExtendPostageStampTool
56
+ GetPostageStampTool
78
57
  };
79
58
  //# sourceMappingURL=index52.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index52.js","sources":["../../src/plugins/community/swarm/tools/ExtendPostageStampTool.ts"],"sourcesContent":["import {\r\n BaseHederaQueryTool,\r\n HederaAgentKit,\r\n type GenericPluginContext,\r\n} from \"hedera-agent-kit\";\r\nimport { BatchId, Bee, Duration, Size } from \"@ethersphere/bee-js\";\r\nimport { z } from \"zod\";\r\nimport {\r\n errorHasStatus,\r\n getErrorMessage,\r\n getResponseWithStructuredContent,\r\n makeDate,\r\n ToolResponse,\r\n} from \"../utils\";\r\nimport { BAD_REQUEST_STATUS, GATEWAY_STAMP_ERROR_MESSAGE, NOT_FOUND_STATUS } from \"../constants\";\r\nimport { SwarmConfig } from \"../config\";\r\n\r\nconst ExtendPostageStampSchema = z.object({\r\n postageBatchId: z.string(),\r\n duration: z.string().optional(),\r\n size: z.number().optional(),\r\n});\r\n\r\nexport class ExtendPostageStampTool extends BaseHederaQueryTool<typeof ExtendPostageStampSchema> {\r\n name = \"swarm-extend-postage-stamp\";\r\n description = `Increase the duration (relative to current duration) or size (in megabytes) of a postage stamp.\r\n postageBatchId: The id of the batch for which extend is performed.\r\n size: The storage size in MB (Megabytes). These other size units convert like this to MB: 1 byte = 0.000001 MB, 1 KB = 0.001 MB, 1GB= 1000MB.\r\n duration: Duration for which the data should be stored. Time to live of the postage stamp, e.g. 1d - 1 day, 1w - 1 week, 1month - 1 month.\r\n `;\r\n namespace = \"swarm\";\r\n specificInputSchema = ExtendPostageStampSchema;\r\n bee: Bee;\r\n config: SwarmConfig;\r\n \r\n constructor(params: {\r\n hederaKit: HederaAgentKit;\r\n config: SwarmConfig;\r\n logger?: GenericPluginContext['logger'];\r\n bee: Bee;\r\n }) {\r\n const { bee, config, ...rest } = params;\r\n super(rest);\r\n this.bee = bee;\r\n this.config = config;\r\n }\r\n \r\n protected async executeQuery(\r\n input: z.infer<typeof ExtendPostageStampSchema>\r\n ): Promise<ToolResponse | string> {\r\n const { postageBatchId, duration, size } = input;\r\n\r\n if (!postageBatchId) {\r\n this.logger.error(\r\n 'Missing required parameter: postageBatchId.'\r\n );\r\n\r\n throw new Error('Missing required parameter: postageBatchId.');\r\n } else if (!duration && !size) {\r\n this.logger.error(\r\n 'You need at least one parameter from duration and size.'\r\n );\r\n\r\n throw new Error('You need at least one parameter from duration and size.');\r\n }\r\n\r\n // If size is missing, Size.fromBytes(1) will get smallest depth and not increase size.\r\n const extendSize = !!size ? Size.fromMegabytes(size) : Size.fromBytes(1); \r\n let extendDuration = Duration.ZERO;\r\n\r\n try {\r\n if (duration) {\r\n extendDuration = Duration.fromMilliseconds(makeDate(duration));\r\n }\r\n } catch (makeDateError) {\r\n this.logger.error(\r\n 'Invalid parameter: duration.'\r\n );\r\n\r\n throw new Error('Invalid parameter: duration.');\r\n }\r\n\r\n let extendStorageResponse;\r\n\r\n try {\r\n extendStorageResponse = await this.bee.extendStorage(\r\n postageBatchId,\r\n extendSize,\r\n extendDuration\r\n );\r\n } catch (error) {\r\n let errorMessage = 'Extend failed.';\r\n\r\n if (errorHasStatus(error, NOT_FOUND_STATUS)) {\r\n errorMessage = GATEWAY_STAMP_ERROR_MESSAGE;\r\n } else if (errorHasStatus(error, BAD_REQUEST_STATUS)) {\r\n errorMessage = getErrorMessage(error);\r\n }\r\n\r\n this.logger.error(\r\n errorMessage,\r\n error\r\n );\r\n\r\n throw new Error(errorMessage);\r\n }\r\n\r\n return getResponseWithStructuredContent({\r\n postageBatchId: extendStorageResponse.toHex(),\r\n });\r\n }\r\n}\r\n"],"names":[],"mappings":";;;;;AAiBA,MAAM,2BAA2B,EAAE,OAAO;AAAA,EACxC,gBAAgB,EAAE,OAAA;AAAA,EAClB,UAAU,EAAE,OAAA,EAAS,SAAA;AAAA,EACrB,MAAM,EAAE,OAAA,EAAS,SAAA;AACnB,CAAC;AAEM,MAAM,+BAA+B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AAEA,WAAO,iCAAiC;AAAA,MACtC,gBAAgB,sBAAsB,MAAA;AAAA,IAAM,CAC7C;AAAA,EACH;AACF;"}
1
+ {"version":3,"file":"index52.js","sources":["../../src/plugins/community/swarm/tools/GetPostageStampTool.ts"],"sourcesContent":["import {\r\n type GenericPluginContext,\r\n BaseHederaQueryTool,\r\n type HederaAgentKit,\r\n} from \"hedera-agent-kit\";\r\nimport { Bee } from \"@ethersphere/bee-js\";\r\nimport { z } from \"zod\";\r\nimport {\r\n PostageBatchCurated,\r\n PostageBatchSummary,\r\n ResponseContent,\r\n} from \"../model\";\r\nimport {\r\n errorHasStatus,\r\n getBatchSummary,\r\n getResponseWithStructuredContent,\r\n ToolResponse,\r\n} from \"../utils\";\r\nimport { GATEWAY_STAMP_ERROR_MESSAGE, NOT_FOUND_STATUS } from \"../constants\";\r\nimport { SwarmConfig } from \"../config\";\r\n\r\nconst GetPostageStampSchema = z.object({\r\n postageBatchId: z.string(),\r\n});\r\n\r\nexport class GetPostageStampTool extends BaseHederaQueryTool<typeof GetPostageStampSchema> {\r\n name = \"swarm-get-postage-stamp\";\r\n description = `Get a specific postage stamp based on postageBatchId.\r\n postageBatchId: The id of the stamp which is requested.\r\n `;\r\n namespace = \"swarm\";\r\n specificInputSchema = GetPostageStampSchema;\r\n bee: Bee;\r\n config: SwarmConfig;\r\n \r\n constructor(params: {\r\n hederaKit: HederaAgentKit;\r\n config: SwarmConfig;\r\n logger?: GenericPluginContext['logger'];\r\n bee: Bee;\r\n }) {\r\n const { bee, config, ...rest } = params;\r\n super(rest);\r\n this.bee = bee;\r\n this.config = config;\r\n }\r\n\r\n protected async executeQuery(\r\n input: z.infer<typeof GetPostageStampSchema>\r\n ): Promise<ToolResponse | string> {\r\n const { postageBatchId } = input;\r\n if (!postageBatchId) {\r\n this.logger.error(\r\n 'Missing required parameter: postageBatchId.'\r\n );\r\n\r\n throw new Error(\"Missing required parameter: postageBatchId.\");\r\n }\r\n\r\n let rawPostageBatch;\r\n\r\n try {\r\n rawPostageBatch = await this.bee.getPostageBatch(postageBatchId);\r\n } catch (error) {\r\n let errorMessage = 'Retrieval of postage batch failed.';\r\n \r\n if (errorHasStatus(error, NOT_FOUND_STATUS)) {\r\n errorMessage = GATEWAY_STAMP_ERROR_MESSAGE;\r\n }\r\n\r\n this.logger.error(\r\n errorMessage,\r\n error\r\n );\r\n\r\n throw new Error(errorMessage);\r\n }\r\n\r\n const batch: PostageBatchCurated = {\r\n ...rawPostageBatch,\r\n batchID: rawPostageBatch.batchID.toHex(),\r\n };\r\n const batchSummary: PostageBatchSummary = getBatchSummary(rawPostageBatch);\r\n\r\n const content: ResponseContent<PostageBatchCurated, PostageBatchSummary> = {\r\n raw: batch,\r\n summary: batchSummary,\r\n };\r\n\r\n return getResponseWithStructuredContent(content);\r\n }\r\n}\r\n"],"names":[],"mappings":";;;;AAqBA,MAAM,wBAAwB,EAAE,OAAO;AAAA,EACrC,gBAAgB,EAAE,OAAA;AACpB,CAAC;AAEM,MAAM,4BAA4B,oBAAkD;AAAA,EAUzF,YAAY,QAKT;AACD,UAAM,EAAE,KAAK,QAAQ,GAAG,SAAS;AACjC,UAAM,IAAI;AAhBZ,SAAA,OAAO;AACP,SAAA,cAAc;AAAA;AAAA;AAGd,SAAA,YAAY;AACZ,SAAA,sBAAsB;AAYpB,SAAK,MAAM;AACX,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,MAAgB,aACZ,OAC8B;AAChC,UAAM,EAAE,mBAAmB;AAC3B,QAAI,CAAC,gBAAgB;AACnB,WAAK,OAAO;AAAA,QACV;AAAA,MAAA;AAGF,YAAM,IAAI,MAAM,6CAA6C;AAAA,IAC/D;AAEA,QAAI;AAEJ,QAAI;AACF,wBAAkB,MAAM,KAAK,IAAI,gBAAgB,cAAc;AAAA,IACjE,SAAS,OAAO;AACd,UAAI,eAAe;AAEnB,UAAI,eAAe,OAAO,gBAAgB,GAAG;AAC3C,uBAAe;AAAA,MACjB;AAEA,WAAK,OAAO;AAAA,QACV;AAAA,QACA;AAAA,MAAA;AAGF,YAAM,IAAI,MAAM,YAAY;AAAA,IAC9B;AAEA,UAAM,QAA6B;AAAA,MACjC,GAAG;AAAA,MACH,SAAS,gBAAgB,QAAQ,MAAA;AAAA,IAAM;AAEzC,UAAM,eAAoC,gBAAgB,eAAe;AAEzE,UAAM,UAAqE;AAAA,MACzE,KAAK;AAAA,MACL,SAAS;AAAA,IAAA;AAGX,WAAO,iCAAiC,OAAO;AAAA,EACjD;AACF;"}
@@ -1,75 +1,83 @@
1
- import { BaseHederaQueryTool } from "hedera-agent-kit";
1
+ import { Wallet } from "@ethereumjs/wallet";
2
2
  import { z } from "zod";
3
- import { getResponseWithStructuredContent } from "./index62.js";
4
- import { GATEWAY_TAG_ERROR_MESSAGE } from "./index63.js";
5
- const QueryUploadProgressSchema = z.object({
6
- tagId: z.string()
3
+ import crypto from "crypto";
4
+ import { hexToBytes, errorHasStatus, getErrorMessage, getResponseWithStructuredContent } from "./index62.js";
5
+ import { BaseHederaQueryTool } from "hedera-agent-kit";
6
+ import { BAD_REQUEST_STATUS } from "./index63.js";
7
+ const ReadFeedSchema = z.object({
8
+ memoryTopic: z.string(),
9
+ owner: z.string().optional()
7
10
  });
8
- class QueryUploadProgressTool extends BaseHederaQueryTool {
11
+ class ReadFeedTool extends BaseHederaQueryTool {
9
12
  constructor(params) {
10
13
  const { bee, config, ...rest } = params;
11
14
  super(rest);
12
- this.name = "swarm-query-upload-progress";
13
- this.description = `Query upload progress for a specific upload session identified with the returned Tag ID.
14
- tagId: Tag ID returned by swarm-upload-file and swarm-upload-folder tools to track upload progress.
15
+ this.name = "swarm-read-feed";
16
+ this.description = `Retrieve the latest data from the feed of a given topic.
17
+ memoryTopic: Feed topic.
18
+ owner: When accessing external memory or feed, ethereum address of the owner must be set.
15
19
  `;
16
20
  this.namespace = "swarm";
17
- this.specificInputSchema = QueryUploadProgressSchema;
21
+ this.specificInputSchema = ReadFeedSchema;
18
22
  this.bee = bee;
19
23
  this.config = config;
20
24
  }
21
25
  async executeQuery(input) {
22
- if (!input?.tagId) {
26
+ const { memoryTopic, owner } = input;
27
+ if (!memoryTopic) {
23
28
  this.logger.error(
24
- "Missing required parameter: tagId."
29
+ "Missing required parameter: memoryTopic."
25
30
  );
26
- throw new Error("Missing required parameter: tagId.");
31
+ throw new Error("Missing required parameter: memoryTopic.");
27
32
  }
28
- const tagUid = Number.parseInt(input.tagId, 10);
29
- if (Number.isNaN(tagUid)) {
30
- this.logger.error(
31
- "Invalid tagId format. Expected a numeric string."
32
- );
33
- throw new Error("Invalid tagId format. Expected a numeric string.");
33
+ this.logger.info(`[API] Downloading text from Swarm feed with topic: ${memoryTopic}.`);
34
+ if (!this.config.beeFeedPK) {
35
+ this.logger.error("Feed private key not configured.");
36
+ throw new Error("Feed private key not configured.");
34
37
  }
35
- try {
36
- const tag = await this.bee.retrieveTag(tagUid);
37
- const synced = tag.synced ?? 0;
38
- const seen = tag.seen ?? 0;
39
- const processed = synced + seen;
40
- const total = tag.split ?? 0;
41
- const startedAt = tag.startedAt;
42
- const processedPercentage = total > 0 ? Math.round(processed / total * 100) : 0;
43
- const isComplete = processedPercentage === 100;
44
- let tagDeleted = false;
45
- if (isComplete) {
46
- try {
47
- await this.bee.deleteTag(tagUid);
48
- tagDeleted = true;
49
- } catch {
50
- }
38
+ let topic = memoryTopic;
39
+ if (topic.startsWith("0x")) {
40
+ topic = topic.slice(2);
41
+ }
42
+ const isHexString = /^[0-9a-fA-F]{64}$/.test(topic);
43
+ if (!isHexString) {
44
+ const hash = crypto.createHash("sha256").update(memoryTopic).digest("hex");
45
+ topic = hash;
46
+ }
47
+ const topicBytes = hexToBytes(topic);
48
+ let feedOwner = owner;
49
+ if (!feedOwner) {
50
+ const feedPrivateKey = hexToBytes(this.config.beeFeedPK);
51
+ const signer = new Wallet(feedPrivateKey);
52
+ feedOwner = signer.getAddressString().slice(2);
53
+ } else {
54
+ if (feedOwner.startsWith("0x")) {
55
+ feedOwner = feedOwner.slice(2);
56
+ }
57
+ if (feedOwner.length !== 40) {
58
+ this.logger.error("Owner must be a valid Ethereum address.");
59
+ throw new Error("Owner must be a valid Ethereum address.");
51
60
  }
52
- return getResponseWithStructuredContent({
53
- processedPercentage,
54
- message: isComplete ? "Upload completed successfully." : `Upload progress: ${processedPercentage}% processed`,
55
- startedAt,
56
- tagAddress: tag.address
57
- });
61
+ }
62
+ let textData;
63
+ try {
64
+ const feedReader = this.bee.makeFeedReader(topicBytes, feedOwner);
65
+ const latestUpdate = await feedReader.downloadPayload();
66
+ textData = latestUpdate.payload.toUtf8();
58
67
  } catch (error) {
59
- let errorMessage = `Failed to retrieve upload progress: ${error?.message ?? "Unknown error"}`;
60
- const status = error?.status ?? error?.response?.status;
61
- if (status === 404) {
62
- errorMessage = `Tag with ID ${input.tagId} does not exist or has been deleted. ` + GATEWAY_TAG_ERROR_MESSAGE;
68
+ let errorMessage = "Reading feed failed.";
69
+ if (errorHasStatus(error, BAD_REQUEST_STATUS)) {
70
+ errorMessage = getErrorMessage(error);
63
71
  }
64
- this.logger.error(
65
- errorMessage,
66
- error
67
- );
72
+ this.logger.error(errorMessage, error);
68
73
  throw new Error(errorMessage);
69
74
  }
75
+ return getResponseWithStructuredContent({
76
+ textData
77
+ });
70
78
  }
71
79
  }
72
80
  export {
73
- QueryUploadProgressTool
81
+ ReadFeedTool
74
82
  };
75
83
  //# sourceMappingURL=index53.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index53.js","sources":["../../src/plugins/community/swarm/tools/QueryUploadProgressTool.ts"],"sourcesContent":["import {\r\n type GenericPluginContext,\r\n BaseHederaQueryTool,\r\n type HederaAgentKit,\r\n} from \"hedera-agent-kit\";\r\nimport { Bee } from \"@ethersphere/bee-js\";\r\nimport { z } from \"zod\";\r\nimport {\r\n errorHasStatus,\r\n getResponseWithStructuredContent,\r\n ToolResponse,\r\n} from \"../utils\";\r\nimport { GATEWAY_TAG_ERROR_MESSAGE } from \"../constants\";\r\nimport { SwarmConfig } from \"../config\";\r\n\r\nconst QueryUploadProgressSchema = z.object({\r\n tagId: z.string(),\r\n});\r\n\r\nexport class QueryUploadProgressTool extends BaseHederaQueryTool<typeof QueryUploadProgressSchema> {\r\n name = \"swarm-query-upload-progress\";\r\n description = `Query upload progress for a specific upload session identified with the returned Tag ID.\r\n tagId: Tag ID returned by swarm-upload-file and swarm-upload-folder tools to track upload progress.\r\n `;\r\n namespace = \"swarm\";\r\n specificInputSchema = QueryUploadProgressSchema;\r\n bee: Bee;\r\n config: SwarmConfig;\r\n \r\n constructor(params: {\r\n hederaKit: HederaAgentKit;\r\n config: SwarmConfig;\r\n logger?: GenericPluginContext['logger'];\r\n bee: Bee;\r\n }) {\r\n const { bee, config, ...rest } = params;\r\n super(rest);\r\n this.bee = bee;\r\n this.config = config;\r\n }\r\n\r\n protected async executeQuery(\r\n input: z.infer<typeof QueryUploadProgressSchema>\r\n ): Promise<ToolResponse | string> {\r\n if (!input?.tagId) {\r\n this.logger.error(\r\n 'Missing required parameter: tagId.'\r\n );\r\n\r\n throw new Error('Missing required parameter: tagId.');\r\n }\r\n\r\n const tagUid = Number.parseInt(input.tagId, 10);\r\n if (Number.isNaN(tagUid)) {\r\n this.logger.error(\r\n 'Invalid tagId format. Expected a numeric string.'\r\n );\r\n\r\n throw new Error('Invalid tagId format. Expected a numeric string.');\r\n }\r\n\r\n try {\r\n const tag = await this.bee.retrieveTag(tagUid);\r\n\r\n const synced = tag.synced ?? 0;\r\n const seen = tag.seen ?? 0;\r\n const processed = synced + seen;\r\n const total = tag.split ?? 0;\r\n const startedAt = tag.startedAt;\r\n\r\n const processedPercentage =\r\n total > 0 ? Math.round((processed / total) * 100) : 0;\r\n const isComplete = processedPercentage === 100;\r\n\r\n let tagDeleted = false;\r\n if (isComplete) {\r\n try {\r\n await this.bee.deleteTag(tagUid);\r\n tagDeleted = true;\r\n } catch {\r\n // Non-fatal: if deletion fails we still return progress\r\n }\r\n }\r\n\r\n return getResponseWithStructuredContent({\r\n processedPercentage,\r\n message: isComplete\r\n ? \"Upload completed successfully.\"\r\n : `Upload progress: ${processedPercentage}% processed`,\r\n startedAt,\r\n tagAddress: tag.address,\r\n });\r\n } catch (error: any) {\r\n let errorMessage = `Failed to retrieve upload progress: ${error?.message ?? \"Unknown error\"}`;\r\n \r\n const status = error?.status ?? error?.response?.status;\r\n if (status === 404) {\r\n errorMessage = `Tag with ID ${input.tagId} does not exist or has been deleted. ` + GATEWAY_TAG_ERROR_MESSAGE;\r\n }\r\n \r\n this.logger.error(\r\n errorMessage,\r\n error\r\n );\r\n \r\n throw new Error(errorMessage);\r\n }\r\n }\r\n}\r\n"],"names":[],"mappings":";;;;AAeA,MAAM,4BAA4B,EAAE,OAAO;AAAA,EACzC,OAAO,EAAE,OAAA;AACX,CAAC;AAEM,MAAM,gCAAgC,oBAAsD;AAAA,EAUjG,YAAY,QAKT;AACD,UAAM,EAAE,KAAK,QAAQ,GAAG,SAAS;AACjC,UAAM,IAAI;AAhBZ,SAAA,OAAO;AACP,SAAA,cAAc;AAAA;AAAA;AAGd,SAAA,YAAY;AACZ,SAAA,sBAAsB;AAYpB,SAAK,MAAM;AACX,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,MAAgB,aACZ,OAC8B;AAChC,QAAI,CAAC,OAAO,OAAO;AACjB,WAAK,OAAO;AAAA,QACV;AAAA,MAAA;AAGF,YAAM,IAAI,MAAM,oCAAoC;AAAA,IACtD;AAEA,UAAM,SAAS,OAAO,SAAS,MAAM,OAAO,EAAE;AAC9C,QAAI,OAAO,MAAM,MAAM,GAAG;AACxB,WAAK,OAAO;AAAA,QACV;AAAA,MAAA;AAGF,YAAM,IAAI,MAAM,kDAAkD;AAAA,IACpE;AAEA,QAAI;AACF,YAAM,MAAM,MAAM,KAAK,IAAI,YAAY,MAAM;AAE7C,YAAM,SAAS,IAAI,UAAU;AAC7B,YAAM,OAAO,IAAI,QAAQ;AACzB,YAAM,YAAY,SAAS;AAC3B,YAAM,QAAQ,IAAI,SAAS;AAC3B,YAAM,YAAY,IAAI;AAEtB,YAAM,sBACJ,QAAQ,IAAI,KAAK,MAAO,YAAY,QAAS,GAAG,IAAI;AACtD,YAAM,aAAa,wBAAwB;AAE3C,UAAI,aAAa;AACjB,UAAI,YAAY;AACd,YAAI;AACF,gBAAM,KAAK,IAAI,UAAU,MAAM;AAC/B,uBAAa;AAAA,QACf,QAAQ;AAAA,QAER;AAAA,MACF;AAEA,aAAO,iCAAiC;AAAA,QACtC;AAAA,QACA,SAAS,aACL,mCACA,oBAAoB,mBAAmB;AAAA,QAC3C;AAAA,QACA,YAAY,IAAI;AAAA,MAAA,CACjB;AAAA,IACH,SAAS,OAAY;AACnB,UAAI,eAAe,uCAAuC,OAAO,WAAW,eAAe;AAE3F,YAAM,SAAS,OAAO,UAAU,OAAO,UAAU;AACjD,UAAI,WAAW,KAAK;AAClB,uBAAe,eAAe,MAAM,KAAK,0CAA0C;AAAA,MACrF;AAEA,WAAK,OAAO;AAAA,QACV;AAAA,QACA;AAAA,MAAA;AAGF,YAAM,IAAI,MAAM,YAAY;AAAA,IAC9B;AAAA,EACF;AACF;"}
1
+ {"version":3,"file":"index53.js","sources":["../../src/plugins/community/swarm/tools/ReadFeedTool.ts"],"sourcesContent":["import { Bee } from \"@ethersphere/bee-js\";\r\nimport { Wallet } from \"@ethereumjs/wallet\";\r\nimport { z } from \"zod\";\r\nimport crypto from \"crypto\";\r\nimport { errorHasStatus, getErrorMessage, getResponseWithStructuredContent, hexToBytes, ToolResponse } from \"../utils\";\r\nimport { BaseHederaQueryTool, GenericPluginContext, HederaAgentKit } from \"hedera-agent-kit\";\r\nimport { SwarmConfig } from \"../config\";\r\nimport { BAD_REQUEST_STATUS } from \"../constants\";\r\n\r\nconst ReadFeedSchema = z.object({\r\n memoryTopic: z.string(),\r\n owner: z.string().optional()\r\n});\r\n\r\nexport class ReadFeedTool extends BaseHederaQueryTool<typeof ReadFeedSchema> {\r\n name = \"swarm-read-feed\";\r\n description = `Retrieve the latest data from the feed of a given topic.\r\n memoryTopic: Feed topic.\r\n owner: When accessing external memory or feed, ethereum address of the owner must be set.\r\n `;\r\n namespace = \"swarm\";\r\n specificInputSchema = ReadFeedSchema;\r\n bee: Bee;\r\n config: SwarmConfig;\r\n \r\n constructor(params: {\r\n hederaKit: HederaAgentKit;\r\n config: SwarmConfig;\r\n logger?: GenericPluginContext['logger'];\r\n bee: Bee;\r\n }) {\r\n const { bee, config, ...rest } = params;\r\n super(rest);\r\n this.bee = bee;\r\n this.config = config;\r\n }\r\n\r\n protected async executeQuery(\r\n input: z.infer<typeof ReadFeedSchema>\r\n ): Promise<ToolResponse | string> {\r\n const { memoryTopic, owner } = input;\r\n\r\n if (!memoryTopic) {\r\n this.logger.error(\r\n 'Missing required parameter: memoryTopic.'\r\n );\r\n\r\n throw new Error('Missing required parameter: memoryTopic.');\r\n }\r\n\r\n this.logger.info(`[API] Downloading text from Swarm feed with topic: ${memoryTopic}.`);\r\n\r\n if (!this.config.beeFeedPK) {\r\n this.logger.error('Feed private key not configured.');\r\n\r\n throw new Error('Feed private key not configured.');\r\n }\r\n\r\n // Process topic - if not a hex string, hash it\r\n let topic = memoryTopic;\r\n if (topic.startsWith(\"0x\")) {\r\n topic = topic.slice(2);\r\n }\r\n const isHexString = /^[0-9a-fA-F]{64}$/.test(topic);\r\n\r\n if (!isHexString) {\r\n // Hash the topic string using SHA-256\r\n const hash = crypto.createHash(\"sha256\").update(memoryTopic).digest(\"hex\");\r\n topic = hash;\r\n }\r\n\r\n // Convert topic string to bytes\r\n const topicBytes = hexToBytes(topic);\r\n\r\n let feedOwner = owner;\r\n if (!feedOwner) {\r\n const feedPrivateKey = hexToBytes(this.config.beeFeedPK);\r\n const signer = new Wallet(feedPrivateKey);\r\n feedOwner = signer.getAddressString().slice(2);\r\n } else {\r\n if (feedOwner.startsWith(\"0x\")) {\r\n feedOwner = feedOwner.slice(2);\r\n }\r\n if (feedOwner.length !== 40) {\r\n this.logger.error('Owner must be a valid Ethereum address.');\r\n\r\n throw new Error('Owner must be a valid Ethereum address.');\r\n }\r\n }\r\n\r\n let textData;\r\n \r\n try {\r\n const feedReader = this.bee.makeFeedReader(topicBytes, feedOwner);\r\n const latestUpdate = await feedReader.downloadPayload();\r\n textData = latestUpdate.payload.toUtf8();\r\n } catch (error) {\r\n let errorMessage = 'Reading feed failed.';\r\n if (errorHasStatus(error, BAD_REQUEST_STATUS)) {\r\n errorMessage = getErrorMessage(error);\r\n }\r\n this.logger.error(errorMessage, error);\r\n throw new Error(errorMessage);\r\n }\r\n \r\n return getResponseWithStructuredContent({\r\n textData,\r\n });\r\n }\r\n}\r\n"],"names":[],"mappings":";;;;;;AASA,MAAM,iBAAiB,EAAE,OAAO;AAAA,EAC9B,aAAa,EAAE,OAAA;AAAA,EACf,OAAO,EAAE,OAAA,EAAS,SAAA;AACpB,CAAC;AAEM,MAAM,qBAAqB,oBAA2C;AAAA,EAW3E,YAAY,QAKT;AACD,UAAM,EAAE,KAAK,QAAQ,GAAG,SAAS;AACjC,UAAM,IAAI;AAjBZ,SAAA,OAAO;AACP,SAAA,cAAc;AAAA;AAAA;AAAA;AAId,SAAA,YAAY;AACZ,SAAA,sBAAsB;AAYpB,SAAK,MAAM;AACX,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,MAAgB,aACZ,OAC8B;AACjC,UAAM,EAAE,aAAa,MAAA,IAAU;AAE9B,QAAI,CAAC,aAAa;AAChB,WAAK,OAAO;AAAA,QACV;AAAA,MAAA;AAGF,YAAM,IAAI,MAAM,0CAA0C;AAAA,IAC5D;AAEA,SAAK,OAAO,KAAK,sDAAsD,WAAW,GAAG;AAErF,QAAI,CAAC,KAAK,OAAO,WAAW;AAC1B,WAAK,OAAO,MAAM,kCAAkC;AAEpD,YAAM,IAAI,MAAM,kCAAkC;AAAA,IACpD;AAGA,QAAI,QAAQ;AACZ,QAAI,MAAM,WAAW,IAAI,GAAG;AAC1B,cAAQ,MAAM,MAAM,CAAC;AAAA,IACvB;AACA,UAAM,cAAc,oBAAoB,KAAK,KAAK;AAElD,QAAI,CAAC,aAAa;AAEhB,YAAM,OAAO,OAAO,WAAW,QAAQ,EAAE,OAAO,WAAW,EAAE,OAAO,KAAK;AACzE,cAAQ;AAAA,IACV;AAGA,UAAM,aAAa,WAAW,KAAK;AAEnC,QAAI,YAAY;AAChB,QAAI,CAAC,WAAW;AACd,YAAM,iBAAiB,WAAW,KAAK,OAAO,SAAS;AACvD,YAAM,SAAS,IAAI,OAAO,cAAc;AACxC,kBAAY,OAAO,mBAAmB,MAAM,CAAC;AAAA,IAC/C,OAAO;AACL,UAAI,UAAU,WAAW,IAAI,GAAG;AAC9B,oBAAY,UAAU,MAAM,CAAC;AAAA,MAC/B;AACA,UAAI,UAAU,WAAW,IAAI;AAC3B,aAAK,OAAO,MAAM,yCAAyC;AAE3D,cAAM,IAAI,MAAM,yCAAyC;AAAA,MAC3D;AAAA,IACF;AAEA,QAAI;AAEJ,QAAI;AACF,YAAM,aAAa,KAAK,IAAI,eAAe,YAAY,SAAS;AAChE,YAAM,eAAe,MAAM,WAAW,gBAAA;AACtC,iBAAW,aAAa,QAAQ,OAAA;AAAA,IAClC,SAAS,OAAO;AACd,UAAI,eAAe;AACnB,UAAI,eAAe,OAAO,kBAAkB,GAAG;AAC7C,uBAAe,gBAAgB,KAAK;AAAA,MACtC;AACA,WAAK,OAAO,MAAM,cAAc,KAAK;AACrC,YAAM,IAAI,MAAM,YAAY;AAAA,IAC9B;AAEA,WAAO,iCAAiC;AAAA,MACtC;AAAA,IAAA,CACD;AAAA,EACH;AACF;"}
@@ -1,124 +1,100 @@
1
- import { MantarayNode } from "@ethersphere/bee-js";
2
- import { z } from "zod";
3
- import fs from "fs";
4
- import path from "path";
5
1
  import { BaseHederaQueryTool } from "hedera-agent-kit";
6
- import { promisify } from "util";
7
- const DownloadFilesSchema = z.object({
8
- reference: z.string(),
9
- filePath: z.string().optional()
2
+ import { z } from "zod";
3
+ import crypto from "crypto";
4
+ import { getUploadPostageBatchId, hexToBytes, errorHasStatus, getErrorMessage, getResponseWithStructuredContent } from "./index62.js";
5
+ import { BAD_REQUEST_STATUS } from "./index63.js";
6
+ import { Wallet } from "@ethereumjs/wallet";
7
+ const UpdateFeedSchema = z.object({
8
+ data: z.string(),
9
+ memoryTopic: z.string(),
10
+ postageBatchId: z.string().optional()
10
11
  });
11
- class DownloadFilesTool extends BaseHederaQueryTool {
12
+ class UpdateFeedTool extends BaseHederaQueryTool {
12
13
  constructor(params) {
13
14
  const { bee, config, ...rest } = params;
14
15
  super(rest);
15
- this.name = "swarm-download-files";
16
- this.description = `Download folder, files from a Swarm reference and save to file path or return file list of the reference.
17
- Prioritizes this tool over swarm-download-data if there is no assumption about the data type.
18
- reference: Swarm reference hash.
19
- filePath: Optional file path to save the downloaded content (only available in stdio mode). If not provided list of files in the manifest will be returned.
20
- `;
16
+ this.name = "swarm-update-feed";
17
+ this.description = `Update the feed of a given topic with new data.
18
+ data: Arbitrary string to upload.
19
+ memoryTopic: If provided, uploads the data to a feed with this topic. It is the label of the memory that can be used later to retrieve the data instead of its content hash. If not a hex string, it will be hashed to create a feed topic.
20
+ postageBatchId: The postage stamp batch ID which will be used to perform the upload, if it is provided.`;
21
21
  this.namespace = "swarm";
22
- this.specificInputSchema = DownloadFilesSchema;
22
+ this.specificInputSchema = UpdateFeedSchema;
23
23
  this.bee = bee;
24
24
  this.config = config;
25
25
  }
26
26
  async executeQuery(input) {
27
- const { reference, filePath } = input;
28
- if (!reference) {
27
+ const { data, memoryTopic, postageBatchId: inputPostageBatchId } = input;
28
+ if (!data) {
29
+ this.logger.error(
30
+ "Missing required parameter: data."
31
+ );
32
+ throw new Error("Missing required parameter: data.");
33
+ } else if (!memoryTopic) {
29
34
  this.logger.error(
30
- "Missing required parameter: reference."
35
+ "Missing required parameter: topic."
31
36
  );
32
- throw new Error("Missing required parameter: reference.");
37
+ throw new Error("Missing required parameter: topic.");
33
38
  }
34
- this.logger.info(`[API] Downloading folder from Swarm with reference: ${reference}.`);
35
- let isManifest = false;
36
- let node;
39
+ let postageBatchId = "";
37
40
  try {
38
- node = await MantarayNode.unmarshal(this.bee, reference);
39
- await node.loadRecursively(this.bee);
40
- isManifest = true;
41
+ postageBatchId = await getUploadPostageBatchId(
42
+ inputPostageBatchId,
43
+ this.bee,
44
+ this.config
45
+ );
41
46
  } catch (error) {
47
+ let errorMessage = "Update feed failed.";
48
+ if (error instanceof Error) {
49
+ errorMessage = error.message;
50
+ }
51
+ this.logger.error(errorMessage);
52
+ throw new Error(errorMessage);
53
+ }
54
+ const binaryData = Buffer.from(data);
55
+ if (!this.config.beeFeedPK) {
56
+ this.logger.error("Feed private key not configured.");
57
+ throw new Error("Feed private key not configured.");
42
58
  }
43
- if (isManifest) {
44
- if (filePath) {
45
- const destinationFolder = filePath;
46
- if (!fs.existsSync(destinationFolder)) {
47
- await promisify(fs.mkdir)(destinationFolder, { recursive: true });
48
- }
49
- const nodes = node.collect();
50
- if (nodes.length === 1) {
51
- const node2 = nodes[0];
52
- const data = await this.bee.downloadData(node2.targetAddress);
53
- await promisify(fs.writeFile)(
54
- path.join(
55
- destinationFolder,
56
- node2.fullPathString.split("\\").slice(-1)[0]
57
- ),
58
- data.toUint8Array()
59
- );
60
- } else {
61
- for (const node2 of nodes) {
62
- const parsedPath = path.parse(node2.fullPathString);
63
- const nodeDestFolder = path.join(destinationFolder, parsedPath.dir);
64
- if (!fs.existsSync(nodeDestFolder)) {
65
- await promisify(fs.mkdir)(nodeDestFolder, { recursive: true });
66
- }
67
- const data = await this.bee.downloadData(node2.targetAddress);
68
- await promisify(fs.writeFile)(
69
- path.join(destinationFolder, node2.fullPathString),
70
- data.toUint8Array()
71
- );
72
- }
73
- }
74
- return {
75
- content: [
76
- {
77
- type: "text",
78
- text: JSON.stringify(
79
- {
80
- reference,
81
- manifestNodeCount: nodes.length,
82
- savedTo: destinationFolder,
83
- message: `Manifest content (${nodes.length} files) successfully downloaded to ${destinationFolder}`
84
- },
85
- null,
86
- 2
87
- )
88
- }
89
- ]
90
- };
91
- } else {
92
- const nodes = node.collect();
93
- const filesList = nodes.map((node2) => ({
94
- path: node2.fullPathString || "/",
95
- targetAddress: Array.from(node2.targetAddress).map((e) => e.toString(16).padStart(2, "0")).join(""),
96
- metadata: node2.metadata
97
- }));
98
- return {
99
- content: [
100
- {
101
- type: "text",
102
- text: JSON.stringify(
103
- {
104
- reference,
105
- type: "manifest",
106
- files: filesList,
107
- message: "This is a manifest with multiple files. Provide a filePath to download all files or download individual files using their specific references."
108
- },
109
- null,
110
- 2
111
- )
112
- }
113
- ]
114
- };
59
+ let topic = memoryTopic;
60
+ if (topic.startsWith("0x")) {
61
+ topic = topic.slice(2);
62
+ }
63
+ const isHexString = /^[0-9a-fA-F]{64}$/.test(memoryTopic);
64
+ if (!isHexString) {
65
+ const hash = crypto.createHash("sha256").update(memoryTopic).digest("hex");
66
+ topic = hash;
67
+ }
68
+ const topicBytes = hexToBytes(topic);
69
+ const feedPrivateKey = hexToBytes(this.config.beeFeedPK);
70
+ const signer = new Wallet(feedPrivateKey);
71
+ const owner = signer.getAddressString().slice(2);
72
+ let result;
73
+ try {
74
+ const feedWriter = this.bee.makeFeedWriter(topicBytes, feedPrivateKey);
75
+ result = await feedWriter.uploadPayload(postageBatchId, binaryData);
76
+ } catch (error) {
77
+ let errorMessage = "Unable to update feed.";
78
+ if (errorHasStatus(error, BAD_REQUEST_STATUS)) {
79
+ errorMessage = getErrorMessage(error);
115
80
  }
116
- } else {
117
- return "Try swarm-download-data tool instead since the given reference is not a manifest.";
81
+ this.logger.error(
82
+ errorMessage,
83
+ error
84
+ );
85
+ throw new Error(errorMessage);
118
86
  }
87
+ const reference = result.reference.toString();
88
+ return getResponseWithStructuredContent({
89
+ reference,
90
+ topicString: memoryTopic,
91
+ topic,
92
+ feedUrl: `${this.bee.url}/feeds/${owner}/${topic}`,
93
+ message: "Data successfully uploaded to Swarm and linked to feed."
94
+ });
119
95
  }
120
96
  }
121
97
  export {
122
- DownloadFilesTool
98
+ UpdateFeedTool
123
99
  };
124
100
  //# sourceMappingURL=index54.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index54.js","sources":["../../src/plugins/community/swarm/tools/DownloadFilesTool.ts"],"sourcesContent":["import { Bee, MantarayNode } from \"@ethersphere/bee-js\";\r\nimport { z } from \"zod\";\r\nimport fs from \"fs\";\r\nimport path from \"path\";\r\nimport { BaseHederaQueryTool, GenericPluginContext, HederaAgentKit } from \"hedera-agent-kit\";\r\nimport { promisify } from \"util\";\r\nimport { ToolResponse } from \"../utils\";\r\nimport { SwarmConfig } from \"../config\";\r\n\r\nconst DownloadFilesSchema = z.object({\r\n reference: z.string(),\r\n filePath: z.string().optional()\r\n});\r\n\r\nexport class DownloadFilesTool extends BaseHederaQueryTool<typeof DownloadFilesSchema> {\r\n name = \"swarm-download-files\";\r\n description = `Download folder, files from a Swarm reference and save to file path or return file list of the reference.\r\n Prioritizes this tool over swarm-download-data if there is no assumption about the data type.\r\n reference: Swarm reference hash.\r\n filePath: Optional file path to save the downloaded content (only available in stdio mode). If not provided list of files in the manifest will be returned.\r\n `;\r\n namespace = \"swarm\";\r\n specificInputSchema = DownloadFilesSchema;\r\n bee: Bee; \r\n config: SwarmConfig;\r\n\r\n constructor(params: {\r\n hederaKit: HederaAgentKit;\r\n config: SwarmConfig;\r\n logger?: GenericPluginContext['logger'];\r\n bee: Bee;\r\n }) {\r\n const { bee, config, ...rest } = params;\r\n super(rest);\r\n this.bee = bee;\r\n this.config = config;\r\n }\r\n\r\n protected async executeQuery(\r\n input: z.infer<typeof DownloadFilesSchema>\r\n ): Promise<ToolResponse | string> {\r\n const { reference, filePath } = input;\r\n \r\n if (!reference) {\r\n this.logger.error(\r\n 'Missing required parameter: reference.'\r\n );\r\n \r\n throw new Error(\"Missing required parameter: reference.\");\r\n }\r\n\r\n this.logger.info(`[API] Downloading folder from Swarm with reference: ${reference}.`);\r\n\r\n // Check if the reference is a manifest\r\n let isManifest = false;\r\n let node: MantarayNode;\r\n\r\n try {\r\n node = await MantarayNode.unmarshal(this.bee, reference);\r\n await node.loadRecursively(this.bee);\r\n isManifest = true;\r\n } catch (error) {\r\n // ignore\r\n }\r\n\r\n if (isManifest) {\r\n if (filePath) {\r\n const destinationFolder = filePath;\r\n\r\n if (!fs.existsSync(destinationFolder)) {\r\n await promisify(fs.mkdir)(destinationFolder, { recursive: true });\r\n }\r\n\r\n const nodes = node!.collect();\r\n\r\n if (nodes.length === 1) {\r\n const node = nodes[0];\r\n const data = await this.bee.downloadData(node.targetAddress);\r\n await promisify(fs.writeFile)(\r\n path.join(\r\n destinationFolder,\r\n node.fullPathString.split(\"\\\\\").slice(-1)[0]\r\n ),\r\n data.toUint8Array()\r\n );\r\n } else {\r\n // Download each node\r\n for (const node of nodes) {\r\n const parsedPath = path.parse(node.fullPathString);\r\n const nodeDestFolder = path.join(destinationFolder, parsedPath.dir);\r\n // Create subdirectories if necessary\r\n if (!fs.existsSync(nodeDestFolder)) {\r\n await promisify(fs.mkdir)(nodeDestFolder, { recursive: true });\r\n }\r\n\r\n const data = await this.bee.downloadData(node.targetAddress);\r\n await promisify(fs.writeFile)(\r\n path.join(destinationFolder, node.fullPathString),\r\n data.toUint8Array()\r\n );\r\n }\r\n }\r\n\r\n return {\r\n content: [\r\n {\r\n type: \"text\",\r\n text: JSON.stringify(\r\n {\r\n reference: reference,\r\n manifestNodeCount: nodes.length,\r\n savedTo: destinationFolder,\r\n message: `Manifest content (${nodes.length} files) successfully downloaded to ${destinationFolder}`,\r\n },\r\n null,\r\n 2\r\n ),\r\n },\r\n ],\r\n };\r\n } else {\r\n // regular file\r\n const nodes = node!.collect();\r\n const filesList = nodes.map((node) => ({\r\n path: node.fullPathString || \"/\",\r\n targetAddress: Array.from(node.targetAddress)\r\n .map((e) => e.toString(16).padStart(2, \"0\"))\r\n .join(\"\"),\r\n metadata: node.metadata,\r\n }));\r\n\r\n return {\r\n content: [\r\n {\r\n type: \"text\",\r\n text: JSON.stringify(\r\n {\r\n reference: reference,\r\n type: \"manifest\",\r\n files: filesList,\r\n message:\r\n \"This is a manifest with multiple files. Provide a filePath to download all files or download individual files using their specific references.\",\r\n },\r\n null,\r\n 2\r\n ),\r\n },\r\n ],\r\n };\r\n }\r\n } else {\r\n return \"Try swarm-download-data tool instead since the given reference is not a manifest.\";\r\n }\r\n }\r\n}\r\n"],"names":["node"],"mappings":";;;;;;AASA,MAAM,sBAAsB,EAAE,OAAO;AAAA,EACnC,WAAW,EAAE,OAAA;AAAA,EACb,UAAU,EAAE,OAAA,EAAS,SAAA;AACvB,CAAC;AAEM,MAAM,0BAA0B,oBAAgD;AAAA,EAYrF,YAAY,QAKT;AACD,UAAM,EAAE,KAAK,QAAQ,GAAG,SAAS;AACjC,UAAM,IAAI;AAlBZ,SAAA,OAAO;AACP,SAAA,cAAc;AAAA;AAAA;AAAA;AAAA;AAKd,SAAA,YAAY;AACZ,SAAA,sBAAsB;AAYpB,SAAK,MAAM;AACX,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,MAAgB,aACZ,OAC8B;AAChC,UAAM,EAAE,WAAW,SAAA,IAAa;AAEhC,QAAI,CAAC,WAAW;AACd,WAAK,OAAO;AAAA,QACV;AAAA,MAAA;AAGF,YAAM,IAAI,MAAM,wCAAwC;AAAA,IAC1D;AAEA,SAAK,OAAO,KAAK,uDAAuD,SAAS,GAAG;AAGpF,QAAI,aAAa;AACjB,QAAI;AAEJ,QAAI;AACF,aAAO,MAAM,aAAa,UAAU,KAAK,KAAK,SAAS;AACvD,YAAM,KAAK,gBAAgB,KAAK,GAAG;AACnC,mBAAa;AAAA,IACf,SAAS,OAAO;AAAA,IAEhB;AAEA,QAAI,YAAY;AACd,UAAI,UAAU;AACZ,cAAM,oBAAoB;AAE1B,YAAI,CAAC,GAAG,WAAW,iBAAiB,GAAG;AACrC,gBAAM,UAAU,GAAG,KAAK,EAAE,mBAAmB,EAAE,WAAW,MAAM;AAAA,QAClE;AAEA,cAAM,QAAQ,KAAM,QAAA;AAEpB,YAAI,MAA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,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAC1C,KAAK,EAAE;AAAA,UACV,UAAUA,MAAK;AAAA,QAAA,EACf;AAEF,eAAO;AAAA,UACL,SAAS;AAAA,YACP;AAAA,cACE,MAAM;AAAA,cACN,MAAM,KAAK;AAAA,gBACT;AAAA,kBACE;AAAA,kBACA,MAAM;AAAA,kBACN,OAAO;AAAA,kBACP,SACE;AAAA,gBAAA;AAAA,gBAEJ;AAAA,gBACA;AAAA,cAAA;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MAEJ;AAAA,IACF,OAAO;AACL,aAAO;AAAA,IACT;AAAA,EACF;AACF;"}
1
+ {"version":3,"file":"index54.js","sources":["../../src/plugins/community/swarm/tools/UpdateFeedTool.ts"],"sourcesContent":["import {\r\n BaseHederaQueryTool,\r\n HederaAgentKit,\r\n type GenericPluginContext,\r\n} from \"hedera-agent-kit\";\r\nimport { Bee } from \"@ethersphere/bee-js\";\r\nimport { z } from \"zod\";\r\nimport crypto from \"crypto\";\r\nimport {\r\n errorHasStatus,\r\n getErrorMessage,\r\n getResponseWithStructuredContent,\r\n getUploadPostageBatchId,\r\n hexToBytes,\r\n ToolResponse,\r\n} from \"../utils\";\r\nimport { BAD_REQUEST_STATUS } from \"../constants\";\r\nimport { Wallet } from \"@ethereumjs/wallet\";\r\nimport { SwarmConfig } from \"../config\";\r\n\r\nconst UpdateFeedSchema = z.object({\r\n data: z.string(),\r\n memoryTopic: z.string(),\r\n postageBatchId: z.string().optional(),\r\n});\r\n\r\nexport class UpdateFeedTool extends BaseHederaQueryTool<typeof UpdateFeedSchema> {\r\n name = \"swarm-update-feed\";\r\n description = `Update the feed of a given topic with new data.\r\n data: Arbitrary string to upload.\r\n memoryTopic: If provided, uploads the data to a feed with this topic. It is the label of the memory that can be used later to retrieve the data instead of its content hash. If not a hex string, it will be hashed to create a feed topic.\r\n postageBatchId: The postage stamp batch ID which will be used to perform the upload, if it is provided.`;\r\n namespace = \"swarm\";\r\n specificInputSchema = UpdateFeedSchema;\r\n bee: Bee;\r\n config: SwarmConfig;\r\n \r\n constructor(params: {\r\n hederaKit: HederaAgentKit;\r\n config: SwarmConfig;\r\n logger?: GenericPluginContext['logger'];\r\n bee: Bee;\r\n }) {\r\n const { bee, config, ...rest } = params;\r\n super(rest);\r\n this.bee = bee;\r\n this.config = config;\r\n }\r\n \r\n protected async executeQuery(\r\n input: z.infer<typeof UpdateFeedSchema>\r\n ): Promise<ToolResponse | string> {\r\n const { data, memoryTopic, postageBatchId: inputPostageBatchId } = input;\r\n if (!data) {\r\n this.logger.error(\r\n 'Missing required parameter: data.'\r\n );\r\n\r\n throw new Error('Missing required parameter: data.');\r\n } else if (!memoryTopic) {\r\n this.logger.error(\r\n 'Missing required parameter: topic.'\r\n );\r\n\r\n throw new Error('Missing required parameter: topic.');\r\n }\r\n \r\n let postageBatchId = \"\";\r\n\r\n try {\r\n postageBatchId = await getUploadPostageBatchId(\r\n inputPostageBatchId,\r\n this.bee,\r\n this.config,\r\n );\r\n } catch (error) {\r\n let errorMessage = 'Update feed failed.';\r\n if (error instanceof Error) {\r\n errorMessage = error.message;\r\n }\r\n this.logger.error(errorMessage);\r\n\r\n throw new Error(errorMessage);\r\n }\r\n\r\n const binaryData = Buffer.from(data);\r\n\r\n // Feed upload if memoryTopic is specified\r\n if (!this.config.beeFeedPK) {\r\n this.logger.error('Feed private key not configured.');\r\n\r\n throw new Error('Feed private key not configured.');\r\n }\r\n\r\n // Process topic - if not a hex string, hash it\r\n let topic = memoryTopic;\r\n if (topic.startsWith(\"0x\")) {\r\n topic = topic.slice(2);\r\n }\r\n const isHexString = /^[0-9a-fA-F]{64}$/.test(memoryTopic);\r\n\r\n if (!isHexString) {\r\n // Hash the topic string using SHA-256\r\n const hash = crypto\r\n .createHash(\"sha256\")\r\n .update(memoryTopic)\r\n .digest(\"hex\");\r\n topic = hash;\r\n }\r\n\r\n // Convert topic string to bytes\r\n const topicBytes = hexToBytes(topic);\r\n\r\n const feedPrivateKey = hexToBytes(this.config.beeFeedPK);\r\n const signer = new Wallet(feedPrivateKey);\r\n const owner = signer.getAddressString().slice(2);\r\n\r\n let result;\r\n\r\n try {\r\n const feedWriter = this.bee.makeFeedWriter(topicBytes, feedPrivateKey);\r\n\r\n result = await feedWriter.uploadPayload(postageBatchId!, binaryData);\r\n } catch (error) {\r\n let errorMessage = 'Unable to update feed.';\r\n\r\n if (errorHasStatus(error, BAD_REQUEST_STATUS)) {\r\n errorMessage = getErrorMessage(error);\r\n }\r\n\r\n this.logger.error(\r\n errorMessage,\r\n error\r\n );\r\n \r\n throw new Error(errorMessage);\r\n }\r\n\r\n const reference = result.reference.toString();\r\n\r\n return getResponseWithStructuredContent({\r\n reference,\r\n topicString: memoryTopic,\r\n topic: topic,\r\n feedUrl: `${this.bee.url}/feeds/${owner}/${topic}`,\r\n message: 'Data successfully uploaded to Swarm and linked to feed.',\r\n });\r\n }\r\n}\r\n"],"names":[],"mappings":";;;;;;AAoBA,MAAM,mBAAmB,EAAE,OAAO;AAAA,EAChC,MAAM,EAAE,OAAA;AAAA,EACR,aAAa,EAAE,OAAA;AAAA,EACf,gBAAgB,EAAE,OAAA,EAAS,SAAA;AAC7B,CAAC;AAEM,MAAM,uBAAuB,oBAA6C;AAAA,EAW/E,YAAY,QAKT;AACD,UAAM,EAAE,KAAK,QAAQ,GAAG,SAAS;AACjC,UAAM,IAAI;AAjBZ,SAAA,OAAO;AACP,SAAA,cAAc;AAAA;AAAA;AAAA;AAId,SAAA,YAAY;AACZ,SAAA,sBAAsB;AAYpB,SAAK,MAAM;AACX,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,MAAgB,aACZ,OAC8B;AAChC,UAAM,EAAE,MAAM,aAAa,gBAAgB,wBAAyB;AACnE,QAAI,CAAC,MAAM;AACV,WAAK,OAAO;AAAA,QACV;AAAA,MAAA;AAGF,YAAM,IAAI,MAAM,mCAAmC;AAAA,IACrD,WAAW,CAAC,aAAa;AACvB,WAAK,OAA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