musonda 1.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/IMPLEMENTATION.md +432 -0
- package/README.md +119 -0
- package/dist/agent/harness.d.ts +25 -0
- package/dist/agent/harness.js +215 -0
- package/dist/agent/harness.js.map +1 -0
- package/dist/agent/openaiResponsesClient.d.ts +35 -0
- package/dist/agent/openaiResponsesClient.js +250 -0
- package/dist/agent/openaiResponsesClient.js.map +1 -0
- package/dist/agent/systemPrompt.d.ts +9 -0
- package/dist/agent/systemPrompt.js +100 -0
- package/dist/agent/systemPrompt.js.map +1 -0
- package/dist/agent/types.d.ts +53 -0
- package/dist/agent/types.js +2 -0
- package/dist/agent/types.js.map +1 -0
- package/dist/cli/commands/chat.d.ts +6 -0
- package/dist/cli/commands/chat.js +8 -0
- package/dist/cli/commands/chat.js.map +1 -0
- package/dist/cli/commands/doctor.d.ts +4 -0
- package/dist/cli/commands/doctor.js +336 -0
- package/dist/cli/commands/doctor.js.map +1 -0
- package/dist/cli/commands/gateway.d.ts +20 -0
- package/dist/cli/commands/gateway.js +135 -0
- package/dist/cli/commands/gateway.js.map +1 -0
- package/dist/cli/commands/help.d.ts +4 -0
- package/dist/cli/commands/help.js +159 -0
- package/dist/cli/commands/help.js.map +1 -0
- package/dist/cli/commands/plugins.d.ts +18 -0
- package/dist/cli/commands/plugins.js +250 -0
- package/dist/cli/commands/plugins.js.map +1 -0
- package/dist/cli/commands/service.d.ts +16 -0
- package/dist/cli/commands/service.js +136 -0
- package/dist/cli/commands/service.js.map +1 -0
- package/dist/cli/commands/setup.d.ts +4 -0
- package/dist/cli/commands/setup.js +8 -0
- package/dist/cli/commands/setup.js.map +1 -0
- package/dist/cli/commands/status.d.ts +4 -0
- package/dist/cli/commands/status.js +73 -0
- package/dist/cli/commands/status.js.map +1 -0
- package/dist/cli/commands/update.d.ts +22 -0
- package/dist/cli/commands/update.js +226 -0
- package/dist/cli/commands/update.js.map +1 -0
- package/dist/cli/daemon.d.ts +33 -0
- package/dist/cli/daemon.js +208 -0
- package/dist/cli/daemon.js.map +1 -0
- package/dist/cli/interactiveMenu.d.ts +5 -0
- package/dist/cli/interactiveMenu.js +225 -0
- package/dist/cli/interactiveMenu.js.map +1 -0
- package/dist/cli/musondaCli.d.ts +30 -0
- package/dist/cli/musondaCli.js +269 -0
- package/dist/cli/musondaCli.js.map +1 -0
- package/dist/cli/ui.d.ts +49 -0
- package/dist/cli/ui.js +90 -0
- package/dist/cli/ui.js.map +1 -0
- package/dist/cli.d.ts +9 -0
- package/dist/cli.js +315 -0
- package/dist/cli.js.map +1 -0
- package/dist/config/loader.d.ts +12 -0
- package/dist/config/loader.js +217 -0
- package/dist/config/loader.js.map +1 -0
- package/dist/config/paths.d.ts +11 -0
- package/dist/config/paths.js +18 -0
- package/dist/config/paths.js.map +1 -0
- package/dist/config/types.d.ts +246 -0
- package/dist/config/types.js +155 -0
- package/dist/config/types.js.map +1 -0
- package/dist/gateway/channels/cli.d.ts +37 -0
- package/dist/gateway/channels/cli.js +298 -0
- package/dist/gateway/channels/cli.js.map +1 -0
- package/dist/gateway/channels/discord.d.ts +18 -0
- package/dist/gateway/channels/discord.js +419 -0
- package/dist/gateway/channels/discord.js.map +1 -0
- package/dist/gateway/channels/slack.d.ts +26 -0
- package/dist/gateway/channels/slack.js +470 -0
- package/dist/gateway/channels/slack.js.map +1 -0
- package/dist/gateway/channels/webhook.d.ts +18 -0
- package/dist/gateway/channels/webhook.js +49 -0
- package/dist/gateway/channels/webhook.js.map +1 -0
- package/dist/gateway/http.d.ts +33 -0
- package/dist/gateway/http.js +605 -0
- package/dist/gateway/http.js.map +1 -0
- package/dist/gateway/server.d.ts +38 -0
- package/dist/gateway/server.js +233 -0
- package/dist/gateway/server.js.map +1 -0
- package/dist/gateway/types.d.ts +28 -0
- package/dist/gateway/types.js +2 -0
- package/dist/gateway/types.js.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +32 -0
- package/dist/index.js.map +1 -0
- package/dist/memory/memoryManager.d.ts +22 -0
- package/dist/memory/memoryManager.js +200 -0
- package/dist/memory/memoryManager.js.map +1 -0
- package/dist/memory/storage.d.ts +24 -0
- package/dist/memory/storage.js +187 -0
- package/dist/memory/storage.js.map +1 -0
- package/dist/memory/types.d.ts +43 -0
- package/dist/memory/types.js +2 -0
- package/dist/memory/types.js.map +1 -0
- package/dist/plugins/manifest.d.ts +23 -0
- package/dist/plugins/manifest.js +185 -0
- package/dist/plugins/manifest.js.map +1 -0
- package/dist/plugins/mcp/mcpBridge.d.ts +31 -0
- package/dist/plugins/mcp/mcpBridge.js +115 -0
- package/dist/plugins/mcp/mcpBridge.js.map +1 -0
- package/dist/plugins/mcp/mcpClient.d.ts +43 -0
- package/dist/plugins/mcp/mcpClient.js +309 -0
- package/dist/plugins/mcp/mcpClient.js.map +1 -0
- package/dist/plugins/mcp/mcpConfig.d.ts +34 -0
- package/dist/plugins/mcp/mcpConfig.js +326 -0
- package/dist/plugins/mcp/mcpConfig.js.map +1 -0
- package/dist/plugins/mcp/types.d.ts +48 -0
- package/dist/plugins/mcp/types.js +2 -0
- package/dist/plugins/mcp/types.js.map +1 -0
- package/dist/plugins/pluginManager.d.ts +164 -0
- package/dist/plugins/pluginManager.js +1016 -0
- package/dist/plugins/pluginManager.js.map +1 -0
- package/dist/plugins/skills/frontmatterParser.d.ts +28 -0
- package/dist/plugins/skills/frontmatterParser.js +189 -0
- package/dist/plugins/skills/frontmatterParser.js.map +1 -0
- package/dist/plugins/skills/skillDiscovery.d.ts +15 -0
- package/dist/plugins/skills/skillDiscovery.js +148 -0
- package/dist/plugins/skills/skillDiscovery.js.map +1 -0
- package/dist/plugins/skills/skillTools.d.ts +8 -0
- package/dist/plugins/skills/skillTools.js +195 -0
- package/dist/plugins/skills/skillTools.js.map +1 -0
- package/dist/plugins/skills/types.d.ts +25 -0
- package/dist/plugins/skills/types.js +2 -0
- package/dist/plugins/skills/types.js.map +1 -0
- package/dist/plugins/types.d.ts +30 -0
- package/dist/plugins/types.js +2 -0
- package/dist/plugins/types.js.map +1 -0
- package/dist/scheduler/scheduler.d.ts +25 -0
- package/dist/scheduler/scheduler.js +239 -0
- package/dist/scheduler/scheduler.js.map +1 -0
- package/dist/scheduler/types.d.ts +39 -0
- package/dist/scheduler/types.js +2 -0
- package/dist/scheduler/types.js.map +1 -0
- package/dist/security/childProcessEnv.d.ts +5 -0
- package/dist/security/childProcessEnv.js +42 -0
- package/dist/security/childProcessEnv.js.map +1 -0
- package/dist/security/fileSandbox.d.ts +153 -0
- package/dist/security/fileSandbox.js +779 -0
- package/dist/security/fileSandbox.js.map +1 -0
- package/dist/service/index.d.ts +30 -0
- package/dist/service/index.js +41 -0
- package/dist/service/index.js.map +1 -0
- package/dist/service/systemd.d.ts +36 -0
- package/dist/service/systemd.js +409 -0
- package/dist/service/systemd.js.map +1 -0
- package/dist/service/types.d.ts +118 -0
- package/dist/service/types.js +6 -0
- package/dist/service/types.js.map +1 -0
- package/dist/tools/builtin/calcTools.d.ts +2 -0
- package/dist/tools/builtin/calcTools.js +51 -0
- package/dist/tools/builtin/calcTools.js.map +1 -0
- package/dist/tools/builtin/fileTools.d.ts +11 -0
- package/dist/tools/builtin/fileTools.js +352 -0
- package/dist/tools/builtin/fileTools.js.map +1 -0
- package/dist/tools/builtin/memoryTools.d.ts +4 -0
- package/dist/tools/builtin/memoryTools.js +123 -0
- package/dist/tools/builtin/memoryTools.js.map +1 -0
- package/dist/tools/builtin/noteTools.d.ts +4 -0
- package/dist/tools/builtin/noteTools.js +91 -0
- package/dist/tools/builtin/noteTools.js.map +1 -0
- package/dist/tools/builtin/pluginTools.d.ts +29 -0
- package/dist/tools/builtin/pluginTools.js +406 -0
- package/dist/tools/builtin/pluginTools.js.map +1 -0
- package/dist/tools/builtin/scheduleTools.d.ts +4 -0
- package/dist/tools/builtin/scheduleTools.js +156 -0
- package/dist/tools/builtin/scheduleTools.js.map +1 -0
- package/dist/tools/builtin/timeTools.d.ts +2 -0
- package/dist/tools/builtin/timeTools.js +41 -0
- package/dist/tools/builtin/timeTools.js.map +1 -0
- package/dist/tools/builtin/webTools.d.ts +12 -0
- package/dist/tools/builtin/webTools.js +325 -0
- package/dist/tools/builtin/webTools.js.map +1 -0
- package/dist/tools/registry.d.ts +15 -0
- package/dist/tools/registry.js +111 -0
- package/dist/tools/registry.js.map +1 -0
- package/dist/tools/types.d.ts +41 -0
- package/dist/tools/types.js +2 -0
- package/dist/tools/types.js.map +1 -0
- package/dist/utils/logger.d.ts +29 -0
- package/dist/utils/logger.js +124 -0
- package/dist/utils/logger.js.map +1 -0
- package/dist/wizard/onboarding.d.ts +3 -0
- package/dist/wizard/onboarding.js +408 -0
- package/dist/wizard/onboarding.js.map +1 -0
- package/package.json +69 -0
- package/plugins/example-calc/mcp.json +11 -0
- package/plugins/example-calc/plugin.json +12 -0
- package/plugins/example-calc/server.mjs +92 -0
- package/plugins/example-calc/skills/math-assistant/SKILL.md +15 -0
- package/plugins/plugin-builder/plugin.json +12 -0
- package/plugins/plugin-builder/skills/create-plugin/SKILL.md +149 -0
- package/plugins/plugin-builder/skills/manage-plugins/SKILL.md +157 -0
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { SystemPromptBuilder } from './systemPrompt.js';
|
|
2
|
+
import { logger } from '../utils/logger.js';
|
|
3
|
+
export class AgentHarness {
|
|
4
|
+
config;
|
|
5
|
+
memory;
|
|
6
|
+
tools;
|
|
7
|
+
client;
|
|
8
|
+
maxToolIterations = 8;
|
|
9
|
+
scheduler;
|
|
10
|
+
pluginManager;
|
|
11
|
+
constructor(config, memory, tools, client, scheduler, pluginManager) {
|
|
12
|
+
this.config = config;
|
|
13
|
+
this.memory = memory;
|
|
14
|
+
this.tools = tools;
|
|
15
|
+
this.client = client;
|
|
16
|
+
this.scheduler = scheduler;
|
|
17
|
+
this.pluginManager = pluginManager;
|
|
18
|
+
}
|
|
19
|
+
setScheduler(scheduler) {
|
|
20
|
+
this.scheduler = scheduler;
|
|
21
|
+
}
|
|
22
|
+
getScheduler() {
|
|
23
|
+
return this.scheduler;
|
|
24
|
+
}
|
|
25
|
+
setPluginManager(pluginManager) {
|
|
26
|
+
this.pluginManager = pluginManager;
|
|
27
|
+
}
|
|
28
|
+
getPluginManager() {
|
|
29
|
+
return this.pluginManager;
|
|
30
|
+
}
|
|
31
|
+
getMemoryManager() {
|
|
32
|
+
return this.memory;
|
|
33
|
+
}
|
|
34
|
+
getToolRegistry() {
|
|
35
|
+
return this.tools;
|
|
36
|
+
}
|
|
37
|
+
getClient() {
|
|
38
|
+
return this.client;
|
|
39
|
+
}
|
|
40
|
+
formatToolStatus(name) {
|
|
41
|
+
const lower = name.toLowerCase();
|
|
42
|
+
if (lower.includes('search') || lower.includes('google') || lower.includes('bing')) {
|
|
43
|
+
return 'Searching the web…';
|
|
44
|
+
}
|
|
45
|
+
return `Running \`${name}\`…`;
|
|
46
|
+
}
|
|
47
|
+
formatToolReviewStatus(name, output) {
|
|
48
|
+
const lower = name.toLowerCase();
|
|
49
|
+
if (lower.includes('search')) {
|
|
50
|
+
try {
|
|
51
|
+
const parsed = JSON.parse(output);
|
|
52
|
+
if (Array.isArray(parsed)) {
|
|
53
|
+
return `Reviewing ${parsed.length} results…`;
|
|
54
|
+
}
|
|
55
|
+
if (parsed && Array.isArray(parsed.results)) {
|
|
56
|
+
return `Reviewing ${parsed.results.length} results…`;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
catch { }
|
|
60
|
+
return 'Reviewing results…';
|
|
61
|
+
}
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
async processMessage(input) {
|
|
65
|
+
const { sessionId, channel, channelId, userId, userName, threadTs, messageText, scheduler } = input;
|
|
66
|
+
const activeScheduler = scheduler || this.scheduler;
|
|
67
|
+
const assistantName = this.config.assistant.customName || this.config.assistant.name || 'Musonda';
|
|
68
|
+
logger.agent(`Processing message from ${userName || userId} on [${channel}]: "${messageText.substring(0, 60)}${messageText.length > 60 ? '...' : ''}"`);
|
|
69
|
+
const emitEvent = async (event) => {
|
|
70
|
+
if (input.onEvent) {
|
|
71
|
+
try {
|
|
72
|
+
await input.onEvent(event);
|
|
73
|
+
}
|
|
74
|
+
catch (cbErr) {
|
|
75
|
+
logger.debug('Error in onEvent callback:', cbErr);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (event.type === 'output.delta' && input.onStreamDelta) {
|
|
79
|
+
try {
|
|
80
|
+
await input.onStreamDelta(event.text);
|
|
81
|
+
}
|
|
82
|
+
catch (cbErr) {
|
|
83
|
+
logger.debug('Error in onStreamDelta callback:', cbErr);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
try {
|
|
88
|
+
await emitEvent({ type: 'run.started' });
|
|
89
|
+
await emitEvent({ type: 'status', text: 'Thinking…' });
|
|
90
|
+
// 1. Fetch user profile
|
|
91
|
+
const profile = this.memory.getProfile();
|
|
92
|
+
// 2. Auto-recall relevant long-term memories based on the user's message
|
|
93
|
+
const recalledMemories = this.memory.searchMemories(messageText, this.config.memory.autoRecallTopK);
|
|
94
|
+
if (recalledMemories.length > 0) {
|
|
95
|
+
logger.memory(`Auto-recalled ${recalledMemories.length} relevant memories for query`);
|
|
96
|
+
}
|
|
97
|
+
// 3. Build dynamic system prompt
|
|
98
|
+
const availableSkills = this.pluginManager?.getAllSkills ? this.pluginManager.getAllSkills() : [];
|
|
99
|
+
const instructions = SystemPromptBuilder.build(this.config, profile, recalledMemories, { channel, userName: userName || profile.name }, availableSkills);
|
|
100
|
+
// 4. Retrieve recent short-term session messages
|
|
101
|
+
const recentHistory = this.memory.getRecentSessionMessages(sessionId, this.config.memory.maxShortTermHistory);
|
|
102
|
+
// 5. Construct input items for OpenAI Responses API
|
|
103
|
+
const inputItems = [];
|
|
104
|
+
// Add recent conversation history as easy input messages
|
|
105
|
+
for (const msg of recentHistory) {
|
|
106
|
+
if (msg.role === 'user' || msg.role === 'assistant') {
|
|
107
|
+
inputItems.push({
|
|
108
|
+
role: msg.role,
|
|
109
|
+
content: msg.content,
|
|
110
|
+
type: 'message',
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
// Add current user message
|
|
115
|
+
inputItems.push({
|
|
116
|
+
role: 'user',
|
|
117
|
+
content: messageText,
|
|
118
|
+
type: 'message',
|
|
119
|
+
});
|
|
120
|
+
// Record user message in session memory
|
|
121
|
+
this.memory.appendSessionMessage(sessionId, {
|
|
122
|
+
role: 'user',
|
|
123
|
+
content: messageText,
|
|
124
|
+
}, channel, userId, userName);
|
|
125
|
+
// 6. Multi-turn Agent Reasoning & Tool Loop
|
|
126
|
+
const openAiTools = this.tools.getOpenAITools();
|
|
127
|
+
let totalToolCalls = 0;
|
|
128
|
+
let finalReplyText = '';
|
|
129
|
+
let iterations = 0;
|
|
130
|
+
while (iterations < this.maxToolIterations) {
|
|
131
|
+
iterations++;
|
|
132
|
+
await emitEvent({ type: 'status', text: 'Thinking…' });
|
|
133
|
+
const modelResponse = await this.client.generate({
|
|
134
|
+
instructions,
|
|
135
|
+
input: inputItems,
|
|
136
|
+
tools: openAiTools,
|
|
137
|
+
onDelta: async (delta) => {
|
|
138
|
+
await emitEvent({ type: 'output.delta', text: delta });
|
|
139
|
+
},
|
|
140
|
+
onReasoningSummaryDelta: async (delta) => {
|
|
141
|
+
await emitEvent({ type: 'reasoning.summary.delta', text: delta });
|
|
142
|
+
},
|
|
143
|
+
});
|
|
144
|
+
if (modelResponse.text) {
|
|
145
|
+
finalReplyText = modelResponse.text;
|
|
146
|
+
}
|
|
147
|
+
// If no tool calls were requested, we are done
|
|
148
|
+
if (!modelResponse.toolCalls || modelResponse.toolCalls.length === 0) {
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
// Execute tool calls
|
|
152
|
+
totalToolCalls += modelResponse.toolCalls.length;
|
|
153
|
+
logger.agent(`Executing ${modelResponse.toolCalls.length} tool call(s) in turn ${iterations}`);
|
|
154
|
+
for (const call of modelResponse.toolCalls) {
|
|
155
|
+
// Append model's tool call to input items
|
|
156
|
+
inputItems.push({
|
|
157
|
+
type: 'function_call',
|
|
158
|
+
call_id: call.callId,
|
|
159
|
+
name: call.name,
|
|
160
|
+
arguments: call.arguments,
|
|
161
|
+
});
|
|
162
|
+
const toolStatus = this.formatToolStatus(call.name);
|
|
163
|
+
await emitEvent({ type: 'status', text: toolStatus });
|
|
164
|
+
await emitEvent({ type: 'tool.started', name: call.name });
|
|
165
|
+
// Execute tool with context
|
|
166
|
+
const execResult = await this.tools.executeTool(call.name, call.arguments, {
|
|
167
|
+
sessionId,
|
|
168
|
+
channel,
|
|
169
|
+
channelId,
|
|
170
|
+
userId,
|
|
171
|
+
userName,
|
|
172
|
+
threadTs,
|
|
173
|
+
memory: this.memory,
|
|
174
|
+
config: this.config,
|
|
175
|
+
scheduler: activeScheduler,
|
|
176
|
+
pluginManager: this.pluginManager,
|
|
177
|
+
toolRegistry: this.tools,
|
|
178
|
+
});
|
|
179
|
+
await emitEvent({ type: 'tool.completed', name: call.name });
|
|
180
|
+
const reviewStatus = this.formatToolReviewStatus(call.name, execResult.output);
|
|
181
|
+
if (reviewStatus) {
|
|
182
|
+
await emitEvent({ type: 'status', text: reviewStatus });
|
|
183
|
+
}
|
|
184
|
+
// Append tool output item to input items
|
|
185
|
+
inputItems.push({
|
|
186
|
+
type: 'function_call_output',
|
|
187
|
+
call_id: call.callId,
|
|
188
|
+
output: execResult.output,
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
// Fallback if no text was produced
|
|
193
|
+
if (!finalReplyText.trim()) {
|
|
194
|
+
finalReplyText = `I have completed processing your request with ${totalToolCalls} action(s).`;
|
|
195
|
+
}
|
|
196
|
+
// Record assistant's reply in short-term session memory
|
|
197
|
+
this.memory.appendSessionMessage(sessionId, {
|
|
198
|
+
role: 'assistant',
|
|
199
|
+
content: finalReplyText,
|
|
200
|
+
}, channel, userId, userName);
|
|
201
|
+
await emitEvent({ type: 'run.completed', text: finalReplyText });
|
|
202
|
+
logger.agent(`Replied with ${finalReplyText.length} characters (tools used: ${totalToolCalls})`);
|
|
203
|
+
return {
|
|
204
|
+
replyText: finalReplyText,
|
|
205
|
+
toolCallsCount: totalToolCalls,
|
|
206
|
+
sessionId,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
catch (err) {
|
|
210
|
+
await emitEvent({ type: 'run.failed', message: err.message || 'Run failed' });
|
|
211
|
+
throw err;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
//# sourceMappingURL=harness.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"harness.js","sourceRoot":"","sources":["../../src/agent/harness.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAExD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C,MAAM,OAAO,YAAY;IACf,MAAM,CAAgB;IACtB,MAAM,CAAgB;IACtB,KAAK,CAAe;IACpB,MAAM,CAAwB;IAC9B,iBAAiB,GAAW,CAAC,CAAC;IAE9B,SAAS,CAAO;IAChB,aAAa,CAAO;IAE5B,YACE,MAAqB,EACrB,MAAqB,EACrB,KAAmB,EACnB,MAA6B,EAC7B,SAAe,EACf,aAAmB;QAEnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACrC,CAAC;IAEM,YAAY,CAAC,SAAc;QAChC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;IAEM,YAAY;QACjB,OAAO,IAAI,CAAC,SAAS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BAAgB,cAAc,CAAC,MAAM,4BAA4B,cAAc,GAAG,CAAC,CAAC;YAEjG,OAAO;gBACL,SAAS,EAAE,cAAc;gBACzB,cAAc,EAAE,cAAc;gBAC9B,SAAS;aACV,CAAC;QACJ,CAAC;QAAC,OAAO,GAAQ,EAAE,CAAC;YAClB,MAAM,SAAS,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,IAAI,YAAY,EAAE,CAAC,CAAC;YAC9E,MAAM,GAAG,CAAC;QACZ,CAAC;IACH,CAAC;CACF"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { ModelConfig } from '../config/types.js';
|
|
2
|
+
import { OpenAIFunctionToolSchema } from '../tools/types.js';
|
|
3
|
+
export interface ExtractedToolCall {
|
|
4
|
+
callId: string;
|
|
5
|
+
name: string;
|
|
6
|
+
arguments: string;
|
|
7
|
+
}
|
|
8
|
+
export interface ModelResponseResult {
|
|
9
|
+
text: string;
|
|
10
|
+
toolCalls: ExtractedToolCall[];
|
|
11
|
+
rawOutput: any[];
|
|
12
|
+
}
|
|
13
|
+
export declare class OpenAIResponsesClient {
|
|
14
|
+
private client;
|
|
15
|
+
private model;
|
|
16
|
+
private temperature?;
|
|
17
|
+
private maxOutputTokens;
|
|
18
|
+
private readinessCache;
|
|
19
|
+
private reasoningEffort?;
|
|
20
|
+
constructor(config: ModelConfig);
|
|
21
|
+
getModelName(): string;
|
|
22
|
+
/** Verify that the configured credential can access the configured model. */
|
|
23
|
+
checkReadiness(cacheMs?: number): Promise<{
|
|
24
|
+
ready: boolean;
|
|
25
|
+
reason?: string;
|
|
26
|
+
}>;
|
|
27
|
+
private supportsTemperature;
|
|
28
|
+
generate(params: {
|
|
29
|
+
instructions: string;
|
|
30
|
+
input: any[];
|
|
31
|
+
tools?: OpenAIFunctionToolSchema[];
|
|
32
|
+
onDelta?: (delta: string) => void | Promise<void>;
|
|
33
|
+
onReasoningSummaryDelta?: (delta: string) => void | Promise<void>;
|
|
34
|
+
}): Promise<ModelResponseResult>;
|
|
35
|
+
}
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import OpenAI from 'openai';
|
|
2
|
+
import { logger } from '../utils/logger.js';
|
|
3
|
+
export class OpenAIResponsesClient {
|
|
4
|
+
client;
|
|
5
|
+
model;
|
|
6
|
+
temperature;
|
|
7
|
+
maxOutputTokens;
|
|
8
|
+
readinessCache = null;
|
|
9
|
+
reasoningEffort;
|
|
10
|
+
constructor(config) {
|
|
11
|
+
this.model = config.model || 'gpt-5.6-luna';
|
|
12
|
+
this.temperature = config.temperature;
|
|
13
|
+
this.maxOutputTokens = config.maxOutputTokens ?? 4096;
|
|
14
|
+
this.reasoningEffort = config.reasoningEffort;
|
|
15
|
+
this.client = new OpenAI({
|
|
16
|
+
apiKey: config.apiKey,
|
|
17
|
+
baseURL: config.baseUrl || undefined,
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
getModelName() {
|
|
21
|
+
return this.model;
|
|
22
|
+
}
|
|
23
|
+
/** Verify that the configured credential can access the configured model. */
|
|
24
|
+
async checkReadiness(cacheMs = 30000) {
|
|
25
|
+
const now = Date.now();
|
|
26
|
+
if (this.readinessCache && now - this.readinessCache.checkedAt < cacheMs) {
|
|
27
|
+
return { ready: this.readinessCache.ready, reason: this.readinessCache.reason };
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
await this.client.models.retrieve(this.model, { timeout: 4000, maxRetries: 0 });
|
|
31
|
+
this.readinessCache = { checkedAt: now, ready: true };
|
|
32
|
+
}
|
|
33
|
+
catch (err) {
|
|
34
|
+
const reason = err?.status === 401 || err?.status === 403
|
|
35
|
+
? 'credentials_rejected'
|
|
36
|
+
: err?.status === 404
|
|
37
|
+
? 'model_unavailable'
|
|
38
|
+
: 'provider_unreachable';
|
|
39
|
+
this.readinessCache = { checkedAt: now, ready: false, reason };
|
|
40
|
+
}
|
|
41
|
+
return { ready: this.readinessCache.ready, reason: this.readinessCache.reason };
|
|
42
|
+
}
|
|
43
|
+
supportsTemperature(model) {
|
|
44
|
+
const m = model.toLowerCase();
|
|
45
|
+
// gpt-5.6 family and reasoning models (o1, o3, o4) do not support temperature in Responses API
|
|
46
|
+
if (m.startsWith('gpt-5.6'))
|
|
47
|
+
return false;
|
|
48
|
+
if (m.startsWith('o1') || m.startsWith('o3') || m.startsWith('o4'))
|
|
49
|
+
return false;
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
async generate(params) {
|
|
53
|
+
logger.debug(`Calling OpenAI Responses API with model "${this.model}", ${params.input.length} input items...`);
|
|
54
|
+
const requestPayload = {
|
|
55
|
+
model: this.model,
|
|
56
|
+
instructions: params.instructions,
|
|
57
|
+
input: params.input,
|
|
58
|
+
max_output_tokens: this.maxOutputTokens,
|
|
59
|
+
};
|
|
60
|
+
if (this.reasoningEffort) {
|
|
61
|
+
requestPayload.reasoning = {
|
|
62
|
+
effort: this.reasoningEffort,
|
|
63
|
+
summary: 'auto',
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
if (this.temperature !== undefined && this.supportsTemperature(this.model)) {
|
|
67
|
+
requestPayload.temperature = this.temperature;
|
|
68
|
+
}
|
|
69
|
+
if (params.tools && params.tools.length > 0) {
|
|
70
|
+
requestPayload.tools = params.tools;
|
|
71
|
+
}
|
|
72
|
+
if (params.onDelta || params.onReasoningSummaryDelta) {
|
|
73
|
+
let stream;
|
|
74
|
+
try {
|
|
75
|
+
stream = await this.client.responses.create({
|
|
76
|
+
...requestPayload,
|
|
77
|
+
stream: true,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
const isTempError = err?.status === 400 &&
|
|
82
|
+
(err?.message?.includes('temperature') || err?.param === 'temperature' || err?.error?.param === 'temperature');
|
|
83
|
+
const isReasoningError = err?.status === 400 &&
|
|
84
|
+
(err?.message?.includes('reasoning') || err?.param === 'reasoning' || err?.error?.param === 'reasoning');
|
|
85
|
+
if (isTempError && requestPayload.temperature !== undefined) {
|
|
86
|
+
logger.debug(`Model "${this.model}" does not support temperature parameter. Retrying without temperature...`);
|
|
87
|
+
delete requestPayload.temperature;
|
|
88
|
+
stream = await this.client.responses.create({
|
|
89
|
+
...requestPayload,
|
|
90
|
+
stream: true,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
else if (isReasoningError && requestPayload.reasoning !== undefined) {
|
|
94
|
+
logger.debug(`Model "${this.model}" does not support reasoning parameter. Retrying without reasoning...`);
|
|
95
|
+
delete requestPayload.reasoning;
|
|
96
|
+
stream = await this.client.responses.create({
|
|
97
|
+
...requestPayload,
|
|
98
|
+
stream: true,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
logger.error(`OpenAI Responses API error (${this.model}):`, err.message || err);
|
|
103
|
+
if (err.status === 401 || (err.message && err.message.includes('API key'))) {
|
|
104
|
+
throw new Error(`OpenAI Authentication Error: Your API key is invalid or not provided. Run 'npm run onboard' to configure a valid API key.`);
|
|
105
|
+
}
|
|
106
|
+
throw err;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
let accumulatedText = '';
|
|
110
|
+
let completedResponse = null;
|
|
111
|
+
for await (const event of stream) {
|
|
112
|
+
if (event.type === 'response.output_text.delta') {
|
|
113
|
+
const delta = event.delta || '';
|
|
114
|
+
if (delta) {
|
|
115
|
+
accumulatedText += delta;
|
|
116
|
+
if (params.onDelta) {
|
|
117
|
+
try {
|
|
118
|
+
await params.onDelta(delta);
|
|
119
|
+
}
|
|
120
|
+
catch (cbErr) {
|
|
121
|
+
logger.debug('Error in onDelta streaming callback:', cbErr);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
else if (event.type === 'response.reasoning_summary_text.delta') {
|
|
127
|
+
const delta = event.delta || '';
|
|
128
|
+
if (delta && params.onReasoningSummaryDelta) {
|
|
129
|
+
try {
|
|
130
|
+
await params.onReasoningSummaryDelta(delta);
|
|
131
|
+
}
|
|
132
|
+
catch (cbErr) {
|
|
133
|
+
logger.debug('Error in onReasoningSummaryDelta streaming callback:', cbErr);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
else if (event.type === 'response.completed') {
|
|
138
|
+
completedResponse = event.response;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const toolCalls = [];
|
|
142
|
+
let text = accumulatedText;
|
|
143
|
+
if (completedResponse) {
|
|
144
|
+
if (typeof completedResponse.output_text === 'string' && completedResponse.output_text.trim()) {
|
|
145
|
+
text = completedResponse.output_text;
|
|
146
|
+
}
|
|
147
|
+
if (Array.isArray(completedResponse.output)) {
|
|
148
|
+
for (const item of completedResponse.output) {
|
|
149
|
+
if (item.type === 'message') {
|
|
150
|
+
const msgItem = item;
|
|
151
|
+
if (Array.isArray(msgItem.content)) {
|
|
152
|
+
for (const c of msgItem.content) {
|
|
153
|
+
if (c.type === 'text' || c.type === 'output_text') {
|
|
154
|
+
if (!text.includes(c.text)) {
|
|
155
|
+
text += (text ? '\n' : '') + c.text;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
else if (item.type === 'function_call') {
|
|
162
|
+
const call = item;
|
|
163
|
+
toolCalls.push({
|
|
164
|
+
callId: call.call_id || call.id || `call_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
|
|
165
|
+
name: call.name,
|
|
166
|
+
arguments: typeof call.arguments === 'string' ? call.arguments : JSON.stringify(call.arguments || {}),
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
text: text.trim(),
|
|
173
|
+
toolCalls,
|
|
174
|
+
rawOutput: completedResponse.output || [],
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
return {
|
|
178
|
+
text: accumulatedText.trim(),
|
|
179
|
+
toolCalls,
|
|
180
|
+
rawOutput: [],
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
let response;
|
|
184
|
+
try {
|
|
185
|
+
response = await this.client.responses.create(requestPayload);
|
|
186
|
+
}
|
|
187
|
+
catch (err) {
|
|
188
|
+
// Automatic recovery: if model rejected 'temperature' or 'reasoning', retry without it
|
|
189
|
+
const isTempError = err?.status === 400 &&
|
|
190
|
+
(err?.message?.includes('temperature') || err?.param === 'temperature' || err?.error?.param === 'temperature');
|
|
191
|
+
const isReasoningError = err?.status === 400 &&
|
|
192
|
+
(err?.message?.includes('reasoning') || err?.param === 'reasoning' || err?.error?.param === 'reasoning');
|
|
193
|
+
if (isTempError && requestPayload.temperature !== undefined) {
|
|
194
|
+
logger.debug(`Model "${this.model}" does not support temperature parameter. Retrying without temperature...`);
|
|
195
|
+
delete requestPayload.temperature;
|
|
196
|
+
response = await this.client.responses.create(requestPayload);
|
|
197
|
+
}
|
|
198
|
+
else if (isReasoningError && requestPayload.reasoning !== undefined) {
|
|
199
|
+
logger.debug(`Model "${this.model}" does not support reasoning parameter. Retrying without reasoning...`);
|
|
200
|
+
delete requestPayload.reasoning;
|
|
201
|
+
response = await this.client.responses.create(requestPayload);
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
logger.error(`OpenAI Responses API error (${this.model}):`, err.message || err);
|
|
205
|
+
// Graceful diagnostic for invalid/missing API key
|
|
206
|
+
if (err.status === 401 || (err.message && err.message.includes('API key'))) {
|
|
207
|
+
throw new Error(`OpenAI Authentication Error: Your API key is invalid or not provided. Run 'npm run onboard' to configure a valid API key.`);
|
|
208
|
+
}
|
|
209
|
+
throw err;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
let text = '';
|
|
213
|
+
const toolCalls = [];
|
|
214
|
+
// If SDK populated output_text convenience property
|
|
215
|
+
if (typeof response.output_text === 'string' && response.output_text.trim()) {
|
|
216
|
+
text = response.output_text;
|
|
217
|
+
}
|
|
218
|
+
// Process output items
|
|
219
|
+
if (Array.isArray(response.output)) {
|
|
220
|
+
for (const item of response.output) {
|
|
221
|
+
if (item.type === 'message') {
|
|
222
|
+
const msgItem = item;
|
|
223
|
+
if (Array.isArray(msgItem.content)) {
|
|
224
|
+
for (const c of msgItem.content) {
|
|
225
|
+
if (c.type === 'text' || c.type === 'output_text') {
|
|
226
|
+
if (!text.includes(c.text)) {
|
|
227
|
+
text += (text ? '\n' : '') + c.text;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
else if (item.type === 'function_call') {
|
|
234
|
+
const call = item;
|
|
235
|
+
toolCalls.push({
|
|
236
|
+
callId: call.call_id || call.id || `call_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
|
|
237
|
+
name: call.name,
|
|
238
|
+
arguments: typeof call.arguments === 'string' ? call.arguments : JSON.stringify(call.arguments || {}),
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return {
|
|
244
|
+
text: text.trim(),
|
|
245
|
+
toolCalls,
|
|
246
|
+
rawOutput: response.output || [],
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
//# sourceMappingURL=openaiResponsesClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openaiResponsesClient.js","sourceRoot":"","sources":["../../src/agent/openaiResponsesClient.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAG5B,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAc5C,MAAM,OAAO,qBAAqB;IACxB,MAAM,CAAS;IACf,KAAK,CAAS;IACd,WAAW,CAAU;IACrB,eAAe,CAAS;IACxB,cAAc,GAAkE,IAAI,CAAC;IACrF,eAAe,CAA6B;IAEpD,YAAY,MAAmB;QAC7B,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,IAAI,cAAc,CAAC;QAC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IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;gCACtC,CAAC;4BACH,CAAC;wBACH,CAAC;oBACH,CAAC;gBACH,CAAC;qBAAM,IAAI,IAAI,CAAC,IAAI,KAAK,eAAe,EAAE,CAAC;oBACzC,MAAM,IAAI,GAAG,IAAW,CAAC;oBACzB,SAAS,CAAC,IAAI,CAAC;wBACb,MAAM,EAAE,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,EAAE,IAAI,QAAQ,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE;wBACrG,IAAI,EAAE,IAAI,CAAC,IAAI;wBACf,SAAS,EAAE,OAAO,IAAI,CAAC,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,SAAS,IAAI,EAAE,CAAC;qBACtG,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE;YACjB,SAAS;YACT,SAAS,EAAE,QAAQ,CAAC,MAAM,IAAI,EAAE;SACjC,CAAC;IACJ,CAAC;CACF"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { MusondaConfig } from '../config/types.js';
|
|
2
|
+
import { UserMemoryProfile, MemoryItem } from '../memory/types.js';
|
|
3
|
+
import { AgentSkill } from '../plugins/skills/types.js';
|
|
4
|
+
export declare class SystemPromptBuilder {
|
|
5
|
+
static build(config: MusondaConfig, profile: UserMemoryProfile, recalledMemories: MemoryItem[] | undefined, contextInfo: {
|
|
6
|
+
channel: string;
|
|
7
|
+
userName?: string;
|
|
8
|
+
}, availableSkills?: AgentSkill[]): string;
|
|
9
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
export class SystemPromptBuilder {
|
|
2
|
+
static build(config, profile, recalledMemories = [], contextInfo, availableSkills = []) {
|
|
3
|
+
const assistantName = profile.assistantCustomName || config.assistant.customName || config.assistant.name || 'Musonda';
|
|
4
|
+
const now = new Date();
|
|
5
|
+
const userTimezone = profile.timezone || 'UTC';
|
|
6
|
+
let formattedLocalTime;
|
|
7
|
+
try {
|
|
8
|
+
formattedLocalTime = new Intl.DateTimeFormat('en-US', {
|
|
9
|
+
timeZone: userTimezone,
|
|
10
|
+
dateStyle: 'full',
|
|
11
|
+
timeStyle: 'long',
|
|
12
|
+
}).format(now);
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
formattedLocalTime = now.toUTCString();
|
|
16
|
+
}
|
|
17
|
+
const memorySection = recalledMemories.length > 0
|
|
18
|
+
? `\n## Relevant Recalled Memories from Past Interactions:\n${recalledMemories
|
|
19
|
+
.map((m, idx) => `${idx + 1}. [${m.category.toUpperCase()}] ${m.content} (tags: ${m.tags.join(', ')})`)
|
|
20
|
+
.join('\n')}\n`
|
|
21
|
+
: '';
|
|
22
|
+
const skillsSection = availableSkills && availableSkills.length > 0
|
|
23
|
+
? `\n## Available Agent Skills:
|
|
24
|
+
You have access to specialized Agent Skills installed via plugins. You can inspect all available skills with 'skill_list', read full instructions for any skill with 'skill_read', or run bundled skill scripts with 'skill_run_script'.
|
|
25
|
+
${availableSkills.map((s, idx) => `${idx + 1}. **${s.name}** (from plugin "${s.pluginName}"): ${s.description}`).join('\n')}\n`
|
|
26
|
+
: '';
|
|
27
|
+
const profileBio = profile.bio ? `\n- User Background: ${profile.bio}` : '';
|
|
28
|
+
const profileInterests = profile.interests && profile.interests.length > 0
|
|
29
|
+
? `\n- User Interests: ${profile.interests.join(', ')}`
|
|
30
|
+
: '';
|
|
31
|
+
const profileNotes = profile.notes ? `\n- User Notes: ${profile.notes}` : '';
|
|
32
|
+
return `You are ${assistantName}, a personal autonomous AI companion and agent harness.
|
|
33
|
+
You are running continuously inside the Musonda Gateway, bridging the user through channels like Discord.
|
|
34
|
+
|
|
35
|
+
## Core Identity & Persona:
|
|
36
|
+
- Name: ${assistantName}
|
|
37
|
+
- Role: ${config.assistant.title || 'Personal Autonomous AI Companion'}
|
|
38
|
+
- Personality: ${config.assistant.tone || 'Empathetic, intelligent, proactive, practical, and highly capable'}
|
|
39
|
+
- Running On: OpenAI Responses API using model "${config.model.model}" (efficiency & agentic tier)
|
|
40
|
+
- Active Channel: ${contextInfo.channel.toUpperCase()}
|
|
41
|
+
|
|
42
|
+
## User Profile:
|
|
43
|
+
- User's Name: ${profile.name} (Address them respectfully and naturally)
|
|
44
|
+
- Channel User Handle: ${contextInfo.userName || profile.name}
|
|
45
|
+
- User Timezone: ${userTimezone}
|
|
46
|
+
- Current Local Time: ${formattedLocalTime}${profileBio}${profileInterests}${profileNotes}
|
|
47
|
+
- Communication Style: ${profile.communicationStyle}
|
|
48
|
+
${memorySection}${skillsSection}
|
|
49
|
+
## Operational Directives:
|
|
50
|
+
1. Memory Awareness: You have persistent memory. When the user tells you about themselves, their projects, preferences, or important facts, use the 'memory_store' tool to persist it.
|
|
51
|
+
2. Self-Correction & Learning: If the user corrects you or updates their preferences, update the profile using 'update_user_profile' or store a new memory item.
|
|
52
|
+
3. Tool Usage:
|
|
53
|
+
- Use 'current_time' when timing, dates, or schedule planning matters.
|
|
54
|
+
- Use 'memory_recall' if you need to search past conversations or stored notes.
|
|
55
|
+
- Use 'calculate' for precise mathematical expressions.
|
|
56
|
+
- Use 'web_search' or 'web_fetch' when looking up recent information, links, or documentation.
|
|
57
|
+
- Use 'note_save', 'note_read', 'note_list' to manage personal notes, drafts, or task lists.
|
|
58
|
+
- Use 'skill_list' and 'skill_read' to inspect and load Agent Skills, and 'skill_run_script' to execute bundled skill scripts.
|
|
59
|
+
- Agent Plugins Ecosystem (v1.0.0 Standard: https://agent-plugins.org/):
|
|
60
|
+
You are an expert on portable Agent Plugins conforming to the Agent Plugins 1.0.0 specification (https://agent-plugins.org):
|
|
61
|
+
* Standard Architecture: A plugin package is a self-contained directory containing:
|
|
62
|
+
1. 'plugin.json': Canonical root manifest with "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name" (1-64 lowercase alphanumeric chars with single hyphens or dots, e.g. "acme-tools"), "version", "description", "author", "license", "keywords", and client "extensions".
|
|
63
|
+
2. 'skills/': Fixed directory for Agent Skills. Each immediate child directory contains a 'SKILL.md' file with YAML frontmatter (name matching directory, description) and instructions, plus optional 'scripts/' and 'references/'.
|
|
64
|
+
3. 'mcp.json': Fixed root MCP configuration with "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json" and "mcpServers" ('stdio', 'streamable-http', or 'sse'). Stdio subprocesses receive isolated environment variables 'PLUGIN_ROOT' and persistent writable 'PLUGIN_DATA', with \${PLUGIN_ROOT} and \${PLUGIN_DATA} placeholder expansions in args/env/cwd.
|
|
65
|
+
* Finding Plugins:
|
|
66
|
+
- Use 'plugin_find' to search for plugins both locally and across the ecosystem.
|
|
67
|
+
- Official & Ecosystem Catalogs: https://agent-plugins.org, GitHub organization 'agentplugins' (e.g. 'agentplugins/agent-plugins-example'), GitHub topic 'agent-plugin', and npm keyword 'agent-plugin'.
|
|
68
|
+
- Use 'web_search' or 'web_fetch' to research plugins, compatible clients, and specifications.
|
|
69
|
+
* Adding & Installing Plugins:
|
|
70
|
+
- Use 'plugin_install' to install plugins from a Git repo URL (e.g. 'https://github.com/agentplugins/agent-plugins-example.git', 'agentplugins/agent-plugins-example'), a local directory path, or an npm package. Musonda validates conformance, installs package dependencies, and immediately activates skills and MCP tools in live runtime without restarting the server.
|
|
71
|
+
- Use 'plugin_create' to scaffold custom plugins with valid manifests, skills, and MCP definitions.
|
|
72
|
+
* Inspecting & Using Plugins:
|
|
73
|
+
- Use 'plugin_list' to list all currently active plugins, skills, and MCP tools in the Gateway runtime.
|
|
74
|
+
- Use 'plugin_info' to inspect detailed manifest metadata, skill instruction summaries, and server configurations for any plugin.
|
|
75
|
+
- To use skills: inspect with 'skill_list', load instructions with 'skill_read', and run bundled scripts with 'skill_run_script'.
|
|
76
|
+
- To use MCP tools: invoke bridged MCP tools (prefixed with 'mcp_*') directly from your tool registry.
|
|
77
|
+
* Removing & Managing Plugins:
|
|
78
|
+
- Use 'plugin_remove' to unload and uninstall a plugin. It cleanly terminates active MCP subprocesses, deregisters bridged tools, removes skills, and deletes plugin files (with optional purge of persistent data).
|
|
79
|
+
- Use 'plugin_reload' to refresh plugins from disk without restarting the Gateway.
|
|
80
|
+
- Use MCP (Model Context Protocol) tools (named 'mcp_*') to interact with connected MCP server capabilities.
|
|
81
|
+
- Use File Tools to inspect and manipulate files in the user-permitted workspace:
|
|
82
|
+
* 'file_read' to read file contents or paginate line ranges.
|
|
83
|
+
* 'file_write' to create or overwrite files (parent directories auto-created).
|
|
84
|
+
* 'file_edit' to perform precise search-and-replace text edits.
|
|
85
|
+
* 'file_append' to append text to files.
|
|
86
|
+
* 'file_list' to browse directory trees.
|
|
87
|
+
* 'file_info' to inspect file/directory metadata and permissions.
|
|
88
|
+
* 'directory_create' to create directories.
|
|
89
|
+
* 'file_search' to find files matching glob patterns or names.
|
|
90
|
+
* 'file_grep' to search text across files.
|
|
91
|
+
* 'file_delete' to delete files or directories.
|
|
92
|
+
Filesystem Sandboxing & Guardrails: You operate under strict filesystem sandboxing. You may only access paths explicitly permitted by the user in configuration. Path traversals (e.g. '../'), symlink escapes, and sensitive files (like '.env', private keys, credentials) are strictly forbidden and guarded. If a path is blocked, explain the security boundary to the user.
|
|
93
|
+
4. Channel Formatting: You are communicating via ${contextInfo.channel.toUpperCase()}. Make your messages readable, utilize Markdown headings, bullet points, and code blocks where appropriate. Keep responses engaging and avoid needless boilerplate.
|
|
94
|
+
5. Scheduling & Autonomous Cronjobs: You have built-in autonomous scheduling capabilities via the Gateway. When the user asks you to remind them in the future (e.g. "in 20 minutes", "tomorrow at 9am") or asks for recurring cron tasks (e.g. "every morning at 8am send tech news", "every Monday at 9am send task summary"), use 'schedule_create'. Set action_type to 'reminder' for simple reminder notes, or 'prompt' if you should autonomously generate dynamic content when triggered. Use 'schedule_list' to check active schedules and 'schedule_cancel' to cancel them.
|
|
95
|
+
|
|
96
|
+
${config.assistant.systemInstructions || ''}
|
|
97
|
+
`.trim();
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
//# sourceMappingURL=systemPrompt.js.map
|