@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,187 +1,75 @@
1
- import { ZodError } from "zod";
2
- import { Logger } from "@hashgraphonline/standards-sdk";
3
- class ExecutionPipeline {
4
- constructor(toolRegistry, formEngine, memory, logger) {
5
- this.toolRegistry = toolRegistry;
6
- this.formEngine = formEngine;
7
- this.memory = memory;
8
- this.logger = logger || new Logger({ module: "ExecutionPipeline" });
1
+ import { BaseHederaQueryTool } from "hedera-agent-kit";
2
+ import { z } from "zod";
3
+ import { getUploadPostageBatchId, errorHasStatus, getErrorMessage, getResponseWithStructuredContent } from "./index62.js";
4
+ import { BAD_REQUEST_STATUS } from "./index63.js";
5
+ const UploadDataSchema = z.object({
6
+ data: z.string(),
7
+ redundancyLevel: z.number().optional(),
8
+ postageBatchId: z.string().optional()
9
+ });
10
+ class UploadDataTool extends BaseHederaQueryTool {
11
+ constructor(params) {
12
+ const { bee, config, ...rest } = params;
13
+ super(rest);
14
+ this.name = "swarm-upload-data";
15
+ this.description = `
16
+ Upload text data to Swarm.
17
+ data: Arbitrary string to upload.
18
+ redundancyLevel: Redundancy level for fault tolerance: 0 - none, 1 - medium, 2 - strong, 3 - insane, 4 - paranoid (higher values provide better fault tolerance but increase storage overhead). Optional, value is 0 if not requested.
19
+ postageBatchId: The postage stamp batch ID which will be used to perform the upload, if it is provided.
20
+ `;
21
+ this.namespace = "swarm";
22
+ this.specificInputSchema = UploadDataSchema;
23
+ this.bee = bee;
24
+ this.config = config;
9
25
  }
10
- /**
11
- * Execute a tool through the pipeline
12
- */
13
- async execute(toolName, input, sessionContext) {
14
- const traceId = `trace-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
15
- const startTime = Date.now();
16
- const toolEntry = this.toolRegistry.getTool(toolName);
17
- if (!toolEntry) {
18
- throw new Error(`Tool not found in registry: ${toolName}`);
19
- }
20
- const context = {
21
- toolName,
22
- input,
23
- session: sessionContext || this.buildDefaultSession(),
24
- memory: this.memory,
25
- traceId,
26
- toolEntry
27
- };
28
- try {
29
- const shouldGenerateForm = await this.checkFormGeneration(context);
30
- if (shouldGenerateForm.requiresForm && shouldGenerateForm.formMessage) {
31
- return {
32
- success: false,
33
- output: "Form generation required",
34
- requiresForm: true,
35
- formMessage: shouldGenerateForm.formMessage,
36
- traceId,
37
- executionTime: Date.now() - startTime
38
- };
39
- }
40
- const result = await this.executeToolDirect(context);
41
- return {
42
- success: true,
43
- output: result,
44
- traceId,
45
- executionTime: Date.now() - startTime
46
- };
47
- } catch (error) {
48
- return this.handleExecutionError(
49
- error,
50
- context,
51
- traceId,
52
- Date.now() - startTime
26
+ async executeQuery(input) {
27
+ const { data, redundancyLevel, postageBatchId: inputPostageBatchId } = input;
28
+ if (!data) {
29
+ this.logger.error(
30
+ "Missing required parameter: data."
53
31
  );
32
+ throw new Error("Missing required parameter: data.");
54
33
  }
55
- }
56
- /**
57
- * Execute tool with validation
58
- */
59
- async executeWithValidation(toolName, input, sessionContext) {
60
- return this.execute(toolName, input, sessionContext);
61
- }
62
- /**
63
- * Process form submission
64
- */
65
- async processFormSubmission(toolName, formId, parameters, sessionContext) {
66
- const traceId = `form-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
67
- const startTime = Date.now();
34
+ let postageBatchId = "";
68
35
  try {
69
- const formSubmission = {
70
- formId,
71
- toolName,
72
- parameters,
73
- timestamp: Date.now()
74
- };
75
- const processedInput = await this.formEngine.processSubmission(
76
- formSubmission
36
+ postageBatchId = await getUploadPostageBatchId(
37
+ inputPostageBatchId,
38
+ this.bee,
39
+ this.config
77
40
  );
78
- return this.execute(toolName, processedInput, sessionContext);
79
41
  } catch (error) {
80
- return {
81
- success: false,
82
- output: "Form submission processing failed",
83
- error: error instanceof Error ? error.message : String(error),
84
- traceId,
85
- executionTime: Date.now() - startTime
86
- };
87
- }
88
- }
89
- /**
90
- * Check if form generation is required
91
- */
92
- async checkFormGeneration(context) {
93
- const inputRecord = context.input;
94
- if (inputRecord?.__fromForm === true || inputRecord?.renderForm === false) {
95
- return { requiresForm: false };
96
- }
97
- if (!this.formEngine.shouldGenerateForm(context.toolEntry.tool, context.input)) {
98
- return { requiresForm: false };
99
- }
100
- const formMessage = await this.formEngine.generateForm(
101
- context.toolName,
102
- context.toolEntry.tool,
103
- context.input
104
- );
105
- if (formMessage) {
106
- return { requiresForm: true, formMessage };
107
- }
108
- return { requiresForm: false };
109
- }
110
- /**
111
- * Execute tool directly
112
- */
113
- async executeToolDirect(context) {
114
- const { toolEntry, input } = context;
115
- const parameters = input || {};
116
- const mergedArgs = { ...parameters, renderForm: false };
117
- if (toolEntry.wrapper) {
118
- return this.executeWrappedTool(toolEntry, mergedArgs);
119
- }
120
- return await toolEntry.tool.call(mergedArgs);
121
- }
122
- /**
123
- * Execute wrapped tool
124
- */
125
- async executeWrappedTool(toolEntry, mergedArgs) {
126
- const wrapper = toolEntry.wrapper;
127
- if (!wrapper) {
128
- throw new Error("Tool wrapper not found");
129
- }
130
- const wrapperAsAny = wrapper;
131
- if (wrapperAsAny.executeOriginal) {
132
- return await wrapperAsAny.executeOriginal(mergedArgs);
133
- }
134
- if (wrapperAsAny.originalTool?.call) {
135
- return await wrapperAsAny.originalTool.call(mergedArgs);
42
+ let errorMessage = "Upload data failed.";
43
+ if (error instanceof Error) {
44
+ errorMessage = error.message;
45
+ }
46
+ this.logger.error(errorMessage);
47
+ throw new Error(errorMessage);
136
48
  }
137
- return await toolEntry.originalTool.call(mergedArgs);
138
- }
139
- /**
140
- * Handle execution error
141
- */
142
- handleExecutionError(error, context, traceId, executionTime) {
143
- const errorMessage = error instanceof Error ? error.message : String(error);
144
- if (error instanceof ZodError) {
145
- return {
146
- success: false,
147
- output: "Validation error occurred",
148
- error: errorMessage,
149
- traceId,
150
- executionTime
151
- };
49
+ const binaryData = Buffer.from(data);
50
+ const options = redundancyLevel ? { redundancyLevel } : void 0;
51
+ let result;
52
+ try {
53
+ result = await this.bee.uploadData(postageBatchId, binaryData, options);
54
+ } catch (error) {
55
+ let errorMessage = "Unable to upload data.";
56
+ if (errorHasStatus(error, BAD_REQUEST_STATUS)) {
57
+ errorMessage = getErrorMessage(error);
58
+ }
59
+ this.logger.error(
60
+ errorMessage,
61
+ error
62
+ );
63
+ throw new Error(errorMessage);
152
64
  }
153
- this.logger.error(`Tool execution failed: ${context.toolName}`, {
154
- traceId,
155
- error: errorMessage
65
+ return getResponseWithStructuredContent({
66
+ reference: result.reference.toString(),
67
+ url: this.bee.url + "/bytes/" + result.reference.toString(),
68
+ message: "Data successfully uploaded to Swarm"
156
69
  });
157
- return {
158
- success: false,
159
- output: "Tool execution failed",
160
- error: errorMessage,
161
- traceId,
162
- executionTime
163
- };
164
- }
165
- /**
166
- * Build default session context
167
- */
168
- buildDefaultSession() {
169
- return {
170
- sessionId: `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
171
- timestamp: Date.now()
172
- };
173
- }
174
- /**
175
- * Get statistics about the pipeline
176
- */
177
- getStatistics() {
178
- return {
179
- totalMiddleware: 0,
180
- registeredMiddleware: []
181
- };
182
70
  }
183
71
  }
184
72
  export {
185
- ExecutionPipeline
73
+ UploadDataTool
186
74
  };
187
75
  //# sourceMappingURL=index46.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index46.js","sources":["../../src/execution/execution-pipeline.ts"],"sourcesContent":["import { ZodError } from 'zod';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport { SmartMemoryManager } from '../memory/smart-memory-manager';\nimport { FormEngine, ToolExecutionResult } from '../forms/form-engine';\nimport type { FormMessage, FormSubmission } from '../forms/types';\nimport type { ToolRegistry, ToolRegistryEntry } from '../core/tool-registry';\n\n/**\n * Session context for tool execution\n */\nexport interface SessionContext {\n sessionId: string;\n userId?: string;\n timestamp: number;\n conversationId?: string;\n}\n\n/**\n * Context passed through execution pipeline\n */\nexport interface ExecutionContext {\n toolName: string;\n input: unknown;\n session: SessionContext;\n memory: SmartMemoryManager;\n traceId: string;\n toolEntry: ToolRegistryEntry;\n}\n\n/**\n * Result of tool execution with metadata\n */\nexport interface ExecutionResult extends ToolExecutionResult {\n traceId: string;\n executionTime: number;\n}\n\n/**\n * ExecutionPipeline handles tool execution coordination\n */\nexport class ExecutionPipeline {\n private logger: Logger;\n private toolRegistry: ToolRegistry;\n private formEngine: FormEngine;\n private memory: SmartMemoryManager;\n\n constructor(\n toolRegistry: ToolRegistry,\n formEngine: FormEngine,\n memory: SmartMemoryManager,\n logger?: Logger\n ) {\n this.toolRegistry = toolRegistry;\n this.formEngine = formEngine;\n this.memory = memory;\n this.logger = logger || new Logger({ module: 'ExecutionPipeline' });\n }\n\n /**\n * Execute a tool through the pipeline\n */\n async execute(\n toolName: string,\n input: unknown,\n sessionContext?: SessionContext\n ): Promise<ExecutionResult> {\n const traceId = `trace-${Date.now()}-${Math.random()\n .toString(36)\n .substr(2, 9)}`;\n const startTime = Date.now();\n\n const toolEntry = this.toolRegistry.getTool(toolName);\n if (!toolEntry) {\n throw new Error(`Tool not found in registry: ${toolName}`);\n }\n\n const context: ExecutionContext = {\n toolName,\n input,\n session: sessionContext || this.buildDefaultSession(),\n memory: this.memory,\n traceId,\n toolEntry,\n };\n\n try {\n const shouldGenerateForm = await this.checkFormGeneration(context);\n if (shouldGenerateForm.requiresForm && shouldGenerateForm.formMessage) {\n return {\n success: false,\n output: 'Form generation required',\n requiresForm: true,\n formMessage: shouldGenerateForm.formMessage,\n traceId,\n executionTime: Date.now() - startTime,\n };\n }\n\n const result = await this.executeToolDirect(context);\n\n return {\n success: true,\n output: result,\n traceId,\n executionTime: Date.now() - startTime,\n };\n } catch (error) {\n return this.handleExecutionError(\n error,\n context,\n traceId,\n Date.now() - startTime\n );\n }\n }\n\n /**\n * Execute tool with validation\n */\n async executeWithValidation(\n toolName: string,\n input: unknown,\n sessionContext?: SessionContext\n ): Promise<ExecutionResult> {\n return this.execute(toolName, input, sessionContext);\n }\n\n /**\n * Process form submission\n */\n async processFormSubmission(\n toolName: string,\n formId: string,\n parameters: Record<string, unknown>,\n sessionContext?: SessionContext\n ): Promise<ExecutionResult> {\n const traceId = `form-${Date.now()}-${Math.random()\n .toString(36)\n .substr(2, 9)}`;\n const startTime = Date.now();\n\n try {\n const formSubmission: FormSubmission = {\n formId,\n toolName,\n parameters,\n timestamp: Date.now(),\n };\n\n const processedInput = await this.formEngine.processSubmission(\n formSubmission\n );\n\n return this.execute(toolName, processedInput, sessionContext);\n } catch (error) {\n return {\n success: false,\n output: 'Form submission processing failed',\n error: error instanceof Error ? error.message : String(error),\n traceId,\n executionTime: Date.now() - startTime,\n };\n }\n }\n\n /**\n * Check if form generation is required\n */\n private async checkFormGeneration(context: ExecutionContext): Promise<{\n requiresForm: boolean;\n formMessage?: FormMessage;\n }> {\n const inputRecord = context.input as Record<string, unknown>;\n if (inputRecord?.__fromForm === true || inputRecord?.renderForm === false) {\n return { requiresForm: false };\n }\n\n if (\n !this.formEngine.shouldGenerateForm(context.toolEntry.tool, context.input)\n ) {\n return { requiresForm: false };\n }\n\n const formMessage = await this.formEngine.generateForm(\n context.toolName,\n context.toolEntry.tool,\n context.input\n );\n\n if (formMessage) {\n return { requiresForm: true, formMessage };\n }\n\n return { requiresForm: false };\n }\n\n /**\n * Execute tool directly\n */\n private async executeToolDirect(context: ExecutionContext): Promise<string> {\n const { toolEntry, input } = context;\n const parameters = (input as Record<string, unknown>) || {};\n const mergedArgs = { ...parameters, renderForm: false };\n\n if (toolEntry.wrapper) {\n return this.executeWrappedTool(toolEntry, mergedArgs);\n }\n\n return await toolEntry.tool.call(mergedArgs);\n }\n\n /**\n * Execute wrapped tool\n */\n private async executeWrappedTool(\n toolEntry: ToolRegistryEntry,\n mergedArgs: Record<string, unknown>\n ): Promise<string> {\n const wrapper = toolEntry.wrapper;\n if (!wrapper) {\n throw new Error('Tool wrapper not found');\n }\n\n const wrapperAsAny = wrapper as unknown as {\n executeOriginal?: (args: Record<string, unknown>) => Promise<string>;\n originalTool?: {\n call?: (args: Record<string, unknown>) => Promise<string>;\n };\n };\n\n if (wrapperAsAny.executeOriginal) {\n return await wrapperAsAny.executeOriginal(mergedArgs);\n }\n\n if (wrapperAsAny.originalTool?.call) {\n return await wrapperAsAny.originalTool.call(mergedArgs);\n }\n\n return await toolEntry.originalTool.call(mergedArgs);\n }\n\n /**\n * Handle execution error\n */\n private handleExecutionError(\n error: unknown,\n context: ExecutionContext,\n traceId: string,\n executionTime: number\n ): ExecutionResult {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n if (error instanceof ZodError) {\n return {\n success: false,\n output: 'Validation error occurred',\n error: errorMessage,\n traceId,\n executionTime,\n };\n }\n\n this.logger.error(`Tool execution failed: ${context.toolName}`, {\n traceId,\n error: errorMessage,\n });\n\n return {\n success: false,\n output: 'Tool execution failed',\n error: errorMessage,\n traceId,\n executionTime,\n };\n }\n\n /**\n * Build default session context\n */\n private buildDefaultSession(): SessionContext {\n return {\n sessionId: `session-${Date.now()}-${Math.random()\n .toString(36)\n .substr(2, 9)}`,\n timestamp: Date.now(),\n };\n }\n\n /**\n * Get statistics about the pipeline\n */\n getStatistics(): {\n totalMiddleware: number;\n registeredMiddleware: string[];\n } {\n return {\n totalMiddleware: 0,\n registeredMiddleware: [],\n };\n }\n}\n"],"names":[],"mappings":";;AAwCO,MAAM,kBAAkB;AAAA,EAM7B,YACE,cACA,YACA,QACA,QACA;AACA,SAAK,eAAe;AACpB,SAAK,aAAa;AAClB,SAAK,SAAS;AACd,SAAK,SAAS,UAAU,IAAI,OAAO,EAAE,QAAQ,qBAAqB;AAAA,EACpE;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,QACJ,UACA,OACA,gBAC0B;AAC1B,UAAM,UAAU,SAAS,KAAK,IAAA,CAAK,IAAI,KAAK,OAAA,EACzC,SAAS,EAAE,EACX,OAAO,GAAG,CAAC,CAAC;AACf,UAAM,YAAY,KAAK,IAAA;AAEvB,UAAM,YAAY,KAAK,aAAa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AAA,IAC1C;AAEA,UAAM,eAAe;AAOrB,QAAI,aAAa,iBAAiB;AAChC,aAAO,MAAM,aAAa,gBAAgB,UAAU;AAAA,IACtD;AAEA,QAAI,aAAa,cAAc,MAAM;AACnC,aAAO,MAAM,aAAa,aAAa,KAAK,UAAU;AAAA,IACxD;AAEA,WAAO,MAAM,UAAU,aAAa,KAAK,UAAU;AAAA,EACrD;AAAA;AAAA;AAAA;AAAA,EAKQ,qBACN,OACA,SACA,SACA,eACiB;AACjB,UAAM,eAAe,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAE1E,QAAI,iBAAiB,UAAU;AAC7B,aAAO;AAAA,QACL,SAAS;AAAA,QACT,QAAQ;AAAA,QACR,OAAO;AAAA,QACP;AAAA,QACA;AAAA,MAAA;AAAA,IAEJ;AAEA,SAAK,OAAO,MAAM,0BAA0B,QAAQ,QAAQ,IAAI;AAAA,MAC9D;AAAA,MACA,OAAO;AAAA,IAAA,CACR;AAED,WAAO;AAAA,MACL,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,OAAO;AAAA,MACP;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AAAA;AAAA;AAAA;AAAA,EAKQ,sBAAsC;AAC5C,WAAO;AAAA,MACL,WAAW,WAAW,KAAK,IAAA,CAAK,IAAI,KAAK,OAAA,EACtC,SAAS,EAAE,EACX,OAAO,GAAG,CAAC,CAAC;AAAA,MACf,WAAW,KAAK,IAAA;AAAA,IAAI;AAAA,EAExB;AAAA;AAAA;AAAA;AAAA,EAKA,gBAGE;AACA,WAAO;AAAA,MACL,iBAAiB;AAAA,MACjB,sBAAsB,CAAA;AAAA,IAAC;AAAA,EAE3B;AACF;"}
1
+ {"version":3,"file":"index46.js","sources":["../../src/plugins/community/swarm/tools/UploadDataTool.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 {\r\n errorHasStatus,\r\n getErrorMessage,\r\n getResponseWithStructuredContent,\r\n getUploadPostageBatchId,\r\n ToolResponse,\r\n} from \"../utils\";\r\nimport { BAD_REQUEST_STATUS } from \"../constants\";\r\nimport { SwarmConfig } from \"../config\";\r\n\r\nconst UploadDataSchema = z.object({\r\n data: z.string(),\r\n redundancyLevel: z.number().optional(),\r\n postageBatchId: z.string().optional(),\r\n});\r\n\r\nexport class UploadDataTool extends BaseHederaQueryTool<typeof UploadDataSchema> {\r\n name = \"swarm-upload-data\";\r\n description = `\r\n Upload text data to Swarm.\r\n data: Arbitrary string to upload.\r\n redundancyLevel: Redundancy level for fault tolerance: 0 - none, 1 - medium, 2 - strong, 3 - insane, 4 - paranoid (higher values provide better fault tolerance but increase storage overhead). Optional, value is 0 if not requested.\r\n postageBatchId: The postage stamp batch ID which will be used to perform the upload, if it is provided.\r\n `;\r\n namespace = \"swarm\";\r\n specificInputSchema = UploadDataSchema;\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 UploadDataSchema>\r\n ): Promise<ToolResponse | string> {\r\n const { data, redundancyLevel, postageBatchId: inputPostageBatchId } = input;\r\n\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 }\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 = 'Upload data 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 const options = redundancyLevel ? { redundancyLevel } : undefined;\r\n\r\n let result;\r\n\r\n try {\r\n result = await this.bee.uploadData(postageBatchId, binaryData, options);\r\n } catch (error) {\r\n let errorMessage = 'Unable to upload data.';\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 return getResponseWithStructuredContent({\r\n reference: result.reference.toString(),\r\n url: this.bee.url + \"/bytes/\" + result.reference.toString(),\r\n message: 'Data successfully uploaded to Swarm',\r\n });\r\n }\r\n}\r\n"],"names":[],"mappings":";;;;AAiBA,MAAM,mBAAmB,EAAE,OAAO;AAAA,EAChC,MAAM,EAAE,OAAA;AAAA,EACR,iBAAiB,EAAE,OAAA,EAAS,SAAA;AAAA,EAC5B,gBAAgB,EAAE,OAAA,EAAS,SAAA;AAC7B,CAAC;AAEM,MAAM,uBAAuB,oBAA6C;AAAA,EAa/E,YAAY,QAKT;AACD,UAAM,EAAE,KAAK,QAAQ,GAAG,SAAS;AACjC,UAAM,IAAI;AAnBZ,SAAA,OAAO;AACP,SAAA,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAMd,SAAA,YAAY;AACZ,SAAA,sBAAsB;AAYpB,SAAK,MAAM;AACX,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,MAAgB,aACZ,OAC8B;AAChC,UAAM,EAAE,MAAM,iBAAiB,gBAAgB,wBAAwB;AAEvE,QAAI,CAAC,MAAM;AACT,WAAK,OAAO;AAAA,QACV;AAAA,MAAA;AAGF,YAAM,IAAI,MAAM,mCAAmC;AAAA,IACrD;AAEA,QAAI,iBAAiB;AAErB,QAAI;AACF,uBAAiB,MAAM;AAAA,QACrB;AAAA,QACA,KAAK;AAAA,QACL,KAAK;AAAA,MAAA;AAAA,IAET,SAAS,OAAO;AACd,UAAI,eAAe;AACnB,UAAI,iBAAiB,OAAO;AAC1B,uBAAe,MAAM;AAAA,MACvB;AACA,WAAK,OAAO,MAAM,YAAY;AAE9B,YAAM,IAAI,MAAM,YAAY;AAAA,IAC9B;AAEA,UAAM,aAAa,OAAO,KAAK,IAAI;AAEnC,UAAM,UAAU,kBAAkB,EAAE,gBAAA,IAAoB;AAExD,QAAI;AAEJ,QAAI;AACF,eAAS,MAAM,KAAK,IAAI,WAAW,gBAAgB,YAAY,OAAO;AAAA,IACxE,SAAS,OAAO;AACd,UAAI,eAAe;AAEnB,UAAI,eAAe,OAAO,kBAAkB,GAAG;AAC7C,uBAAe,gBAAgB,KAAK;AAAA,MACtC;AAEA,WAAK,OAAO;AAAA,QACV;AAAA,QACA;AAAA,MAAA;AAGF,YAAM,IAAI,MAAM,YAAY;AAAA,IAC9B;AAEA,WAAO,iCAAiC;AAAA,MACpC,WAAW,OAAO,UAAU,SAAA;AAAA,MAC5B,KAAK,KAAK,IAAI,MAAM,YAAY,OAAO,UAAU,SAAA;AAAA,MACjD,SAAS;AAAA,IAAA,CACV;AAAA,EACL;AACF;"}
@@ -1,10 +1,57 @@
1
- const FIELD_PRIORITIES = {
2
- ESSENTIAL: "essential",
3
- COMMON: "common",
4
- ADVANCED: "advanced",
5
- EXPERT: "expert"
6
- };
1
+ import { z } from "zod";
2
+ import { errorHasStatus, getErrorMessage, getResponseWithStructuredContent } from "./index62.js";
3
+ import { BaseHederaQueryTool } from "hedera-agent-kit";
4
+ import { BAD_REQUEST_STATUS } from "./index63.js";
5
+ const DownloadDataSchema = z.object({
6
+ reference: z.string()
7
+ });
8
+ class DownloadDataTool extends BaseHederaQueryTool {
9
+ constructor(params) {
10
+ const { bee, config, ...rest } = params;
11
+ super(rest);
12
+ this.name = "swarm-download-data";
13
+ this.description = `
14
+ Downloads immutable data from a Swarm content address hash.
15
+ reference: Swarm reference hash.
16
+ `;
17
+ this.namespace = "swarm";
18
+ this.specificInputSchema = DownloadDataSchema;
19
+ this.bee = bee;
20
+ this.config = config;
21
+ }
22
+ async executeQuery(input) {
23
+ const { reference } = input;
24
+ if (!reference) {
25
+ this.logger.error(
26
+ "Missing required parameter: reference."
27
+ );
28
+ throw new Error("Missing required parameter: reference.");
29
+ }
30
+ const isRefNotSwarmHash = reference.length !== 64 && reference.length !== 66;
31
+ if (isRefNotSwarmHash) {
32
+ this.logger.error(
33
+ "Invalid Swarm content address hash value for reference."
34
+ );
35
+ throw new Error("Invalid Swarm content address hash value for reference.");
36
+ }
37
+ let data;
38
+ try {
39
+ data = await this.bee.downloadData(reference);
40
+ } catch (error) {
41
+ let errorMessage = "Downloading data failed.";
42
+ if (errorHasStatus(error, BAD_REQUEST_STATUS)) {
43
+ errorMessage = getErrorMessage(error);
44
+ }
45
+ this.logger.error(errorMessage, error);
46
+ throw new Error(errorMessage);
47
+ }
48
+ const textData = data.toUtf8();
49
+ return getResponseWithStructuredContent({
50
+ textData
51
+ });
52
+ }
53
+ }
7
54
  export {
8
- FIELD_PRIORITIES
55
+ DownloadDataTool
9
56
  };
10
57
  //# sourceMappingURL=index47.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index47.js","sources":["../../src/constants/form-priorities.ts"],"sourcesContent":["/**\n * Form field priorities for progressive disclosure\n */\nexport const FIELD_PRIORITIES = {\n ESSENTIAL: 'essential',\n COMMON: 'common', \n ADVANCED: 'advanced',\n EXPERT: 'expert'\n} as const;\n\n/**\n * Form field types\n */\nexport const FORM_FIELD_TYPES = {\n TEXT: 'text',\n NUMBER: 'number',\n SELECT: 'select',\n CHECKBOX: 'checkbox',\n TEXTAREA: 'textarea',\n FILE: 'file',\n ARRAY: 'array',\n OBJECT: 'object',\n CURRENCY: 'currency',\n PERCENTAGE: 'percentage',\n} as const;"],"names":[],"mappings":"AAGO,MAAM,mBAAmB;AAAA,EAC9B,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,QAAQ;AACV;"}
1
+ {"version":3,"file":"index47.js","sources":["../../src/plugins/community/swarm/tools/DownloadDataTool.ts"],"sourcesContent":["import { Bee } from \"@ethersphere/bee-js\";\r\nimport { z } from \"zod\";\r\nimport { errorHasStatus, getErrorMessage, getResponseWithStructuredContent, 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 DownloadDataSchema = z.object({\r\n reference: z.string(),\r\n});\r\n\r\nexport class DownloadDataTool extends BaseHederaQueryTool<typeof DownloadDataSchema> {\r\n name = \"swarm-download-data\";\r\n description = `\r\n Downloads immutable data from a Swarm content address hash.\r\n reference: Swarm reference hash.\r\n `;\r\n namespace = \"swarm\";\r\n specificInputSchema = DownloadDataSchema;\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 DownloadDataSchema>\r\n ): Promise<ToolResponse | string> {\r\n const { reference } = 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 const isRefNotSwarmHash =\r\n reference.length !== 64 && reference.length !== 66;\r\n\r\n if (isRefNotSwarmHash) {\r\n this.logger.error(\r\n 'Invalid Swarm content address hash value for reference.'\r\n );\r\n\r\n throw new Error(\"Invalid Swarm content address hash value for reference.\");\r\n }\r\n\r\n let data;\r\n try {\r\n data = await this.bee.downloadData(reference);\r\n } catch (error) {\r\n let errorMessage = 'Downloading data failed.';\r\n\r\n if (errorHasStatus(error, BAD_REQUEST_STATUS)) {\r\n errorMessage = getErrorMessage(error);\r\n }\r\n\r\n this.logger.error(errorMessage, error);\r\n throw new Error(errorMessage);\r\n }\r\n\r\n const textData = data.toUtf8();\r\n\r\n return getResponseWithStructuredContent({\r\n textData,\r\n });\r\n }\r\n}\r\n"],"names":[],"mappings":";;;;AAOA,MAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,WAAW,EAAE,OAAA;AACf,CAAC;AAEM,MAAM,yBAAyB,oBAA+C;AAAA,EAWnF,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,cAAc;AAEtB,QAAI,CAAC,WAAW;AACd,WAAK,OAAO;AAAA,QACV;AAAA,MAAA;AAGF,YAAM,IAAI,MAAM,wCAAwC;AAAA,IAC1D;AAEA,UAAM,oBACJ,UAAU,WAAW,MAAM,UAAU,WAAW;AAElD,QAAI,mBAAmB;AACrB,WAAK,OAAO;AAAA,QACV;AAAA,MAAA;AAGF,YAAM,IAAI,MAAM,yDAAyD;AAAA,IAC3E;AAEA,QAAI;AACJ,QAAI;AACF,aAAO,MAAM,KAAK,IAAI,aAAa,SAAS;AAAA,IAC9C,SAAS,OAAO;AACd,UAAI,eAAe;AAEnB,UAAI,eAAe,OAAO,kBAAkB,GAAG;AAC7C,uBAAe,gBAAgB,KAAK;AAAA,MACtC;AAEA,WAAK,OAAO,MAAM,cAAc,KAAK;AACrC,YAAM,IAAI,MAAM,YAAY;AAAA,IAC9B;AAEA,UAAM,WAAW,KAAK,OAAA;AAEtB,WAAO,iCAAiC;AAAA,MACtC;AAAA,IAAA,CACD;AAAA,EACH;AACF;"}
@@ -1,39 +1,85 @@
1
1
  import { BaseHederaQueryTool } from "hedera-agent-kit";
2
+ import { Size, Duration } from "@ethersphere/bee-js";
2
3
  import { z } from "zod";
3
- import { errorHasStatus, getBatchSummary, getResponseWithStructuredContent } from "./index62.js";
4
- import { NOT_FOUND_STATUS, GATEWAY_STAMP_ERROR_MESSAGE } from "./index63.js";
5
- const ListPostageStampsSchema = z.object({
6
- leastUsed: z.boolean().optional(),
7
- limit: z.number().optional(),
8
- minUsage: z.number().optional(),
9
- maxUsage: z.number().optional()
4
+ import { makeDate, runWithTimeout, errorHasStatus, getErrorMessage } from "./index62.js";
5
+ import { CALL_TIMEOUT, POSTAGE_CREATE_TIMEOUT_MESSAGE, GATEWAY_STAMP_ERROR_MESSAGE, NOT_FOUND_STATUS, BAD_REQUEST_STATUS } from "./index63.js";
6
+ const CreatePostageStampSchema = z.object({
7
+ size: z.number(),
8
+ duration: z.string(),
9
+ label: z.string().optional()
10
10
  });
11
- class ListPostageStampsTool extends BaseHederaQueryTool {
11
+ class CreatePostageStampTool extends BaseHederaQueryTool {
12
12
  constructor(params) {
13
13
  const { bee, config, ...rest } = params;
14
14
  super(rest);
15
- this.name = "swarm-list-postage-stamps";
15
+ this.name = "swarm-create-postage-stamp";
16
16
  this.description = `
17
- List the available postage stamps.
18
- leastUsed: A boolean value that tells if stamps are sorted so least used comes first.
19
- limit: Limit is the maximum number of returned stamps.
20
- minUsage: Only list stamps with at least this usage percentage.
21
- maxUsage: Only list stamps with at most this usage percentage.
17
+ Buy postage stamp based on size in megabytes and duration.
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.
20
+ label: Sets label for the postage batch (omit if the user didn't ask for one). Do not set a label with with specific capacity values because they can get misleading.
22
21
  `;
23
22
  this.namespace = "swarm";
24
- this.specificInputSchema = ListPostageStampsSchema;
23
+ this.specificInputSchema = CreatePostageStampSchema;
25
24
  this.bee = bee;
26
25
  this.config = config;
27
26
  }
28
27
  async executeQuery(input) {
29
- const { leastUsed, limit, minUsage, maxUsage } = input;
30
- let rawPostageBatches;
28
+ const { size, duration, label } = input;
29
+ if (!size) {
30
+ this.logger.error(
31
+ "Missing required parameter: size."
32
+ );
33
+ throw new Error("Missing required parameter: size.");
34
+ } else if (!duration) {
35
+ this.logger.error(
36
+ "Missing required parameter: duration."
37
+ );
38
+ throw new Error("Missing required parameter: duration.");
39
+ }
40
+ let durationMs;
31
41
  try {
32
- rawPostageBatches = await this.bee.getPostageBatches();
42
+ durationMs = makeDate(duration);
43
+ } catch (makeDateError) {
44
+ this.logger.error(
45
+ "Invalid parameter: duration."
46
+ );
47
+ throw new Error("Invalid parameter: duration.");
48
+ }
49
+ let buyStorageResponse;
50
+ try {
51
+ let options = {};
52
+ if (label !== void 0) {
53
+ options = {
54
+ label
55
+ };
56
+ }
57
+ const buyStoragePromise = this.bee.buyStorage(
58
+ Size.fromMegabytes(size),
59
+ Duration.fromMilliseconds(durationMs),
60
+ options
61
+ );
62
+ const [response, hasTimedOut] = await runWithTimeout(
63
+ buyStoragePromise,
64
+ CALL_TIMEOUT
65
+ );
66
+ if (hasTimedOut) {
67
+ return JSON.stringify({
68
+ content: [
69
+ {
70
+ type: "text",
71
+ text: POSTAGE_CREATE_TIMEOUT_MESSAGE
72
+ }
73
+ ]
74
+ });
75
+ }
76
+ buyStorageResponse = response;
33
77
  } catch (error) {
34
- let errorMessage = "Retrieval of postage batches failed.";
78
+ let errorMessage = "Unable to buy storage.";
35
79
  if (errorHasStatus(error, NOT_FOUND_STATUS)) {
36
80
  errorMessage = GATEWAY_STAMP_ERROR_MESSAGE;
81
+ } else if (errorHasStatus(error, BAD_REQUEST_STATUS)) {
82
+ errorMessage = getErrorMessage(error);
37
83
  }
38
84
  this.logger.error(
39
85
  errorMessage,
@@ -41,40 +87,17 @@ class ListPostageStampsTool extends BaseHederaQueryTool {
41
87
  );
42
88
  throw new Error(errorMessage);
43
89
  }
44
- const batches = rawPostageBatches.map((batch) => ({
45
- ...batch,
46
- batchID: batch.batchID.toHex()
47
- }));
48
- let filteredPostageBatches = batches.filter((batch) => {
49
- if (!batch.usable) {
50
- return false;
51
- }
52
- const usagePercentage = batch.usage * 100;
53
- if (minUsage !== void 0 && usagePercentage < minUsage) {
54
- return false;
55
- }
56
- if (maxUsage !== void 0 && usagePercentage > maxUsage) {
57
- return false;
58
- }
59
- return true;
60
- });
61
- if (Boolean(leastUsed) && filteredPostageBatches.length) {
62
- filteredPostageBatches = filteredPostageBatches.sort(
63
- (batch1, batch2) => batch1.usage - batch2.usage
64
- );
65
- }
66
- if (limit !== void 0 && limit < filteredPostageBatches.length) {
67
- filteredPostageBatches = filteredPostageBatches.slice(0, limit);
68
- }
69
- const computedPostageBatches = filteredPostageBatches.map((batch) => getBatchSummary(batch));
70
- const content = {
71
- raw: filteredPostageBatches,
72
- summary: computedPostageBatches
90
+ return {
91
+ content: [
92
+ {
93
+ type: "text",
94
+ text: `Postage batch ID: ${buyStorageResponse.toHex()}`
95
+ }
96
+ ]
73
97
  };
74
- return getResponseWithStructuredContent(content);
75
98
  }
76
99
  }
77
100
  export {
78
- ListPostageStampsTool
101
+ CreatePostageStampTool
79
102
  };
80
103
  //# sourceMappingURL=index48.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index48.js","sources":["../../src/plugins/community/swarm/tools/ListPostageStampsTool.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 ListPostageStampsSchema = z.object({\r\n leastUsed: z.boolean().optional(),\r\n limit: z.number().optional(),\r\n minUsage: z.number().optional(),\r\n maxUsage: z.number().optional(),\r\n});\r\n\r\nexport class ListPostageStampsTool extends BaseHederaQueryTool<typeof ListPostageStampsSchema> {\r\n name = \"swarm-list-postage-stamps\";\r\n description =`\r\n List the available postage stamps.\r\n leastUsed: A boolean value that tells if stamps are sorted so least used comes first.\r\n limit: Limit is the maximum number of returned stamps.\r\n minUsage: Only list stamps with at least this usage percentage.\r\n maxUsage: Only list stamps with at most this usage percentage. \r\n `;\r\n namespace = \"swarm\";\r\n specificInputSchema = ListPostageStampsSchema;\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 ListPostageStampsSchema>\r\n ): Promise<ToolResponse | string> {\r\n const { leastUsed, limit, minUsage, maxUsage } = input;\r\n\r\n let rawPostageBatches;\r\n\r\n try {\r\n rawPostageBatches = await this.bee.getPostageBatches();\r\n } catch (error) {\r\n let errorMessage = 'Retrieval of postage batches 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 batches: PostageBatchCurated[] = rawPostageBatches.map((batch) => ({\r\n ...batch,\r\n batchID: batch.batchID.toHex(),\r\n }));\r\n let filteredPostageBatches = batches.filter((batch) => {\r\n if (!batch.usable) {\r\n return false;\r\n }\r\n\r\n const usagePercentage = batch.usage * 100;\r\n\r\n if (minUsage !== undefined && usagePercentage < minUsage) {\r\n return false;\r\n }\r\n\r\n if (maxUsage !== undefined && usagePercentage > maxUsage) {\r\n return false;\r\n }\r\n\r\n return true;\r\n });\r\n\r\n if (Boolean(leastUsed) && filteredPostageBatches.length) {\r\n filteredPostageBatches = filteredPostageBatches.sort(\r\n (batch1, batch2) => batch1.usage - batch2.usage\r\n );\r\n }\r\n\r\n if (limit !== undefined && limit < filteredPostageBatches.length) {\r\n filteredPostageBatches = filteredPostageBatches.slice(0, limit);\r\n }\r\n\r\n const computedPostageBatches: PostageBatchSummary[] =\r\n filteredPostageBatches.map((batch) => getBatchSummary(batch));\r\n\r\n const content: ResponseContent<\r\n PostageBatchCurated[],\r\n PostageBatchSummary[]\r\n > = {\r\n raw: filteredPostageBatches,\r\n summary: computedPostageBatches,\r\n };\r\n\r\n return getResponseWithStructuredContent(content);\r\n }\r\n}\r\n"],"names":[],"mappings":";;;;AAqBA,MAAM,0BAA0B,EAAE,OAAO;AAAA,EACvC,WAAW,EAAE,QAAA,EAAU,SAAA;AAAA,EACvB,OAAO,EAAE,OAAA,EAAS,SAAA;AAAA,EAClB,UAAU,EAAE,OAAA,EAAS,SAAA;AAAA,EACrB,UAAU,EAAE,OAAA,EAAS,SAAA;AACvB,CAAC;AAEM,MAAM,8BAA8B,oBAAoD;AAAA,EAc7F,YAAY,QAKT;AACD,UAAM,EAAE,KAAK,QAAQ,GAAG,SAAS;AACjC,UAAM,IAAI;AApBZ,SAAA,OAAO;AACP,SAAA,cAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOb,SAAA,YAAY;AACZ,SAAA,sBAAsB;AAYpB,SAAK,MAAM;AACX,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,MAAgB,aACZ,OAC8B;AAChC,UAAM,EAAE,WAAW,OAAO,UAAU,aAAa;AAEjD,QAAI;AAEJ,QAAI;AACF,0BAAoB,MAAM,KAAK,IAAI,kBAAA;AAAA,IACrC,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,UAAiC,kBAAkB,IAAI,CAAC,WAAW;AAAA,MACvE,GAAG;AAAA,MACH,SAAS,MAAM,QAAQ,MAAA;AAAA,IAAM,EAC7B;AACF,QAAI,yBAAyB,QAAQ,OAAO,CAAC,UAAU;AACrD,UAAI,CAAC,MAAM,QAAQ;AACjB,eAAO;AAAA,MACT;AAEA,YAAM,kBAAkB,MAAM,QAAQ;AAEtC,UAAI,aAAa,UAAa,kBAAkB,UAAU;AACxD,eAAO;AAAA,MACT;AAEA,UAAI,aAAa,UAAa,kBAAkB,UAAU;AACxD,eAAO;AAAA,MACT;AAEA,aAAO;AAAA,IACT,CAAC;AAED,QAAI,QAAQ,SAAS,KAAK,uBAAuB,QAAQ;AACvD,+BAAyB,uBAAuB;AAAA,QAC9C,CAAC,QAAQ,WAAW,OAAO,QAAQ,OAAO;AAAA,MAAA;AAAA,IAE9C;AAEA,QAAI,UAAU,UAAa,QAAQ,uBAAuB,QAAQ;AAChE,+BAAyB,uBAAuB,MAAM,GAAG,KAAK;AAAA,IAChE;AAEA,UAAM,yBACJ,uBAAuB,IAAI,CAAC,UAAU,gBAAgB,KAAK,CAAC;AAE9D,UAAM,UAGF;AAAA,MACF,KAAK;AAAA,MACL,SAAS;AAAA,IAAA;AAGX,WAAO,iCAAiC,OAAO;AAAA,EACjD;AACF;"}
1
+ {"version":3,"file":"index48.js","sources":["../../src/plugins/community/swarm/tools/CreatePostageStampTool.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 makeDate,\r\n runWithTimeout,\r\n ToolResponse,\r\n} from \"../utils\";\r\nimport { BAD_REQUEST_STATUS, CALL_TIMEOUT, GATEWAY_STAMP_ERROR_MESSAGE, NOT_FOUND_STATUS, POSTAGE_CREATE_TIMEOUT_MESSAGE } from \"../constants\";\r\nimport { SwarmConfig } from \"../config\";\r\n\r\nconst CreatePostageStampSchema = z.object({\r\n size: z.number(),\r\n duration: z.string(),\r\n label: z.string().optional(),\r\n});\r\n\r\nexport class CreatePostageStampTool extends BaseHederaQueryTool<typeof CreatePostageStampSchema> {\r\n name = \"swarm-create-postage-stamp\";\r\n description = `\r\n Buy postage stamp based on size in megabytes and duration.\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 label: Sets label for the postage batch (omit if the user didn't ask for one). Do not set a label with with specific capacity values because they can get misleading.\r\n `;\r\n namespace = \"swarm\";\r\n specificInputSchema = CreatePostageStampSchema;\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 CreatePostageStampSchema>\r\n ): Promise<ToolResponse | string> {\r\n const { size, duration, label } = input;\r\n\r\n if (!size) {\r\n this.logger.error(\r\n 'Missing required parameter: size.'\r\n );\r\n \r\n throw new Error('Missing required parameter: size.');\r\n } else if (!duration) {\r\n this.logger.error(\r\n 'Missing required parameter: duration.'\r\n );\r\n \r\n throw new Error('Missing required parameter: duration.');\r\n }\r\n\r\n let durationMs;\r\n\r\n try {\r\n durationMs = makeDate(duration);\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 buyStorageResponse: BatchId;\r\n\r\n try {\r\n let options = {};\r\n if (label !== undefined) {\r\n options = {\r\n label\r\n };\r\n }\r\n const buyStoragePromise = this.bee.buyStorage(\r\n Size.fromMegabytes(size),\r\n Duration.fromMilliseconds(durationMs),\r\n options\r\n );\r\n const [response, hasTimedOut] = await runWithTimeout(\r\n buyStoragePromise,\r\n CALL_TIMEOUT\r\n );\r\n\r\n if (hasTimedOut) {\r\n return JSON.stringify({\r\n content: [\r\n {\r\n type: 'text',\r\n text: POSTAGE_CREATE_TIMEOUT_MESSAGE,\r\n },\r\n ],\r\n });\r\n }\r\n\r\n buyStorageResponse = response as BatchId;\r\n } catch (error) {\r\n let errorMessage = 'Unable to buy storage.';\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 {\r\n content: [\r\n {\r\n type: 'text',\r\n text: `Postage batch ID: ${buyStorageResponse.toHex()}`,\r\n },\r\n ],\r\n };\r\n }\r\n}\r\n"],"names":[],"mappings":";;;;;AAiBA,MAAM,2BAA2B,EAAE,OAAO;AAAA,EACxC,MAAM,EAAE,OAAA;AAAA,EACR,UAAU,EAAE,OAAA;AAAA,EACZ,OAAO,EAAE,OAAA,EAAS,SAAA;AACpB,CAAC;AAEM,MAAM,+BAA+B,oBAAqD;AAAA,EAa/F,YAAY,QAKT;AACD,UAAM,EAAE,KAAK,QAAQ,GAAG,SAAS;AACjC,UAAM,IAAI;AAnBZ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