opc-agent 0.7.0 → 0.8.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.
- package/dist/channels/email.d.ts +69 -0
- package/dist/channels/email.js +118 -0
- package/dist/channels/slack.d.ts +62 -0
- package/dist/channels/slack.js +107 -0
- package/dist/channels/wechat.d.ts +62 -0
- package/dist/channels/wechat.js +104 -0
- package/dist/core/compose.d.ts +35 -0
- package/dist/core/compose.js +49 -0
- package/dist/core/orchestrator.d.ts +68 -0
- package/dist/core/orchestrator.js +145 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +22 -1
- package/dist/tools/calculator.d.ts +7 -0
- package/dist/tools/calculator.js +70 -0
- package/dist/tools/datetime.d.ts +7 -0
- package/dist/tools/datetime.js +159 -0
- package/dist/tools/json-transform.d.ts +7 -0
- package/dist/tools/json-transform.js +184 -0
- package/dist/tools/text-analysis.d.ts +8 -0
- package/dist/tools/text-analysis.js +113 -0
- package/package.json +1 -1
- package/src/channels/email.ts +177 -0
- package/src/channels/slack.ts +160 -0
- package/src/channels/wechat.ts +149 -0
- package/src/core/compose.ts +77 -0
- package/src/core/orchestrator.ts +215 -0
- package/src/index.ts +16 -0
- package/src/tools/calculator.ts +73 -0
- package/src/tools/datetime.ts +149 -0
- package/src/tools/json-transform.ts +187 -0
- package/src/tools/text-analysis.ts +116 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Orchestrator = void 0;
|
|
4
|
+
const events_1 = require("events");
|
|
5
|
+
class Orchestrator extends events_1.EventEmitter {
|
|
6
|
+
agents = new Map();
|
|
7
|
+
workflows = new Map();
|
|
8
|
+
defaultWorkflow;
|
|
9
|
+
maxParallel;
|
|
10
|
+
constructor(config) {
|
|
11
|
+
super();
|
|
12
|
+
this.maxParallel = config.maxParallel ?? 5;
|
|
13
|
+
this.defaultWorkflow = config.defaultWorkflow;
|
|
14
|
+
for (const agent of config.agents) {
|
|
15
|
+
this.agents.set(agent.id, agent);
|
|
16
|
+
}
|
|
17
|
+
for (const wf of config.workflows ?? []) {
|
|
18
|
+
this.workflows.set(wf.name, wf);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** Register a new agent node */
|
|
22
|
+
registerAgent(agent) {
|
|
23
|
+
this.agents.set(agent.id, agent);
|
|
24
|
+
this.emit('agent:registered', agent.id);
|
|
25
|
+
}
|
|
26
|
+
/** Unregister an agent */
|
|
27
|
+
unregisterAgent(id) {
|
|
28
|
+
this.agents.delete(id);
|
|
29
|
+
this.emit('agent:unregistered', id);
|
|
30
|
+
}
|
|
31
|
+
/** Route a message to the best-matching agent */
|
|
32
|
+
route(message) {
|
|
33
|
+
const content = message.content.toLowerCase();
|
|
34
|
+
let bestMatch;
|
|
35
|
+
let bestPriority = -1;
|
|
36
|
+
for (const agent of this.agents.values()) {
|
|
37
|
+
for (const route of agent.routes) {
|
|
38
|
+
if (content.includes(route.toLowerCase()) || new RegExp(route, 'i').test(content)) {
|
|
39
|
+
const priority = agent.priority ?? 0;
|
|
40
|
+
if (priority > bestPriority) {
|
|
41
|
+
bestMatch = agent;
|
|
42
|
+
bestPriority = priority;
|
|
43
|
+
}
|
|
44
|
+
break;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return bestMatch;
|
|
49
|
+
}
|
|
50
|
+
/** Execute a single agent */
|
|
51
|
+
async executeAgent(agentId, context, message) {
|
|
52
|
+
const agent = this.agents.get(agentId);
|
|
53
|
+
if (!agent)
|
|
54
|
+
throw new Error(`Agent not found: ${agentId}`);
|
|
55
|
+
this.emit('agent:execute', agentId, message);
|
|
56
|
+
const result = await agent.handler(context, message);
|
|
57
|
+
this.emit('agent:complete', agentId, result);
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
/** Run multiple agents in parallel */
|
|
61
|
+
async executeParallel(agentIds, context, message) {
|
|
62
|
+
const results = new Map();
|
|
63
|
+
const batches = [];
|
|
64
|
+
// Batch by maxParallel
|
|
65
|
+
for (let i = 0; i < agentIds.length; i += this.maxParallel) {
|
|
66
|
+
batches.push(agentIds.slice(i, i + this.maxParallel));
|
|
67
|
+
}
|
|
68
|
+
for (const batch of batches) {
|
|
69
|
+
const promises = batch.map(async (id) => {
|
|
70
|
+
const result = await this.executeAgent(id, context, message);
|
|
71
|
+
results.set(id, result);
|
|
72
|
+
});
|
|
73
|
+
await Promise.all(promises);
|
|
74
|
+
}
|
|
75
|
+
return results;
|
|
76
|
+
}
|
|
77
|
+
/** Execute a named workflow */
|
|
78
|
+
async executeWorkflow(workflowName, context, message) {
|
|
79
|
+
const wf = this.workflows.get(workflowName);
|
|
80
|
+
if (!wf)
|
|
81
|
+
throw new Error(`Workflow not found: ${workflowName}`);
|
|
82
|
+
const results = [];
|
|
83
|
+
// Sequential steps
|
|
84
|
+
if (wf.steps) {
|
|
85
|
+
let currentMessage = message;
|
|
86
|
+
for (const agentId of wf.steps) {
|
|
87
|
+
const result = await this.executeAgent(agentId, context, currentMessage);
|
|
88
|
+
results.push(result);
|
|
89
|
+
currentMessage = result; // chain output → next input
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
// Parallel execution
|
|
93
|
+
if (wf.parallel) {
|
|
94
|
+
const parallelResults = await this.executeParallel(wf.parallel, context, message);
|
|
95
|
+
results.push(...parallelResults.values());
|
|
96
|
+
}
|
|
97
|
+
// Router-based
|
|
98
|
+
if (wf.router) {
|
|
99
|
+
const matched = this.route(message);
|
|
100
|
+
const targetId = matched && wf.router.agents.includes(matched.id)
|
|
101
|
+
? matched.id
|
|
102
|
+
: wf.router.fallback;
|
|
103
|
+
if (targetId) {
|
|
104
|
+
const result = await this.executeAgent(targetId, context, message);
|
|
105
|
+
results.push(result);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return results;
|
|
109
|
+
}
|
|
110
|
+
/** Hand off conversation from one agent to another */
|
|
111
|
+
async handoff(request) {
|
|
112
|
+
this.emit('agent:handoff', request);
|
|
113
|
+
const { toAgent, context } = request;
|
|
114
|
+
const lastMessage = context.messages[context.messages.length - 1];
|
|
115
|
+
if (!lastMessage)
|
|
116
|
+
throw new Error('No message in context for handoff');
|
|
117
|
+
return this.executeAgent(toAgent, context, lastMessage);
|
|
118
|
+
}
|
|
119
|
+
/** Process an incoming message using the default workflow or routing */
|
|
120
|
+
async process(context, message) {
|
|
121
|
+
if (this.defaultWorkflow) {
|
|
122
|
+
return this.executeWorkflow(this.defaultWorkflow, context, message);
|
|
123
|
+
}
|
|
124
|
+
// Fallback: route to single agent
|
|
125
|
+
const agent = this.route(message);
|
|
126
|
+
if (agent) {
|
|
127
|
+
const result = await this.executeAgent(agent.id, context, message);
|
|
128
|
+
return [result];
|
|
129
|
+
}
|
|
130
|
+
return [{
|
|
131
|
+
id: `orch-${Date.now()}`,
|
|
132
|
+
role: 'assistant',
|
|
133
|
+
content: 'No agent available to handle this request.',
|
|
134
|
+
timestamp: Date.now(),
|
|
135
|
+
}];
|
|
136
|
+
}
|
|
137
|
+
getAgents() {
|
|
138
|
+
return Array.from(this.agents.values());
|
|
139
|
+
}
|
|
140
|
+
getWorkflows() {
|
|
141
|
+
return Array.from(this.workflows.values());
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
exports.Orchestrator = Orchestrator;
|
|
145
|
+
//# sourceMappingURL=orchestrator.js.map
|
package/dist/index.d.ts
CHANGED
|
@@ -49,6 +49,20 @@ export { publishAgent, installAgent } from './marketplace';
|
|
|
49
49
|
export type { AgentManifest, PublishOptions, InstallOptions } from './marketplace';
|
|
50
50
|
export { createAuthMiddleware, getActiveSessions } from './core/auth';
|
|
51
51
|
export type { AuthConfig, AuthSession } from './core/auth';
|
|
52
|
+
export { Orchestrator } from './core/orchestrator';
|
|
53
|
+
export type { AgentNode, OrchestratorWorkflow, OrchestratorConfig, HandoffRequest } from './core/orchestrator';
|
|
54
|
+
export { AgentPipeline, compose } from './core/compose';
|
|
55
|
+
export type { ComposableAgent, ComposeOptions } from './core/compose';
|
|
56
|
+
export { EmailChannel } from './channels/email';
|
|
57
|
+
export type { EmailChannelConfig, EmailMessage } from './channels/email';
|
|
58
|
+
export { SlackChannel } from './channels/slack';
|
|
59
|
+
export type { SlackChannelConfig, SlashCommandConfig, SlashCommandPayload } from './channels/slack';
|
|
60
|
+
export { WeChatChannel } from './channels/wechat';
|
|
61
|
+
export type { WeChatChannelConfig, WeChatMessage, TemplateMessageData } from './channels/wechat';
|
|
62
|
+
export { CalculatorTool } from './tools/calculator';
|
|
63
|
+
export { DateTimeTool } from './tools/datetime';
|
|
64
|
+
export { JsonTransformTool } from './tools/json-transform';
|
|
65
|
+
export { TextAnalysisTool } from './tools/text-analysis';
|
|
52
66
|
export { HttpSkill } from './skills/http';
|
|
53
67
|
export { WebhookTriggerSkill } from './skills/webhook-trigger';
|
|
54
68
|
export type { WebhookTarget } from './skills/webhook-trigger';
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
3
|
+
exports.EmailChannel = exports.compose = exports.AgentPipeline = exports.Orchestrator = exports.getActiveSessions = exports.createAuthMiddleware = exports.installAgent = exports.publishAgent = exports.deployToHermes = exports.KnowledgeBase = exports.addMessages = exports.detectLocale = exports.getLocale = exports.setLocale = exports.t = exports.LazyLoader = exports.RequestBatcher = exports.ConnectionPool = exports.VersionManager = exports.WebhookChannel = exports.VoiceChannel = exports.HITLManager = exports.AgentRegistry = exports.WorkflowEngine = exports.Analytics = exports.Sandbox = exports.PluginManager = exports.createMCPTool = exports.MCPToolRegistry = exports.Room = exports.SUPPORTED_PROVIDERS = exports.createProvider = exports.MRGConfigReader = exports.ValueTracker = exports.TrustManager = exports.DeepBrainMemoryStore = exports.InMemoryStore = exports.SkillRegistry = exports.BaseSkill = exports.WebSocketChannel = exports.TelegramChannel = exports.WebChannel = exports.BaseChannel = exports.OADSchema = exports.validateOAD = exports.loadOAD = exports.Logger = exports.truncateOutput = exports.AgentRuntime = exports.BaseAgent = void 0;
|
|
4
|
+
exports.DocumentSkill = exports.SchedulerSkill = exports.WebhookTriggerSkill = exports.HttpSkill = exports.TextAnalysisTool = exports.JsonTransformTool = exports.DateTimeTool = exports.CalculatorTool = exports.WeChatChannel = exports.SlackChannel = void 0;
|
|
4
5
|
// OPC Agent — Open Agent Framework
|
|
5
6
|
var agent_1 = require("./core/agent");
|
|
6
7
|
Object.defineProperty(exports, "BaseAgent", { enumerable: true, get: function () { return agent_1.BaseAgent; } });
|
|
@@ -86,6 +87,26 @@ Object.defineProperty(exports, "installAgent", { enumerable: true, get: function
|
|
|
86
87
|
var auth_1 = require("./core/auth");
|
|
87
88
|
Object.defineProperty(exports, "createAuthMiddleware", { enumerable: true, get: function () { return auth_1.createAuthMiddleware; } });
|
|
88
89
|
Object.defineProperty(exports, "getActiveSessions", { enumerable: true, get: function () { return auth_1.getActiveSessions; } });
|
|
90
|
+
// v0.8.0 modules
|
|
91
|
+
var orchestrator_1 = require("./core/orchestrator");
|
|
92
|
+
Object.defineProperty(exports, "Orchestrator", { enumerable: true, get: function () { return orchestrator_1.Orchestrator; } });
|
|
93
|
+
var compose_1 = require("./core/compose");
|
|
94
|
+
Object.defineProperty(exports, "AgentPipeline", { enumerable: true, get: function () { return compose_1.AgentPipeline; } });
|
|
95
|
+
Object.defineProperty(exports, "compose", { enumerable: true, get: function () { return compose_1.compose; } });
|
|
96
|
+
var email_1 = require("./channels/email");
|
|
97
|
+
Object.defineProperty(exports, "EmailChannel", { enumerable: true, get: function () { return email_1.EmailChannel; } });
|
|
98
|
+
var slack_1 = require("./channels/slack");
|
|
99
|
+
Object.defineProperty(exports, "SlackChannel", { enumerable: true, get: function () { return slack_1.SlackChannel; } });
|
|
100
|
+
var wechat_1 = require("./channels/wechat");
|
|
101
|
+
Object.defineProperty(exports, "WeChatChannel", { enumerable: true, get: function () { return wechat_1.WeChatChannel; } });
|
|
102
|
+
var calculator_1 = require("./tools/calculator");
|
|
103
|
+
Object.defineProperty(exports, "CalculatorTool", { enumerable: true, get: function () { return calculator_1.CalculatorTool; } });
|
|
104
|
+
var datetime_1 = require("./tools/datetime");
|
|
105
|
+
Object.defineProperty(exports, "DateTimeTool", { enumerable: true, get: function () { return datetime_1.DateTimeTool; } });
|
|
106
|
+
var json_transform_1 = require("./tools/json-transform");
|
|
107
|
+
Object.defineProperty(exports, "JsonTransformTool", { enumerable: true, get: function () { return json_transform_1.JsonTransformTool; } });
|
|
108
|
+
var text_analysis_1 = require("./tools/text-analysis");
|
|
109
|
+
Object.defineProperty(exports, "TextAnalysisTool", { enumerable: true, get: function () { return text_analysis_1.TextAnalysisTool; } });
|
|
89
110
|
var http_1 = require("./skills/http");
|
|
90
111
|
Object.defineProperty(exports, "HttpSkill", { enumerable: true, get: function () { return http_1.HttpSkill; } });
|
|
91
112
|
var webhook_trigger_1 = require("./skills/webhook-trigger");
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CalculatorTool = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Calculator Tool — v0.8.0
|
|
6
|
+
* Safe math expression evaluation as an LLM function tool.
|
|
7
|
+
*/
|
|
8
|
+
exports.CalculatorTool = {
|
|
9
|
+
name: 'calculator',
|
|
10
|
+
description: 'Evaluate a mathematical expression. Supports basic arithmetic, powers, sqrt, abs, min, max, round, ceil, floor, PI, E.',
|
|
11
|
+
inputSchema: {
|
|
12
|
+
type: 'object',
|
|
13
|
+
properties: {
|
|
14
|
+
expression: {
|
|
15
|
+
type: 'string',
|
|
16
|
+
description: 'Mathematical expression to evaluate, e.g. "2 + 3 * 4" or "sqrt(144) + PI"',
|
|
17
|
+
},
|
|
18
|
+
},
|
|
19
|
+
required: ['expression'],
|
|
20
|
+
},
|
|
21
|
+
async execute(input) {
|
|
22
|
+
const expr = String(input.expression ?? '');
|
|
23
|
+
try {
|
|
24
|
+
const result = safeEval(expr);
|
|
25
|
+
return { content: String(result) };
|
|
26
|
+
}
|
|
27
|
+
catch (err) {
|
|
28
|
+
return { content: `Error: ${err.message}`, isError: true };
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
/** Safe math evaluator — no eval(), no arbitrary code */
|
|
33
|
+
function safeEval(expr) {
|
|
34
|
+
// Whitelist: digits, operators, parens, dots, commas, spaces, and known functions
|
|
35
|
+
const sanitized = expr.replace(/\s+/g, '');
|
|
36
|
+
const allowed = /^[0-9+\-*/().,%^a-zA-Z_]+$/;
|
|
37
|
+
if (!allowed.test(sanitized)) {
|
|
38
|
+
throw new Error('Invalid characters in expression');
|
|
39
|
+
}
|
|
40
|
+
// Replace known math functions/constants
|
|
41
|
+
const prepared = sanitized
|
|
42
|
+
.replace(/\bPI\b/gi, String(Math.PI))
|
|
43
|
+
.replace(/\bE\b/g, String(Math.E))
|
|
44
|
+
.replace(/\bsqrt\b/gi, 'Math.sqrt')
|
|
45
|
+
.replace(/\babs\b/gi, 'Math.abs')
|
|
46
|
+
.replace(/\bmin\b/gi, 'Math.min')
|
|
47
|
+
.replace(/\bmax\b/gi, 'Math.max')
|
|
48
|
+
.replace(/\bround\b/gi, 'Math.round')
|
|
49
|
+
.replace(/\bceil\b/gi, 'Math.ceil')
|
|
50
|
+
.replace(/\bfloor\b/gi, 'Math.floor')
|
|
51
|
+
.replace(/\bpow\b/gi, 'Math.pow')
|
|
52
|
+
.replace(/\blog\b/gi, 'Math.log')
|
|
53
|
+
.replace(/\blog10\b/gi, 'Math.log10')
|
|
54
|
+
.replace(/\bsin\b/gi, 'Math.sin')
|
|
55
|
+
.replace(/\bcos\b/gi, 'Math.cos')
|
|
56
|
+
.replace(/\btan\b/gi, 'Math.tan')
|
|
57
|
+
.replace(/\^/g, '**');
|
|
58
|
+
// Block anything that isn't math
|
|
59
|
+
if (/[a-zA-Z_]/.test(prepared.replace(/Math\.\w+/g, ''))) {
|
|
60
|
+
throw new Error('Unsupported function or variable in expression');
|
|
61
|
+
}
|
|
62
|
+
// Use Function constructor with restricted scope
|
|
63
|
+
const fn = new Function('Math', `"use strict"; return (${prepared});`);
|
|
64
|
+
const result = fn(Math);
|
|
65
|
+
if (typeof result !== 'number' || !isFinite(result)) {
|
|
66
|
+
throw new Error('Expression did not evaluate to a finite number');
|
|
67
|
+
}
|
|
68
|
+
return result;
|
|
69
|
+
}
|
|
70
|
+
//# sourceMappingURL=calculator.js.map
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DateTimeTool = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* DateTime Tool — v0.8.0
|
|
6
|
+
* Date/time operations as an LLM function tool.
|
|
7
|
+
*/
|
|
8
|
+
exports.DateTimeTool = {
|
|
9
|
+
name: 'datetime',
|
|
10
|
+
description: 'Get current date/time, format dates, calculate date differences, or add/subtract time.',
|
|
11
|
+
inputSchema: {
|
|
12
|
+
type: 'object',
|
|
13
|
+
properties: {
|
|
14
|
+
operation: {
|
|
15
|
+
type: 'string',
|
|
16
|
+
enum: ['now', 'format', 'diff', 'add', 'parse'],
|
|
17
|
+
description: 'Operation to perform',
|
|
18
|
+
},
|
|
19
|
+
date: {
|
|
20
|
+
type: 'string',
|
|
21
|
+
description: 'Date string (ISO 8601 or common format)',
|
|
22
|
+
},
|
|
23
|
+
date2: {
|
|
24
|
+
type: 'string',
|
|
25
|
+
description: 'Second date for diff operation',
|
|
26
|
+
},
|
|
27
|
+
format: {
|
|
28
|
+
type: 'string',
|
|
29
|
+
description: 'Output format: iso, date, time, datetime, unix, relative',
|
|
30
|
+
},
|
|
31
|
+
amount: {
|
|
32
|
+
type: 'number',
|
|
33
|
+
description: 'Amount to add (can be negative)',
|
|
34
|
+
},
|
|
35
|
+
unit: {
|
|
36
|
+
type: 'string',
|
|
37
|
+
enum: ['milliseconds', 'seconds', 'minutes', 'hours', 'days', 'weeks', 'months', 'years'],
|
|
38
|
+
description: 'Unit for add operation',
|
|
39
|
+
},
|
|
40
|
+
timezone: {
|
|
41
|
+
type: 'string',
|
|
42
|
+
description: 'IANA timezone (e.g. Asia/Shanghai, America/New_York)',
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
required: ['operation'],
|
|
46
|
+
},
|
|
47
|
+
async execute(input) {
|
|
48
|
+
try {
|
|
49
|
+
const op = String(input.operation);
|
|
50
|
+
const tz = input.timezone;
|
|
51
|
+
switch (op) {
|
|
52
|
+
case 'now': {
|
|
53
|
+
const now = new Date();
|
|
54
|
+
const fmt = input.format ?? 'iso';
|
|
55
|
+
return { content: formatDate(now, fmt, tz) };
|
|
56
|
+
}
|
|
57
|
+
case 'format': {
|
|
58
|
+
const d = parseDate(input.date);
|
|
59
|
+
const fmt = input.format ?? 'iso';
|
|
60
|
+
return { content: formatDate(d, fmt, tz) };
|
|
61
|
+
}
|
|
62
|
+
case 'diff': {
|
|
63
|
+
const d1 = parseDate(input.date);
|
|
64
|
+
const d2 = input.date2 ? parseDate(input.date2) : new Date();
|
|
65
|
+
const diffMs = d2.getTime() - d1.getTime();
|
|
66
|
+
const days = Math.floor(Math.abs(diffMs) / 86400000);
|
|
67
|
+
const hours = Math.floor((Math.abs(diffMs) % 86400000) / 3600000);
|
|
68
|
+
const mins = Math.floor((Math.abs(diffMs) % 3600000) / 60000);
|
|
69
|
+
const sign = diffMs < 0 ? '-' : '';
|
|
70
|
+
return {
|
|
71
|
+
content: JSON.stringify({
|
|
72
|
+
milliseconds: diffMs,
|
|
73
|
+
readable: `${sign}${days}d ${hours}h ${mins}m`,
|
|
74
|
+
days: diffMs / 86400000,
|
|
75
|
+
}),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
case 'add': {
|
|
79
|
+
const d = input.date ? parseDate(input.date) : new Date();
|
|
80
|
+
const amount = Number(input.amount ?? 0);
|
|
81
|
+
const unit = String(input.unit ?? 'days');
|
|
82
|
+
const result = addTime(d, amount, unit);
|
|
83
|
+
const fmt = input.format ?? 'iso';
|
|
84
|
+
return { content: formatDate(result, fmt, tz) };
|
|
85
|
+
}
|
|
86
|
+
case 'parse': {
|
|
87
|
+
const d = parseDate(input.date);
|
|
88
|
+
return {
|
|
89
|
+
content: JSON.stringify({
|
|
90
|
+
iso: d.toISOString(),
|
|
91
|
+
unix: d.getTime(),
|
|
92
|
+
year: d.getFullYear(),
|
|
93
|
+
month: d.getMonth() + 1,
|
|
94
|
+
day: d.getDate(),
|
|
95
|
+
weekday: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()],
|
|
96
|
+
}),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
default:
|
|
100
|
+
return { content: `Unknown operation: ${op}`, isError: true };
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
return { content: `Error: ${err.message}`, isError: true };
|
|
105
|
+
}
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
function parseDate(s) {
|
|
109
|
+
const d = new Date(s);
|
|
110
|
+
if (isNaN(d.getTime()))
|
|
111
|
+
throw new Error(`Invalid date: ${s}`);
|
|
112
|
+
return d;
|
|
113
|
+
}
|
|
114
|
+
function formatDate(d, fmt, tz) {
|
|
115
|
+
if (tz) {
|
|
116
|
+
const localeStr = d.toLocaleString('en-US', { timeZone: tz });
|
|
117
|
+
d = new Date(localeStr);
|
|
118
|
+
}
|
|
119
|
+
switch (fmt) {
|
|
120
|
+
case 'iso': return d.toISOString();
|
|
121
|
+
case 'date': return d.toISOString().split('T')[0];
|
|
122
|
+
case 'time': return d.toTimeString().split(' ')[0];
|
|
123
|
+
case 'datetime': return d.toISOString().replace('T', ' ').replace(/\.\d+Z$/, '');
|
|
124
|
+
case 'unix': return String(d.getTime());
|
|
125
|
+
default: return d.toISOString();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function addTime(d, amount, unit) {
|
|
129
|
+
const result = new Date(d);
|
|
130
|
+
switch (unit) {
|
|
131
|
+
case 'milliseconds':
|
|
132
|
+
result.setTime(result.getTime() + amount);
|
|
133
|
+
break;
|
|
134
|
+
case 'seconds':
|
|
135
|
+
result.setTime(result.getTime() + amount * 1000);
|
|
136
|
+
break;
|
|
137
|
+
case 'minutes':
|
|
138
|
+
result.setTime(result.getTime() + amount * 60000);
|
|
139
|
+
break;
|
|
140
|
+
case 'hours':
|
|
141
|
+
result.setTime(result.getTime() + amount * 3600000);
|
|
142
|
+
break;
|
|
143
|
+
case 'days':
|
|
144
|
+
result.setDate(result.getDate() + amount);
|
|
145
|
+
break;
|
|
146
|
+
case 'weeks':
|
|
147
|
+
result.setDate(result.getDate() + amount * 7);
|
|
148
|
+
break;
|
|
149
|
+
case 'months':
|
|
150
|
+
result.setMonth(result.getMonth() + amount);
|
|
151
|
+
break;
|
|
152
|
+
case 'years':
|
|
153
|
+
result.setFullYear(result.getFullYear() + amount);
|
|
154
|
+
break;
|
|
155
|
+
default: throw new Error(`Unknown unit: ${unit}`);
|
|
156
|
+
}
|
|
157
|
+
return result;
|
|
158
|
+
}
|
|
159
|
+
//# sourceMappingURL=datetime.js.map
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.JsonTransformTool = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* JSON Transform Tool — v0.8.0
|
|
6
|
+
* Parse, query, and transform JSON data as an LLM function tool.
|
|
7
|
+
*/
|
|
8
|
+
exports.JsonTransformTool = {
|
|
9
|
+
name: 'json_transform',
|
|
10
|
+
description: 'Parse, query (JSONPath-like), transform, flatten, or merge JSON data.',
|
|
11
|
+
inputSchema: {
|
|
12
|
+
type: 'object',
|
|
13
|
+
properties: {
|
|
14
|
+
operation: {
|
|
15
|
+
type: 'string',
|
|
16
|
+
enum: ['parse', 'query', 'flatten', 'unflatten', 'merge', 'pick', 'omit', 'sort', 'filter', 'map_keys'],
|
|
17
|
+
description: 'Operation to perform on the JSON data',
|
|
18
|
+
},
|
|
19
|
+
data: {
|
|
20
|
+
description: 'JSON string or object to operate on',
|
|
21
|
+
},
|
|
22
|
+
data2: {
|
|
23
|
+
description: 'Second JSON for merge operation',
|
|
24
|
+
},
|
|
25
|
+
path: {
|
|
26
|
+
type: 'string',
|
|
27
|
+
description: 'Dot-notation path for query (e.g. "users.0.name")',
|
|
28
|
+
},
|
|
29
|
+
keys: {
|
|
30
|
+
type: 'array',
|
|
31
|
+
items: { type: 'string' },
|
|
32
|
+
description: 'Keys for pick/omit operations',
|
|
33
|
+
},
|
|
34
|
+
sortBy: {
|
|
35
|
+
type: 'string',
|
|
36
|
+
description: 'Key to sort array by',
|
|
37
|
+
},
|
|
38
|
+
order: {
|
|
39
|
+
type: 'string',
|
|
40
|
+
enum: ['asc', 'desc'],
|
|
41
|
+
},
|
|
42
|
+
filterKey: {
|
|
43
|
+
type: 'string',
|
|
44
|
+
description: 'Key to filter by',
|
|
45
|
+
},
|
|
46
|
+
filterValue: {
|
|
47
|
+
description: 'Value to match for filter',
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
required: ['operation', 'data'],
|
|
51
|
+
},
|
|
52
|
+
async execute(input) {
|
|
53
|
+
try {
|
|
54
|
+
const op = String(input.operation);
|
|
55
|
+
const data = typeof input.data === 'string' ? JSON.parse(input.data) : input.data;
|
|
56
|
+
switch (op) {
|
|
57
|
+
case 'parse':
|
|
58
|
+
return { content: JSON.stringify(data, null, 2) };
|
|
59
|
+
case 'query': {
|
|
60
|
+
const path = String(input.path ?? '');
|
|
61
|
+
const result = getByPath(data, path);
|
|
62
|
+
return { content: JSON.stringify(result, null, 2) };
|
|
63
|
+
}
|
|
64
|
+
case 'flatten':
|
|
65
|
+
return { content: JSON.stringify(flatten(data), null, 2) };
|
|
66
|
+
case 'unflatten':
|
|
67
|
+
return { content: JSON.stringify(unflatten(data), null, 2) };
|
|
68
|
+
case 'merge': {
|
|
69
|
+
const data2 = typeof input.data2 === 'string' ? JSON.parse(input.data2) : input.data2;
|
|
70
|
+
return { content: JSON.stringify(deepMerge(data, data2), null, 2) };
|
|
71
|
+
}
|
|
72
|
+
case 'pick': {
|
|
73
|
+
const keys = input.keys ?? [];
|
|
74
|
+
const result = {};
|
|
75
|
+
for (const k of keys) {
|
|
76
|
+
if (k in data)
|
|
77
|
+
result[k] = data[k];
|
|
78
|
+
}
|
|
79
|
+
return { content: JSON.stringify(result, null, 2) };
|
|
80
|
+
}
|
|
81
|
+
case 'omit': {
|
|
82
|
+
const keys = new Set(input.keys ?? []);
|
|
83
|
+
const result = {};
|
|
84
|
+
for (const [k, v] of Object.entries(data)) {
|
|
85
|
+
if (!keys.has(k))
|
|
86
|
+
result[k] = v;
|
|
87
|
+
}
|
|
88
|
+
return { content: JSON.stringify(result, null, 2) };
|
|
89
|
+
}
|
|
90
|
+
case 'sort': {
|
|
91
|
+
if (!Array.isArray(data))
|
|
92
|
+
return { content: 'Data must be an array for sort', isError: true };
|
|
93
|
+
const sortBy = String(input.sortBy ?? '');
|
|
94
|
+
const order = input.order === 'desc' ? -1 : 1;
|
|
95
|
+
const sorted = [...data].sort((a, b) => {
|
|
96
|
+
const va = sortBy ? a[sortBy] : a;
|
|
97
|
+
const vb = sortBy ? b[sortBy] : b;
|
|
98
|
+
return va < vb ? -order : va > vb ? order : 0;
|
|
99
|
+
});
|
|
100
|
+
return { content: JSON.stringify(sorted, null, 2) };
|
|
101
|
+
}
|
|
102
|
+
case 'filter': {
|
|
103
|
+
if (!Array.isArray(data))
|
|
104
|
+
return { content: 'Data must be an array for filter', isError: true };
|
|
105
|
+
const fk = String(input.filterKey ?? '');
|
|
106
|
+
const fv = input.filterValue;
|
|
107
|
+
const filtered = data.filter((item) => item[fk] === fv);
|
|
108
|
+
return { content: JSON.stringify(filtered, null, 2) };
|
|
109
|
+
}
|
|
110
|
+
case 'map_keys': {
|
|
111
|
+
// Rename keys: path is "old:new,old2:new2"
|
|
112
|
+
const mapping = String(input.path ?? '').split(',').reduce((acc, pair) => {
|
|
113
|
+
const [old, nw] = pair.split(':');
|
|
114
|
+
if (old && nw)
|
|
115
|
+
acc[old.trim()] = nw.trim();
|
|
116
|
+
return acc;
|
|
117
|
+
}, {});
|
|
118
|
+
const result = {};
|
|
119
|
+
for (const [k, v] of Object.entries(data)) {
|
|
120
|
+
result[mapping[k] ?? k] = v;
|
|
121
|
+
}
|
|
122
|
+
return { content: JSON.stringify(result, null, 2) };
|
|
123
|
+
}
|
|
124
|
+
default:
|
|
125
|
+
return { content: `Unknown operation: ${op}`, isError: true };
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
catch (err) {
|
|
129
|
+
return { content: `Error: ${err.message}`, isError: true };
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
function getByPath(obj, path) {
|
|
134
|
+
return path.split('.').reduce((curr, key) => {
|
|
135
|
+
if (curr == null)
|
|
136
|
+
return undefined;
|
|
137
|
+
const idx = Number(key);
|
|
138
|
+
return Number.isInteger(idx) && Array.isArray(curr) ? curr[idx] : curr[key];
|
|
139
|
+
}, obj);
|
|
140
|
+
}
|
|
141
|
+
function flatten(obj, prefix = '') {
|
|
142
|
+
const result = {};
|
|
143
|
+
if (obj && typeof obj === 'object' && !Array.isArray(obj)) {
|
|
144
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
145
|
+
const key = prefix ? `${prefix}.${k}` : k;
|
|
146
|
+
if (v && typeof v === 'object' && !Array.isArray(v)) {
|
|
147
|
+
Object.assign(result, flatten(v, key));
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
result[key] = v;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return result;
|
|
155
|
+
}
|
|
156
|
+
function unflatten(obj) {
|
|
157
|
+
const result = {};
|
|
158
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
159
|
+
const parts = key.split('.');
|
|
160
|
+
let curr = result;
|
|
161
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
162
|
+
if (!(parts[i] in curr))
|
|
163
|
+
curr[parts[i]] = {};
|
|
164
|
+
curr = curr[parts[i]];
|
|
165
|
+
}
|
|
166
|
+
curr[parts[parts.length - 1]] = value;
|
|
167
|
+
}
|
|
168
|
+
return result;
|
|
169
|
+
}
|
|
170
|
+
function deepMerge(a, b) {
|
|
171
|
+
if (!b)
|
|
172
|
+
return a;
|
|
173
|
+
const result = { ...a };
|
|
174
|
+
for (const [k, v] of Object.entries(b)) {
|
|
175
|
+
if (v && typeof v === 'object' && !Array.isArray(v) && result[k] && typeof result[k] === 'object') {
|
|
176
|
+
result[k] = deepMerge(result[k], v);
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
result[k] = v;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return result;
|
|
183
|
+
}
|
|
184
|
+
//# sourceMappingURL=json-transform.js.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { MCPTool } from './mcp';
|
|
2
|
+
/**
|
|
3
|
+
* Text Analysis Tool — v0.8.0
|
|
4
|
+
* Summarize, translate (stub), sentiment analysis as an LLM function tool.
|
|
5
|
+
* Note: For production, connect to actual LLM/NLP APIs. This provides basic built-in analysis.
|
|
6
|
+
*/
|
|
7
|
+
export declare const TextAnalysisTool: MCPTool;
|
|
8
|
+
//# sourceMappingURL=text-analysis.d.ts.map
|