opc-agent 1.4.0 → 2.0.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/CHANGELOG.md +25 -0
- package/README.md +91 -32
- package/dist/channels/telegram.d.ts +30 -9
- package/dist/channels/telegram.js +125 -33
- package/dist/cli.js +415 -8
- package/dist/core/agent.d.ts +23 -0
- package/dist/core/agent.js +120 -3
- package/dist/core/runtime.d.ts +1 -0
- package/dist/core/runtime.js +44 -0
- package/dist/core/scheduler.d.ts +52 -0
- package/dist/core/scheduler.js +168 -0
- package/dist/core/subagent.d.ts +28 -0
- package/dist/core/subagent.js +65 -0
- package/dist/daemon.d.ts +3 -0
- package/dist/daemon.js +134 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +17 -1
- package/dist/providers/index.d.ts +5 -1
- package/dist/providers/index.js +16 -9
- package/dist/schema/oad.d.ts +179 -4
- package/dist/schema/oad.js +12 -1
- package/dist/skills/auto-learn.d.ts +28 -0
- package/dist/skills/auto-learn.js +257 -0
- package/dist/tools/builtin/datetime.d.ts +3 -0
- package/dist/tools/builtin/datetime.js +44 -0
- package/dist/tools/builtin/file.d.ts +3 -0
- package/dist/tools/builtin/file.js +151 -0
- package/dist/tools/builtin/index.d.ts +15 -0
- package/dist/tools/builtin/index.js +30 -0
- package/dist/tools/builtin/shell.d.ts +3 -0
- package/dist/tools/builtin/shell.js +43 -0
- package/dist/tools/builtin/web.d.ts +3 -0
- package/dist/tools/builtin/web.js +37 -0
- package/dist/tools/mcp-client.d.ts +24 -0
- package/dist/tools/mcp-client.js +119 -0
- package/package.json +1 -1
- package/src/channels/telegram.ts +212 -90
- package/src/cli.ts +418 -8
- package/src/core/agent.ts +295 -152
- package/src/core/runtime.ts +47 -0
- package/src/core/scheduler.ts +187 -0
- package/src/core/subagent.ts +98 -0
- package/src/daemon.ts +96 -0
- package/src/index.ts +11 -0
- package/src/providers/index.ts +354 -339
- package/src/schema/oad.ts +167 -154
- package/src/skills/auto-learn.ts +262 -0
- package/src/tools/builtin/datetime.ts +41 -0
- package/src/tools/builtin/file.ts +107 -0
- package/src/tools/builtin/index.ts +28 -0
- package/src/tools/builtin/shell.ts +43 -0
- package/src/tools/builtin/web.ts +35 -0
- package/src/tools/mcp-client.ts +131 -0
- package/tests/auto-learn.test.ts +105 -0
- package/tests/builtin-tools.test.ts +83 -0
- package/tests/cli.test.ts +46 -0
- package/tests/subagent.test.ts +130 -0
- package/tests/telegram-discord.test.ts +60 -0
package/dist/core/agent.js
CHANGED
|
@@ -4,6 +4,9 @@ exports.BaseAgent = void 0;
|
|
|
4
4
|
const events_1 = require("events");
|
|
5
5
|
const memory_1 = require("../memory");
|
|
6
6
|
const providers_1 = require("../providers");
|
|
7
|
+
const auto_learn_1 = require("../skills/auto-learn");
|
|
8
|
+
const mcp_1 = require("../tools/mcp");
|
|
9
|
+
const subagent_1 = require("./subagent");
|
|
7
10
|
class BaseAgent extends events_1.EventEmitter {
|
|
8
11
|
name;
|
|
9
12
|
_state = 'init';
|
|
@@ -13,6 +16,11 @@ class BaseAgent extends events_1.EventEmitter {
|
|
|
13
16
|
_provider;
|
|
14
17
|
systemPrompt;
|
|
15
18
|
historyLimit;
|
|
19
|
+
toolRegistry = new mcp_1.MCPToolRegistry();
|
|
20
|
+
maxToolRounds;
|
|
21
|
+
skillLearner;
|
|
22
|
+
autoLearnConfig;
|
|
23
|
+
_subAgentManager;
|
|
16
24
|
constructor(options) {
|
|
17
25
|
super();
|
|
18
26
|
this.name = options.name;
|
|
@@ -20,6 +28,15 @@ class BaseAgent extends events_1.EventEmitter {
|
|
|
20
28
|
this.memory = options.memory ?? new memory_1.InMemoryStore();
|
|
21
29
|
this._provider = (0, providers_1.createProvider)(options.provider ?? 'openai', options.model);
|
|
22
30
|
this.historyLimit = options.historyLimit ?? 50;
|
|
31
|
+
this.maxToolRounds = options.maxToolRounds ?? 10;
|
|
32
|
+
this.autoLearnConfig = {
|
|
33
|
+
enabled: options.learning?.autoSkillCreation !== false,
|
|
34
|
+
minConversationLength: options.learning?.minConversationLength ?? 3,
|
|
35
|
+
improveOnUse: options.learning?.improveOnUse !== false,
|
|
36
|
+
};
|
|
37
|
+
if (options.skillsDir) {
|
|
38
|
+
this.skillLearner = new auto_learn_1.SkillLearner(options.skillsDir);
|
|
39
|
+
}
|
|
23
40
|
}
|
|
24
41
|
get state() {
|
|
25
42
|
return this._state;
|
|
@@ -33,12 +50,24 @@ class BaseAgent extends events_1.EventEmitter {
|
|
|
33
50
|
getMemory() {
|
|
34
51
|
return this.memory;
|
|
35
52
|
}
|
|
53
|
+
getSkillLearner() {
|
|
54
|
+
return this.skillLearner;
|
|
55
|
+
}
|
|
56
|
+
getToolRegistry() {
|
|
57
|
+
return this.toolRegistry;
|
|
58
|
+
}
|
|
59
|
+
registerTool(tool) {
|
|
60
|
+
this.toolRegistry.register(tool);
|
|
61
|
+
}
|
|
36
62
|
transition(to) {
|
|
37
63
|
const from = this._state;
|
|
38
64
|
this._state = to;
|
|
39
65
|
this.emit('state:change', from, to);
|
|
40
66
|
}
|
|
41
67
|
async init() {
|
|
68
|
+
if (this.skillLearner) {
|
|
69
|
+
await this.skillLearner.loadLearnedSkills();
|
|
70
|
+
}
|
|
42
71
|
this.transition('ready');
|
|
43
72
|
}
|
|
44
73
|
async start() {
|
|
@@ -66,6 +95,18 @@ class BaseAgent extends events_1.EventEmitter {
|
|
|
66
95
|
getChannels() {
|
|
67
96
|
return this.channels;
|
|
68
97
|
}
|
|
98
|
+
getSubAgentManager() {
|
|
99
|
+
if (!this._subAgentManager) {
|
|
100
|
+
this._subAgentManager = new subagent_1.SubAgentManager();
|
|
101
|
+
}
|
|
102
|
+
return this._subAgentManager;
|
|
103
|
+
}
|
|
104
|
+
async spawnSubAgent(config) {
|
|
105
|
+
return this.getSubAgentManager().spawn(config, this._provider);
|
|
106
|
+
}
|
|
107
|
+
async spawnParallel(configs) {
|
|
108
|
+
return this.getSubAgentManager().spawnParallel(configs, this._provider);
|
|
109
|
+
}
|
|
69
110
|
async handleMessage(message) {
|
|
70
111
|
this.emit('message:in', message);
|
|
71
112
|
const sessionId = message.metadata?.sessionId ?? 'default';
|
|
@@ -93,13 +134,89 @@ class BaseAgent extends events_1.EventEmitter {
|
|
|
93
134
|
this.emit('error', err instanceof Error ? err : new Error(String(err)));
|
|
94
135
|
}
|
|
95
136
|
}
|
|
96
|
-
//
|
|
97
|
-
|
|
98
|
-
const
|
|
137
|
+
// Check if a learned skill matches — prepend instructions to system prompt
|
|
138
|
+
let effectiveSystemPrompt = this.systemPrompt;
|
|
139
|
+
const matchedSkill = this.skillLearner?.matchSkill(message.content);
|
|
140
|
+
if (matchedSkill) {
|
|
141
|
+
matchedSkill.usageCount++;
|
|
142
|
+
matchedSkill.lastUsed = new Date();
|
|
143
|
+
effectiveSystemPrompt = `[Learned Skill: ${matchedSkill.name}]\n${matchedSkill.instructions}\n\n${this.systemPrompt}`;
|
|
144
|
+
this.emit('skill:matched', matchedSkill);
|
|
145
|
+
}
|
|
146
|
+
// Fall back to LLM with tool use loop
|
|
147
|
+
const tools = this.toolRegistry.list();
|
|
148
|
+
const llmMessages = [...context.messages];
|
|
149
|
+
let finalResponse = '';
|
|
150
|
+
for (let round = 0; round <= this.maxToolRounds; round++) {
|
|
151
|
+
const llmResponse = await this._provider.chat(llmMessages, effectiveSystemPrompt, { tools: tools.length > 0 ? tools : undefined });
|
|
152
|
+
const toolCall = this.parseToolCall(llmResponse);
|
|
153
|
+
if (!toolCall || tools.length === 0 || round === this.maxToolRounds) {
|
|
154
|
+
finalResponse = llmResponse;
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
// Execute tool
|
|
158
|
+
const toolResult = await this.toolRegistry.execute(toolCall.name, toolCall.arguments, context);
|
|
159
|
+
this.emit('tool:execute', toolCall.name, toolResult);
|
|
160
|
+
// Add tool call and result to messages for next round
|
|
161
|
+
llmMessages.push({
|
|
162
|
+
id: `tool_call_${Date.now()}`,
|
|
163
|
+
role: 'assistant',
|
|
164
|
+
content: llmResponse,
|
|
165
|
+
timestamp: Date.now(),
|
|
166
|
+
});
|
|
167
|
+
llmMessages.push({
|
|
168
|
+
id: `tool_result_${Date.now()}`,
|
|
169
|
+
role: 'user',
|
|
170
|
+
content: `[Tool Result for ${toolCall.name}]: ${toolResult.content}`,
|
|
171
|
+
timestamp: Date.now(),
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
const response = this.createResponse(finalResponse, message);
|
|
99
175
|
await this.memory.addMessage(sessionId, response);
|
|
100
176
|
this.emit('message:out', response);
|
|
177
|
+
// After response, check if we should learn a skill
|
|
178
|
+
if (this.skillLearner &&
|
|
179
|
+
this.autoLearnConfig.enabled &&
|
|
180
|
+
context.messages.length >= this.autoLearnConfig.minConversationLength) {
|
|
181
|
+
this.skillLearner
|
|
182
|
+
.analyzeForSkillCreation(context.messages, this._provider)
|
|
183
|
+
.then(async (learnedSkill) => {
|
|
184
|
+
if (learnedSkill) {
|
|
185
|
+
await this.skillLearner.saveSkill(learnedSkill);
|
|
186
|
+
this.emit('skill:learned', learnedSkill);
|
|
187
|
+
}
|
|
188
|
+
})
|
|
189
|
+
.catch(() => { });
|
|
190
|
+
}
|
|
191
|
+
// Improve matched skill after use
|
|
192
|
+
if (matchedSkill && this.skillLearner && this.autoLearnConfig.improveOnUse) {
|
|
193
|
+
this.skillLearner
|
|
194
|
+
.improveSkill(matchedSkill, context.messages, this._provider)
|
|
195
|
+
.then(() => this.skillLearner.saveSkill(matchedSkill))
|
|
196
|
+
.catch(() => { });
|
|
197
|
+
}
|
|
101
198
|
return response;
|
|
102
199
|
}
|
|
200
|
+
parseToolCall(response) {
|
|
201
|
+
try {
|
|
202
|
+
const parsed = JSON.parse(response);
|
|
203
|
+
if (parsed.tool_call)
|
|
204
|
+
return parsed.tool_call;
|
|
205
|
+
if (parsed.name && parsed.arguments !== undefined)
|
|
206
|
+
return parsed;
|
|
207
|
+
}
|
|
208
|
+
catch { /* not JSON */ }
|
|
209
|
+
const match = response.match(/<tool_call>\s*(\{[\s\S]*?\})\s*<\/tool_call>/);
|
|
210
|
+
if (match) {
|
|
211
|
+
try {
|
|
212
|
+
const parsed = JSON.parse(match[1]);
|
|
213
|
+
if (parsed.name)
|
|
214
|
+
return parsed;
|
|
215
|
+
}
|
|
216
|
+
catch { /* not valid JSON */ }
|
|
217
|
+
}
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
103
220
|
async *handleMessageStream(message) {
|
|
104
221
|
const sessionId = message.metadata?.sessionId ?? 'default';
|
|
105
222
|
await this.memory.addMessage(sessionId, message);
|
package/dist/core/runtime.d.ts
CHANGED
|
@@ -11,6 +11,7 @@ export declare class AgentRuntime {
|
|
|
11
11
|
private shutdownHandlers;
|
|
12
12
|
private isShuttingDown;
|
|
13
13
|
private analytics;
|
|
14
|
+
private scheduler;
|
|
14
15
|
loadConfig(filePath: string): Promise<OADDocument>;
|
|
15
16
|
setHistoryLimit(limit: number): void;
|
|
16
17
|
initialize(config?: OADDocument): Promise<BaseAgent>;
|
package/dist/core/runtime.js
CHANGED
|
@@ -10,6 +10,7 @@ const telegram_1 = require("../channels/telegram");
|
|
|
10
10
|
const websocket_1 = require("../channels/websocket");
|
|
11
11
|
const deepbrain_1 = require("../memory/deepbrain");
|
|
12
12
|
const analytics_1 = require("../analytics");
|
|
13
|
+
const scheduler_1 = require("./scheduler");
|
|
13
14
|
const MAX_TOOL_OUTPUT = 5000;
|
|
14
15
|
const DEFAULT_HISTORY_LIMIT = 50;
|
|
15
16
|
function truncateOutput(output, maxChars = MAX_TOOL_OUTPUT) {
|
|
@@ -26,6 +27,7 @@ class AgentRuntime {
|
|
|
26
27
|
shutdownHandlers = [];
|
|
27
28
|
isShuttingDown = false;
|
|
28
29
|
analytics = new analytics_1.Analytics();
|
|
30
|
+
scheduler = null;
|
|
29
31
|
async loadConfig(filePath) {
|
|
30
32
|
this.config = (0, config_1.loadOAD)(filePath);
|
|
31
33
|
this.logger.info('Config loaded', { name: this.config.metadata.name });
|
|
@@ -116,6 +118,40 @@ class AgentRuntime {
|
|
|
116
118
|
this.analytics.recordError();
|
|
117
119
|
});
|
|
118
120
|
this.logger.info('Agent initialized', { name: cfg.metadata.name });
|
|
121
|
+
// Initialize scheduler if jobs are configured
|
|
122
|
+
const schedulerCfg = cfg.spec.scheduler;
|
|
123
|
+
if (schedulerCfg?.jobs && Array.isArray(schedulerCfg.jobs) && schedulerCfg.jobs.length > 0) {
|
|
124
|
+
this.scheduler = new scheduler_1.Scheduler(async (job) => {
|
|
125
|
+
this.logger.info('Scheduler firing job', { name: job.name, task: job.task });
|
|
126
|
+
if (this.agent) {
|
|
127
|
+
const msg = {
|
|
128
|
+
id: `cron-${job.id}-${Date.now()}`,
|
|
129
|
+
role: 'user',
|
|
130
|
+
content: job.task,
|
|
131
|
+
timestamp: Date.now(),
|
|
132
|
+
metadata: { source: 'scheduler', jobId: job.id, jobName: job.name },
|
|
133
|
+
};
|
|
134
|
+
try {
|
|
135
|
+
await this.agent.handleMessage(msg);
|
|
136
|
+
}
|
|
137
|
+
catch (err) {
|
|
138
|
+
this.logger.error('Scheduler job failed', { name: job.name, error: err instanceof Error ? err.message : String(err) });
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
for (let i = 0; i < schedulerCfg.jobs.length; i++) {
|
|
143
|
+
const j = schedulerCfg.jobs[i];
|
|
144
|
+
const id = j.id || j.name?.toLowerCase().replace(/\s+/g, '-') || `job-${i}`;
|
|
145
|
+
this.scheduler.addJob({
|
|
146
|
+
id,
|
|
147
|
+
name: j.name || id,
|
|
148
|
+
schedule: j.schedule,
|
|
149
|
+
task: j.task || '',
|
|
150
|
+
enabled: j.enabled !== false,
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
this.logger.info('Scheduler configured', { jobs: schedulerCfg.jobs.length });
|
|
154
|
+
}
|
|
119
155
|
return this.agent;
|
|
120
156
|
}
|
|
121
157
|
async start() {
|
|
@@ -123,12 +159,20 @@ class AgentRuntime {
|
|
|
123
159
|
throw new Error('Agent not initialized.');
|
|
124
160
|
this.setupGracefulShutdown();
|
|
125
161
|
await this.agent.start();
|
|
162
|
+
if (this.scheduler) {
|
|
163
|
+
this.scheduler.start();
|
|
164
|
+
this.logger.info('Scheduler started');
|
|
165
|
+
}
|
|
126
166
|
this.logger.info('Agent started');
|
|
127
167
|
}
|
|
128
168
|
async stop() {
|
|
129
169
|
if (!this.agent)
|
|
130
170
|
return;
|
|
131
171
|
this.logger.info('Stopping agent...');
|
|
172
|
+
if (this.scheduler) {
|
|
173
|
+
this.scheduler.stop();
|
|
174
|
+
this.logger.info('Scheduler stopped');
|
|
175
|
+
}
|
|
132
176
|
await this.agent.stop();
|
|
133
177
|
for (const handler of this.shutdownHandlers) {
|
|
134
178
|
await handler();
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Simple cron scheduler — no external dependencies.
|
|
3
|
+
* Supports cron expressions: star, star-slash-N, M-N, M,N for minute/hour/day/month/weekday.
|
|
4
|
+
*/
|
|
5
|
+
export interface CronJob {
|
|
6
|
+
id: string;
|
|
7
|
+
name: string;
|
|
8
|
+
schedule: string;
|
|
9
|
+
task: string;
|
|
10
|
+
enabled: boolean;
|
|
11
|
+
lastRun?: Date;
|
|
12
|
+
nextRun?: Date;
|
|
13
|
+
}
|
|
14
|
+
type CronField = {
|
|
15
|
+
type: 'any';
|
|
16
|
+
} | {
|
|
17
|
+
type: 'every';
|
|
18
|
+
step: number;
|
|
19
|
+
} | {
|
|
20
|
+
type: 'list';
|
|
21
|
+
values: number[];
|
|
22
|
+
};
|
|
23
|
+
interface ParsedCron {
|
|
24
|
+
minute: CronField;
|
|
25
|
+
hour: CronField;
|
|
26
|
+
dayOfMonth: CronField;
|
|
27
|
+
month: CronField;
|
|
28
|
+
dayOfWeek: CronField;
|
|
29
|
+
}
|
|
30
|
+
export declare function parseCron(expr: string): ParsedCron;
|
|
31
|
+
export declare function cronMatches(parsed: ParsedCron, date: Date): boolean;
|
|
32
|
+
export type JobHandler = (job: CronJob) => void | Promise<void>;
|
|
33
|
+
export declare class Scheduler {
|
|
34
|
+
private jobs;
|
|
35
|
+
private parsed;
|
|
36
|
+
private timer;
|
|
37
|
+
private handler;
|
|
38
|
+
constructor(handler: JobHandler);
|
|
39
|
+
addJob(job: CronJob): void;
|
|
40
|
+
removeJob(id: string): void;
|
|
41
|
+
enableJob(id: string): void;
|
|
42
|
+
disableJob(id: string): void;
|
|
43
|
+
getJobs(): CronJob[];
|
|
44
|
+
getJob(id: string): CronJob | undefined;
|
|
45
|
+
/** Run a specific job immediately */
|
|
46
|
+
runJob(id: string): Promise<boolean>;
|
|
47
|
+
start(): void;
|
|
48
|
+
stop(): void;
|
|
49
|
+
private tick;
|
|
50
|
+
}
|
|
51
|
+
export {};
|
|
52
|
+
//# sourceMappingURL=scheduler.d.ts.map
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Simple cron scheduler — no external dependencies.
|
|
4
|
+
* Supports cron expressions: star, star-slash-N, M-N, M,N for minute/hour/day/month/weekday.
|
|
5
|
+
*/
|
|
6
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
+
exports.Scheduler = void 0;
|
|
8
|
+
exports.parseCron = parseCron;
|
|
9
|
+
exports.cronMatches = cronMatches;
|
|
10
|
+
function parseField(field, min, max) {
|
|
11
|
+
if (field === '*')
|
|
12
|
+
return { type: 'any' };
|
|
13
|
+
if (field.startsWith('*/')) {
|
|
14
|
+
const step = parseInt(field.slice(2), 10);
|
|
15
|
+
if (isNaN(step) || step <= 0)
|
|
16
|
+
throw new Error(`Invalid cron step: ${field}`);
|
|
17
|
+
return { type: 'every', step };
|
|
18
|
+
}
|
|
19
|
+
// Could be comma-separated, each part could be a range
|
|
20
|
+
const values = [];
|
|
21
|
+
for (const part of field.split(',')) {
|
|
22
|
+
if (part.includes('-')) {
|
|
23
|
+
const [a, b] = part.split('-').map(Number);
|
|
24
|
+
if (isNaN(a) || isNaN(b))
|
|
25
|
+
throw new Error(`Invalid cron range: ${part}`);
|
|
26
|
+
for (let i = a; i <= b; i++)
|
|
27
|
+
values.push(i);
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
const n = parseInt(part, 10);
|
|
31
|
+
if (isNaN(n))
|
|
32
|
+
throw new Error(`Invalid cron value: ${part}`);
|
|
33
|
+
values.push(n);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return { type: 'list', values };
|
|
37
|
+
}
|
|
38
|
+
function parseCron(expr) {
|
|
39
|
+
const parts = expr.trim().split(/\s+/);
|
|
40
|
+
if (parts.length !== 5)
|
|
41
|
+
throw new Error(`Invalid cron expression (need 5 fields): ${expr}`);
|
|
42
|
+
return {
|
|
43
|
+
minute: parseField(parts[0], 0, 59),
|
|
44
|
+
hour: parseField(parts[1], 0, 23),
|
|
45
|
+
dayOfMonth: parseField(parts[2], 1, 31),
|
|
46
|
+
month: parseField(parts[3], 1, 12),
|
|
47
|
+
dayOfWeek: parseField(parts[4], 0, 6),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function fieldMatches(field, value) {
|
|
51
|
+
switch (field.type) {
|
|
52
|
+
case 'any': return true;
|
|
53
|
+
case 'every': return value % field.step === 0;
|
|
54
|
+
case 'list': return field.values.includes(value);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function cronMatches(parsed, date) {
|
|
58
|
+
return (fieldMatches(parsed.minute, date.getMinutes()) &&
|
|
59
|
+
fieldMatches(parsed.hour, date.getHours()) &&
|
|
60
|
+
fieldMatches(parsed.dayOfMonth, date.getDate()) &&
|
|
61
|
+
fieldMatches(parsed.month, date.getMonth() + 1) &&
|
|
62
|
+
fieldMatches(parsed.dayOfWeek, date.getDay()));
|
|
63
|
+
}
|
|
64
|
+
/** Compute approximate next run (scans forward up to 48h). */
|
|
65
|
+
function computeNextRun(parsed, from) {
|
|
66
|
+
const d = new Date(from);
|
|
67
|
+
d.setSeconds(0, 0);
|
|
68
|
+
d.setMinutes(d.getMinutes() + 1);
|
|
69
|
+
const limit = 48 * 60; // 48 hours in minutes
|
|
70
|
+
for (let i = 0; i < limit; i++) {
|
|
71
|
+
if (cronMatches(parsed, d))
|
|
72
|
+
return new Date(d);
|
|
73
|
+
d.setMinutes(d.getMinutes() + 1);
|
|
74
|
+
}
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
class Scheduler {
|
|
78
|
+
jobs = new Map();
|
|
79
|
+
parsed = new Map();
|
|
80
|
+
timer = null;
|
|
81
|
+
handler;
|
|
82
|
+
constructor(handler) {
|
|
83
|
+
this.handler = handler;
|
|
84
|
+
}
|
|
85
|
+
addJob(job) {
|
|
86
|
+
const p = parseCron(job.schedule);
|
|
87
|
+
this.parsed.set(job.id, p);
|
|
88
|
+
job.nextRun = computeNextRun(p, new Date()) ?? undefined;
|
|
89
|
+
this.jobs.set(job.id, job);
|
|
90
|
+
}
|
|
91
|
+
removeJob(id) {
|
|
92
|
+
this.jobs.delete(id);
|
|
93
|
+
this.parsed.delete(id);
|
|
94
|
+
}
|
|
95
|
+
enableJob(id) {
|
|
96
|
+
const job = this.jobs.get(id);
|
|
97
|
+
if (job)
|
|
98
|
+
job.enabled = true;
|
|
99
|
+
}
|
|
100
|
+
disableJob(id) {
|
|
101
|
+
const job = this.jobs.get(id);
|
|
102
|
+
if (job)
|
|
103
|
+
job.enabled = false;
|
|
104
|
+
}
|
|
105
|
+
getJobs() {
|
|
106
|
+
return Array.from(this.jobs.values());
|
|
107
|
+
}
|
|
108
|
+
getJob(id) {
|
|
109
|
+
return this.jobs.get(id);
|
|
110
|
+
}
|
|
111
|
+
/** Run a specific job immediately */
|
|
112
|
+
async runJob(id) {
|
|
113
|
+
const job = this.jobs.get(id);
|
|
114
|
+
if (!job)
|
|
115
|
+
return false;
|
|
116
|
+
job.lastRun = new Date();
|
|
117
|
+
await this.handler(job);
|
|
118
|
+
const parsed = this.parsed.get(id);
|
|
119
|
+
if (parsed)
|
|
120
|
+
job.nextRun = computeNextRun(parsed, new Date());
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
start() {
|
|
124
|
+
if (this.timer)
|
|
125
|
+
return;
|
|
126
|
+
// Check every 60 seconds
|
|
127
|
+
this.timer = setInterval(() => this.tick(), 60_000);
|
|
128
|
+
// Also tick immediately
|
|
129
|
+
this.tick();
|
|
130
|
+
}
|
|
131
|
+
stop() {
|
|
132
|
+
if (this.timer) {
|
|
133
|
+
clearInterval(this.timer);
|
|
134
|
+
this.timer = null;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
tick() {
|
|
138
|
+
const now = new Date();
|
|
139
|
+
for (const [id, job] of this.jobs) {
|
|
140
|
+
if (!job.enabled)
|
|
141
|
+
continue;
|
|
142
|
+
const parsed = this.parsed.get(id);
|
|
143
|
+
if (!parsed)
|
|
144
|
+
continue;
|
|
145
|
+
if (cronMatches(parsed, now)) {
|
|
146
|
+
// Avoid double-fire: check lastRun isn't same minute
|
|
147
|
+
if (job.lastRun) {
|
|
148
|
+
const last = job.lastRun;
|
|
149
|
+
if (last.getFullYear() === now.getFullYear() &&
|
|
150
|
+
last.getMonth() === now.getMonth() &&
|
|
151
|
+
last.getDate() === now.getDate() &&
|
|
152
|
+
last.getHours() === now.getHours() &&
|
|
153
|
+
last.getMinutes() === now.getMinutes()) {
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
job.lastRun = new Date(now);
|
|
158
|
+
job.nextRun = computeNextRun(parsed, now);
|
|
159
|
+
// Fire and forget (log errors)
|
|
160
|
+
Promise.resolve(this.handler(job)).catch((err) => {
|
|
161
|
+
console.error(`[scheduler] Job "${job.name}" failed:`, err);
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
exports.Scheduler = Scheduler;
|
|
168
|
+
//# sourceMappingURL=scheduler.js.map
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export interface SubAgentConfig {
|
|
2
|
+
name: string;
|
|
3
|
+
task: string;
|
|
4
|
+
systemPrompt?: string;
|
|
5
|
+
provider?: string;
|
|
6
|
+
model?: string;
|
|
7
|
+
timeout?: number;
|
|
8
|
+
isolated?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface SubAgentResult {
|
|
11
|
+
id: string;
|
|
12
|
+
name: string;
|
|
13
|
+
status: 'completed' | 'failed' | 'timeout';
|
|
14
|
+
result: string;
|
|
15
|
+
duration: number;
|
|
16
|
+
}
|
|
17
|
+
export declare class SubAgentManager {
|
|
18
|
+
private agents;
|
|
19
|
+
spawn(config: SubAgentConfig, parentProvider?: any): Promise<SubAgentResult>;
|
|
20
|
+
spawnParallel(configs: SubAgentConfig[], parentProvider?: any): Promise<SubAgentResult[]>;
|
|
21
|
+
list(): Array<{
|
|
22
|
+
id: string;
|
|
23
|
+
name: string;
|
|
24
|
+
status: string;
|
|
25
|
+
}>;
|
|
26
|
+
kill(id: string): boolean;
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=subagent.d.ts.map
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SubAgentManager = void 0;
|
|
4
|
+
const agent_1 = require("./agent");
|
|
5
|
+
const memory_1 = require("../memory");
|
|
6
|
+
class SubAgentManager {
|
|
7
|
+
agents = new Map();
|
|
8
|
+
async spawn(config, parentProvider) {
|
|
9
|
+
const id = `sub_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
|
10
|
+
const timeout = config.timeout ?? 300000;
|
|
11
|
+
const isolated = config.isolated !== false;
|
|
12
|
+
const agent = new agent_1.BaseAgent({
|
|
13
|
+
name: config.name,
|
|
14
|
+
systemPrompt: config.systemPrompt ?? 'You are a helpful sub-agent.',
|
|
15
|
+
provider: config.provider ?? 'openai',
|
|
16
|
+
model: config.model,
|
|
17
|
+
memory: isolated ? new memory_1.InMemoryStore() : undefined,
|
|
18
|
+
});
|
|
19
|
+
this.agents.set(id, { agent, status: 'running', name: config.name });
|
|
20
|
+
const message = {
|
|
21
|
+
id: `msg_${Date.now()}`,
|
|
22
|
+
role: 'user',
|
|
23
|
+
content: config.task,
|
|
24
|
+
timestamp: Date.now(),
|
|
25
|
+
metadata: { subAgentId: id },
|
|
26
|
+
};
|
|
27
|
+
const start = Date.now();
|
|
28
|
+
try {
|
|
29
|
+
const result = await Promise.race([
|
|
30
|
+
agent.handleMessage(message),
|
|
31
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error('SubAgent timeout')), timeout)),
|
|
32
|
+
]);
|
|
33
|
+
const duration = Date.now() - start;
|
|
34
|
+
this.agents.set(id, { agent, status: 'completed', name: config.name });
|
|
35
|
+
return { id, name: config.name, status: 'completed', result: result.content, duration };
|
|
36
|
+
}
|
|
37
|
+
catch (err) {
|
|
38
|
+
const duration = Date.now() - start;
|
|
39
|
+
const isTimeout = err.message.includes('timeout');
|
|
40
|
+
const status = isTimeout ? 'timeout' : 'failed';
|
|
41
|
+
this.agents.set(id, { agent, status, name: config.name });
|
|
42
|
+
return { id, name: config.name, status, result: err.message, duration };
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
async spawnParallel(configs, parentProvider) {
|
|
46
|
+
return Promise.all(configs.map((c) => this.spawn(c, parentProvider)));
|
|
47
|
+
}
|
|
48
|
+
list() {
|
|
49
|
+
return Array.from(this.agents.entries()).map(([id, entry]) => ({
|
|
50
|
+
id,
|
|
51
|
+
name: entry.name,
|
|
52
|
+
status: entry.status,
|
|
53
|
+
}));
|
|
54
|
+
}
|
|
55
|
+
kill(id) {
|
|
56
|
+
const entry = this.agents.get(id);
|
|
57
|
+
if (!entry)
|
|
58
|
+
return false;
|
|
59
|
+
entry.status = 'killed';
|
|
60
|
+
this.agents.set(id, entry);
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
exports.SubAgentManager = SubAgentManager;
|
|
65
|
+
//# sourceMappingURL=subagent.js.map
|
package/dist/daemon.d.ts
ADDED