Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(agents): add per-function AI config and fix challenge solver CLI dispatch

Adam Eivy76e50b34b45b
diff --git a/.changelog/v0.12.x.md b/.changelog/v0.12.x.md
index 35e7b2fe31..d116161f12 100644
--- a/.changelog/v0.12.x.md
+++ b/.changelog/v0.12.x.md
@@ -370,25 +370,22 @@ This release adds branch management and automated release workflow capabilities
- `client/src/services/api.js` — Added `getCosActionableInsights()` API function
- `client/src/pages/ChiefOfStaff.jsx` — Renders ActionableInsightsBanner above QuickSummary on the Tasks tab
-### Agents — Per-Agent AI Provider/Model Configuration
-- **Agent-level AI config**: Each agent can now have its own default AI provider and model for content generation, instead of always using the globally active provider
-- **Overview tab selector**: New "Default AI Provider" section on the agent Overview tab with provider and model dropdowns, plus a dedicated Save button
-- **System Default fallback**: When no provider is configured (or cleared), the agent falls back to the globally active provider
-- **Automated flows**: Scheduled actions (post, comment, engage, monitor) all use the agent's configured provider when available
-- **Manual generation**: "Generate Post" and "Generate Comment" in the Tools tab use the agent's AI config
-- **Challenge solver**: Moltbook verification challenges can use the agent's preferred provider for solving
+### Agents — Per-Function AI Provider/Model Configuration
+- **Per-function AI config**: Each agent can now configure separate AI providers for **Content Generation** (posts/comments), **Engagement** (autonomous interactions), and **Challenge Solving** (verification)
+- **Overview tab UI**: Replaced single "Default AI Provider" selector with 3 function-specific rows, each with provider + model dropdowns
+- **Backward compatible**: Agents with the old `{ providerId, model }` format continue to work — per-function overrides take precedence when set
+- **CLI provider fix**: Challenge solver now correctly dispatches to CLI providers (was hardcoding API-only execution, causing "API error: 0" for CLI providers like Claude Code CLI)
+- **Removed dead code**: Removed regex-based challenge solver fallback that didn't work reliably with obfuscated text
**Server changes**:
-- `server/lib/validation.js` — Added `agentAiConfigSchema` and `aiConfig` field to `agentSchema`
-- `server/services/agentPersonalities.js` — `createAgent()` preserves `aiConfig` field
-- `server/services/agentActionExecutor.js` — `executePost`, `executeComment`, `executeEngage`, `executeMonitor` pass `agent.aiConfig` to content generators
-- `server/routes/agentTools.js` — `check-posts` and `engage` endpoints pass `agent.aiConfig` to `generateReply`/`generateComment`
-- `server/integrations/moltbook/challengeSolver.js` — `solveChallenge()` and `solveWithAI()` accept optional AI config for agent-specific provider
+- `server/lib/validation.js` — Expanded `agentAiConfigSchema` with optional `content`, `engagement`, `challenge` sub-objects
+- `server/services/agentActionExecutor.js` — `executePost`/`executeComment` use `aiConfig.content`, `executeEngage`/`executeMonitor` use `aiConfig.engagement`
+- `server/routes/agentTools.js` — Publish routes pass `aiConfig.challenge` to client, engage/check-posts use `aiConfig.engagement`
+- `server/integrations/moltbook/challengeSolver.js` — Added CLI provider dispatch (same pattern as `agentContentGenerator.js`), removed regex fallback
**Client changes**:
-- `client/src/components/agents/tabs/OverviewTab.jsx` — Added "Default AI Provider" card with provider/model selectors and save button
-- `client/src/components/agents/tabs/ToolsTab.jsx` — Generate Post and Generate Comment pass agent's `aiConfig` to API calls
-- `client/src/components/agents/AgentDetail.jsx` — Passes `agent` prop to ToolsTab
+- `client/src/components/agents/tabs/OverviewTab.jsx` — 3-row per-function AI provider/model selector UI
+- `client/src/components/agents/tabs/ToolsTab.jsx` — Generate Post/Comment use `aiConfig.content` config
### Dashboard — CoS Productivity Widget
- **At-a-glance CoS status**: New widget on the main Dashboard showing Chief of Staff productivity metrics without navigating to the CoS page
diff --git a/client/src/components/agents/tabs/OverviewTab.jsx b/client/src/components/agents/tabs/OverviewTab.jsx
index 06bfa0b862..31b9d83018 100644
--- a/client/src/components/agents/tabs/OverviewTab.jsx
+++ b/client/src/components/agents/tabs/OverviewTab.jsx
@@ -76,8 +76,10 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {
const selectedProvider = providers.find(p => p.id === selectedProviderId);
const availableModels = selectedProvider?.models || [];
- const aiConfigProvider = providers.find(p => p.id === formData?.aiConfig?.providerId);
- const aiConfigModels = aiConfigProvider?.models || [];
+ const getModelsForProvider = (providerId) => {
+ const p = providers.find(pr => pr.id === providerId);
+ return p?.models || [];
+ };
const handleGenerate = async () => {
setGenerating(true);
@@ -119,9 +121,24 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {
toast.success(`Generated: ${generated.name || 'personality'}`);
};
+ const buildAiConfig = (config) => {
+ if (!config) return undefined;
+ const cleaned = {};
+ if (config.providerId) cleaned.providerId = config.providerId;
+ if (config.model) cleaned.model = config.model;
+ const fnKeys = ['content', 'engagement', 'challenge'];
+ for (const key of fnKeys) {
+ if (config[key]?.providerId) {
+ cleaned[key] = { providerId: config[key].providerId };
+ if (config[key].model) cleaned[key].model = config[key].model;
+ }
+ }
+ return Object.keys(cleaned).length > 0 ? cleaned : undefined;
+ };
+
const handleSave = async (e) => {
e.preventDefault();
- const aiConfig = formData.aiConfig?.providerId ? formData.aiConfig : undefined;
+ const aiConfig = buildAiConfig(formData.aiConfig);
const submitData = {
...formData,
personality: {
@@ -372,68 +389,84 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {
</form>
</div>
- {/* Default AI Provider Section */}
+ {/* Per-Function AI Provider Section */}
<div className="bg-port-card border border-port-border rounded-lg p-4">
<div className="flex items-center gap-2 mb-3">
<Cpu size={16} className="text-port-accent" />
- <h3 className="text-md font-semibold text-white">Default AI Provider</h3>
+ <h3 className="text-md font-semibold text-white">AI Providers</h3>
</div>
<p className="text-xs text-gray-500 mb-3">
- Choose which AI provider and model this agent uses for content generation (posts, comments, replies). Leave as "System Default" to use the globally active provider.
+ Choose AI providers for each function. "System Default" uses the globally active provider.
</p>
- <div className="flex items-end gap-3">
- <div className="flex-1">
- <label className="block text-xs text-gray-400 mb-1">Provider</label>
- <select
- value={formData.aiConfig?.providerId || ''}
- onChange={(e) => setFormData(prev => ({
- ...prev,
- aiConfig: { ...prev.aiConfig, providerId: e.target.value || undefined, model: undefined }
- }))}
- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
- >
- <option value="">System Default</option>
- {providers.map(p => (
- <option key={p.id} value={p.id}>{p.name}</option>
- ))}
- </select>
- </div>
- <div className="flex-1">
- <label className="block text-xs text-gray-400 mb-1">Model</label>
- <select
- value={formData.aiConfig?.model || ''}
- onChange={(e) => setFormData(prev => ({
- ...prev,
- aiConfig: { ...prev.aiConfig, model: e.target.value || undefined }
- }))}
- disabled={!formData.aiConfig?.providerId}
- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm disabled:opacity-50"
- >
- <option value="">Default</option>
- {aiConfigModels.map(m => (
- <option key={m} value={m}>{m}</option>
- ))}
- </select>
- </div>
- <button
- type="button"
- onClick={async () => {
- const aiConfig = formData.aiConfig?.providerId ? formData.aiConfig : undefined;
- await api.updateAgentPersonality(agentId, { aiConfig });
- toast.success(aiConfig ? 'AI provider saved' : 'Reset to system default');
- onAgentUpdate?.();
- }}
- className="px-4 py-1.5 bg-port-success text-white rounded hover:bg-port-success/80 text-sm whitespace-nowrap"
- >
- Save
- </button>
+ <div className="space-y-3">
+ {[
+ { key: 'content', label: 'Content Generation', desc: 'Posts, comments, replies' },
+ { key: 'engagement', label: 'Engagement', desc: 'Autonomous voting & commenting' },
+ { key: 'challenge', label: 'Challenge Solving', desc: 'Verification challenges' }
+ ].map(({ key, label, desc }) => {
+ const fnConfig = formData.aiConfig?.[key] || {};
+ const fnModels = getModelsForProvider(fnConfig.providerId);
+ return (
+ <div key={key} className="flex items-end gap-3">
+ <div className="w-40 shrink-0 pb-1">
+ <div className="text-sm text-white">{label}</div>
+ <div className="text-[10px] text-gray-500">{desc}</div>
+ </div>
+ <div className="flex-1">
+ <label className="block text-xs text-gray-400 mb-1">Provider</label>
+ <select
+ value={fnConfig.providerId || ''}
+ onChange={(e) => setFormData(prev => ({
+ ...prev,
+ aiConfig: {
+ ...prev.aiConfig,
+ [key]: { ...prev.aiConfig?.[key], providerId: e.target.value || undefined, model: undefined }
+ }
+ }))}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
+ >
+ <option value="">System Default</option>
+ {providers.map(p => (
+ <option key={p.id} value={p.id}>{p.name}</option>
+ ))}
+ </select>
+ </div>
+ <div className="flex-1">
+ <label className="block text-xs text-gray-400 mb-1">Model</label>
+ <select
+ value={fnConfig.model || ''}
+ onChange={(e) => setFormData(prev => ({
+ ...prev,
+ aiConfig: {
+ ...prev.aiConfig,
+ [key]: { ...prev.aiConfig?.[key], model: e.target.value || undefined }
+ }
+ }))}
+ disabled={!fnConfig.providerId}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm disabled:opacity-50"
+ >
+ <option value="">Default</option>
+ {fnModels.map(m => (
+ <option key={m} value={m}>{m}</option>
+ ))}
+ </select>
+ </div>
+ </div>
+ );
+ })}
</div>
- {formData.aiConfig?.providerId && (
- <p className="text-xs text-port-accent mt-2">
- Using: {aiConfigProvider?.name || formData.aiConfig.providerId}
- {formData.aiConfig.model && ` / ${formData.aiConfig.model}`}
- </p>
- )}
+ <button
+ type="button"
+ onClick={async () => {
+ const aiConfig = buildAiConfig(formData.aiConfig);
+ await api.updateAgentPersonality(agentId, { aiConfig });
+ toast.success(aiConfig ? 'AI providers saved' : 'Reset to system defaults');
+ onAgentUpdate?.();
+ }}
+ className="mt-3 px-4 py-1.5 bg-port-success text-white rounded hover:bg-port-success/80 text-sm"
+ >
+ Save AI Config
+ </button>
</div>
{/* Accounts Section */}
diff --git a/client/src/components/agents/tabs/ToolsTab.jsx b/client/src/components/agents/tabs/ToolsTab.jsx
index b9b1a67c93..63733b3da7 100644
--- a/client/src/components/agents/tabs/ToolsTab.jsx
+++ b/client/src/components/agents/tabs/ToolsTab.jsx
@@ -111,7 +111,8 @@ export default function ToolsTab({ agentId, agent }) {
const handleGeneratePost = async () => {
if (!agentId || !selectedAccountId) return;
setGenerating(true);
- const generated = await api.generateAgentPost(agentId, selectedAccountId, selectedSubmolt, agent?.aiConfig?.providerId, agent?.aiConfig?.model);
+ const contentConfig = agent?.aiConfig?.content || agent?.aiConfig;
+ const generated = await api.generateAgentPost(agentId, selectedAccountId, selectedSubmolt, contentConfig?.providerId, contentConfig?.model);
setPostTitle(generated.title);
setPostContent(generated.content);
setGenerating(false);
@@ -163,9 +164,10 @@ export default function ToolsTab({ agentId, agent }) {
const handleGenerateComment = async () => {
if (!selectedPost) return;
setGeneratingComment(true);
+ const contentConfig = agent?.aiConfig?.content || agent?.aiConfig;
const generated = await api.generateAgentComment(
agentId, selectedAccountId, selectedPost.id, replyToId || undefined,
- agent?.aiConfig?.providerId, agent?.aiConfig?.model
+ contentConfig?.providerId, contentConfig?.model
);
setCommentContent(generated.content);
setGeneratingComment(false);
diff --git a/server/integrations/moltbook/challengeSolver.js b/server/integrations/moltbook/challengeSolver.js
index be4130c9ba..068eba6bf4 100644
--- a/server/integrations/moltbook/challengeSolver.js
+++ b/server/integrations/moltbook/challengeSolver.js
@@ -9,126 +9,14 @@
* - Contains a simple arithmetic problem (addition, subtraction, etc.)
* - Answer must be a number with 2 decimal places (e.g., "47.00")
*
- * Uses AI for interpretation when available, with a regex fallback.
+ * Uses AI for interpretation — supports both API and CLI providers.
*/
-import { executeApiRun, createRun } from '../../services/runner.js';
+import { executeApiRun, executeCliRun, createRun } from '../../services/runner.js';
import { getActiveProvider, getProviderById } from '../../services/providers.js';
/**
- * Strip obfuscation noise from Moltbook challenge text
- * Removes: brackets, carets, braces, then collapses consecutive case-insensitive duplicate letters
- */
-export function cleanChallengeText(text) {
- // Strip all injected noise — keep only letters, digits, spaces, commas, question marks, hyphens
- let cleaned = text.replace(/[^a-zA-Z0-9\s,?'-]/g, '');
-
- // Collapse consecutive case-insensitive duplicate letters
- // e.g., "LoOoBbSsTtEeR" -> "LoBSTER" (lobster)
- let result = '';
- for (let i = 0; i < cleaned.length; i++) {
- const char = cleaned[i];
- const prev = result[result.length - 1];
- if (prev && char.toLowerCase() === prev.toLowerCase()) continue;
- result += char;
- }
-
- // Normalize whitespace
- return result.replace(/\s+/g, ' ').trim();
-}
-
-// Word-to-number mapping for fallback solver
-const WORD_NUMBERS = {
- zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9,
- ten: 10, eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16,
- seventeen: 17, eighteen: 18, nineteen: 19, twenty: 20, thirty: 30, forty: 40, fifty: 50,
- sixty: 60, seventy: 70, eighty: 80, ninety: 90, hundred: 100, thousand: 1000
-};
-
-/**
- * Parse a number from word representation (e.g., "thirty five" -> 35)
- */
-function wordsToNumber(words) {
- const tokens = words.toLowerCase().split(/[\s-]+/);
- let total = 0;
- let current = 0;
-
- for (const token of tokens) {
- const val = WORD_NUMBERS[token];
- if (val === undefined) continue;
- if (val === 100) {
- current = (current || 1) * 100;
- } else if (val === 1000) {
- current = (current || 1) * 1000;
- total += current;
- current = 0;
- } else {
- current += val;
- }
- }
-
- return total + current;
-}
-
-/**
- * Attempt to solve the challenge using regex-based number extraction and arithmetic
- */
-export function solveWithRegex(challengeText) {
- const cleaned = cleanChallengeText(challengeText);
- console.log(`🔐 Cleaned challenge: "${cleaned}"`);
-
- // Try to find numeric values (digit-based)
- const digitNumbers = cleaned.match(/\d+\.?\d*/g);
- if (digitNumbers?.length >= 2) {
- // Simple addition/subtraction with digit numbers
- const nums = digitNumbers.map(Number);
- if (cleaned.toLowerCase().includes('add') || cleaned.toLowerCase().includes('total') || cleaned.toLowerCase().includes('sum') || cleaned.toLowerCase().includes('plus')) {
- return nums.reduce((a, b) => a + b, 0);
- }
- if (cleaned.toLowerCase().includes('subtract') || cleaned.toLowerCase().includes('minus') || cleaned.toLowerCase().includes('difference')) {
- return nums[0] - nums.slice(1).reduce((a, b) => a + b, 0);
- }
- if (cleaned.toLowerCase().includes('multiply') || cleaned.toLowerCase().includes('times') || cleaned.toLowerCase().includes('product')) {
- return nums.reduce((a, b) => a * b, 1);
- }
- // Default: addition for "total" / "what is"
- return nums.reduce((a, b) => a + b, 0);
- }
-
- // Try word-based numbers
- const lc = cleaned.toLowerCase();
-
- // Extract patterns like "X is [number words] and ... adds/plus [number words]"
- const numberWordPattern = /(?:zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand)[\s-]*/gi;
-
- // Find number word sequences
- const numberSequences = [];
- let match;
- const wordRegex = /(?:(?:zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand)[\s-]*)+/gi;
- while ((match = wordRegex.exec(lc)) !== null) {
- const num = wordsToNumber(match[0]);
- if (num > 0) numberSequences.push(num);
- }
-
- if (numberSequences.length >= 2) {
- if (lc.includes('add') || lc.includes('total') || lc.includes('sum') || lc.includes('plus')) {
- return numberSequences.reduce((a, b) => a + b, 0);
- }
- if (lc.includes('subtract') || lc.includes('minus') || lc.includes('difference')) {
- return numberSequences[0] - numberSequences.slice(1).reduce((a, b) => a + b, 0);
- }
- if (lc.includes('multiply') || lc.includes('times') || lc.includes('product')) {
- return numberSequences.reduce((a, b) => a * b, 1);
- }
- // Default: addition
- return numberSequences.reduce((a, b) => a + b, 0);
- }
-
- return null;
-}
-
-/**
- * Solve using AI interpretation
+ * Solve using AI interpretation (supports both API and CLI providers)
*/
async function solveWithAI(challengeText, aiConfig) {
let provider;
@@ -159,20 +47,40 @@ Answer:`;
});
let responseText = '';
+ const isCliProvider = provider.type === 'cli';
+
await new Promise((resolve, reject) => {
- executeApiRun(
- runId,
- provider,
- model,
- prompt,
- process.cwd(),
- [],
- (data) => { responseText += typeof data === 'string' ? data : (data?.text || ''); },
- (result) => {
- if (result?.error) reject(new Error(result.error));
- else resolve(result);
- }
- );
+ if (isCliProvider) {
+ executeCliRun(
+ runId,
+ provider,
+ prompt,
+ process.cwd(),
+ (text) => { responseText += text; },
+ (result) => {
+ if (result?.error || result?.success === false) {
+ reject(new Error(result?.error || 'CLI execution failed'));
+ } else {
+ resolve(result);
+ }
+ },
+ provider.timeout || 300000
+ );
+ } else {
+ executeApiRun(
+ runId,
+ provider,
+ model,
+ prompt,
+ process.cwd(),
+ [],
+ (data) => { responseText += typeof data === 'string' ? data : (data?.text || ''); },
+ (result) => {
+ if (result?.error) reject(new Error(result.error));
+ else resolve(result);
+ }
+ );
+ }
});
// Extract number from response
@@ -187,7 +95,6 @@ Answer:`;
/**
* Solve a Moltbook verification challenge
- * Prefers AI (handles obfuscation reliably), falls back to regex if no AI provider
* @param {string} challengeText - The obfuscated challenge text
* @param {{ providerId?: string, model?: string }} [aiConfig] - Optional AI provider config
* @returns {string|null} Answer formatted with 2 decimal places, or null if unsolvable
@@ -195,7 +102,6 @@ Answer:`;
export async function solveChallenge(challengeText, aiConfig) {
console.log(`🔐 Solving challenge: "${challengeText.substring(0, 80)}..."`);
- // Try AI first — handles obfuscation much better than regex
const aiAnswer = await solveWithAI(challengeText, aiConfig).catch(err => {
console.log(`🔐 AI solver error: ${err.message}`);
return null;
@@ -206,15 +112,6 @@ export async function solveChallenge(challengeText, aiConfig) {
return formatted;
}
- // Fall back to regex (works when numbers aren't heavily obfuscated)
- console.log(`🔐 AI unavailable, trying regex solver...`);
- const regexAnswer = solveWithRegex(challengeText);
- if (regexAnswer !== null) {
- const formatted = regexAnswer.toFixed(2);
- console.log(`🔐 Regex solver: ${formatted}`);
- return formatted;
- }
-
- console.error(`❌ Could not solve Moltbook challenge`);
+ console.error(`❌ Could not solve Moltbook challenge — no AI provider available`);
return null;
}
diff --git a/server/lib/validation.js b/server/lib/validation.js
index cfe1a111fc..c19b52f637 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -29,10 +29,19 @@ export const agentAvatarSchema = z.object({
color: z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional()
}).optional();
-// Agent AI config (preferred provider/model for content generation)
-export const agentAiConfigSchema = z.object({
+// Per-function AI provider/model override
+const aiFunctionConfigSchema = z.object({
providerId: z.string().min(1).optional(),
model: z.string().min(1).optional()
+});
+
+// Agent AI config (preferred provider/model, with optional per-function overrides)
+export const agentAiConfigSchema = z.object({
+ providerId: z.string().min(1).optional(),
+ model: z.string().min(1).optional(),
+ content: aiFunctionConfigSchema.optional(),
+ engagement: aiFunctionConfigSchema.optional(),
+ challenge: aiFunctionConfigSchema.optional()
}).optional();
// Full agent schema
diff --git a/server/routes/agentTools.js b/server/routes/agentTools.js
index 3f3a76897a..b4bbaa33ad 100644
--- a/server/routes/agentTools.js
+++ b/server/routes/agentTools.js
@@ -102,7 +102,7 @@ router.post('/publish-post', asyncHandler(async (req, res) => {
console.log(`🛠️ POST /api/agents/tools/publish-post agent=${data.agentId} submolt=${data.submolt}`);
const { client, agent, account } = await getClientAndAgent(data.accountId, data.agentId);
- client.aiConfig = agent.aiConfig;
+ client.aiConfig = agent.aiConfig?.challenge || agent.aiConfig;
const result = await client.createPost(data.submolt, data.title, data.content);
const post = result?.post || result;
const postId = post?.id || post?._id || post?.post_id;
@@ -132,7 +132,7 @@ router.post('/publish-comment', asyncHandler(async (req, res) => {
console.log(`🛠️ POST /api/agents/tools/publish-comment agent=${data.agentId} post=${data.postId}`);
const { client, agent } = await getClientAndAgent(data.accountId, data.agentId);
- client.aiConfig = agent.aiConfig;
+ client.aiConfig = agent.aiConfig?.challenge || agent.aiConfig;
let result;
if (data.parentId) {
@@ -209,7 +209,8 @@ router.post('/engage', asyncHandler(async (req, res) => {
const rateCheck = checkRateLimit(client.apiKey, 'comment');
if (!rateCheck.allowed) break;
- const generated = await generateComment(agent, opportunity.post, opportunity.comments, null, agent.aiConfig?.providerId, agent.aiConfig?.model);
+ const engagementConfig = agent.aiConfig?.engagement || agent.aiConfig;
+ const generated = await generateComment(agent, opportunity.post, opportunity.comments, null, engagementConfig?.providerId, engagementConfig?.model);
const result = await client.createComment(opportunity.post.id, generated.content);
comments.push({
@@ -483,7 +484,8 @@ router.post('/check-posts', asyncHandler(async (req, res) => {
if (!suspended && replied.length < data.maxReplies) {
const rateCheck = checkRateLimit(client.apiKey, 'comment');
if (rateCheck.allowed) {
- const generated = await generateReply(agent, post, comment, null, agent.aiConfig?.providerId, agent.aiConfig?.model);
+ const engagementConfig = agent.aiConfig?.engagement || agent.aiConfig;
+ const generated = await generateReply(agent, post, comment, null, engagementConfig?.providerId, engagementConfig?.model);
const replyResult = await client.replyToComment(postId, comment.id, generated.content).catch(e => {
if (isAccountSuspended(e)) suspended = true;
else console.log(`👀 Reply failed on post ${postId}: ${e.message}`);
diff --git a/server/services/agentActionExecutor.js b/server/services/agentActionExecutor.js
index 06a8d32371..dd3eadf600 100644
--- a/server/services/agentActionExecutor.js
+++ b/server/services/agentActionExecutor.js
@@ -74,7 +74,8 @@ async function executePost(client, agent, params) {
// AI generate if content not provided
if ((!title || !content) && aiGenerate !== false) {
console.log(`🤖 AI generating post content for "${agent.name}"`);
- const generated = await generatePost(agent, { submolt }, agent.aiConfig?.providerId, agent.aiConfig?.model);
+ const contentConfig = agent.aiConfig?.content || agent.aiConfig;
+ const generated = await generatePost(agent, { submolt }, contentConfig?.providerId, contentConfig?.model);
title = generated.title;
content = generated.content;
}
@@ -113,10 +114,12 @@ async function executeComment(client, agent, params) {
const pick = opportunities[0];
postId = pick.post.id;
+ const contentConfig = agent.aiConfig?.content || agent.aiConfig;
+
// AI generate comment if no content
if (!content) {
console.log(`🤖 AI generating comment for "${agent.name}" on post ${postId}`);
- const generated = await generateComment(agent, pick.post, pick.comments, null, agent.aiConfig?.providerId, agent.aiConfig?.model);
+ const generated = await generateComment(agent, pick.post, pick.comments, null, contentConfig?.providerId, contentConfig?.model);
content = generated.content;
}
} else if (!content) {
@@ -125,18 +128,19 @@ async function executeComment(client, agent, params) {
const post = await client.getPost(postId);
const commentsResponse = await client.getComments(postId);
const comments = commentsResponse.comments || commentsResponse || [];
+ const contentConfig = agent.aiConfig?.content || agent.aiConfig;
if (parentId) {
const parent = comments.find(c => c.id === parentId);
if (parent) {
- const generated = await generateReply(agent, post, parent, null, agent.aiConfig?.providerId, agent.aiConfig?.model);
+ const generated = await generateReply(agent, post, parent, null, contentConfig?.providerId, contentConfig?.model);
content = generated.content;
} else {
- const generated = await generateComment(agent, post, comments, null, agent.aiConfig?.providerId, agent.aiConfig?.model);
+ const generated = await generateComment(agent, post, comments, null, contentConfig?.providerId, contentConfig?.model);
content = generated.content;
}
} else {
- const generated = await generateComment(agent, post, comments, null, agent.aiConfig?.providerId, agent.aiConfig?.model);
+ const generated = await generateComment(agent, post, comments, null, contentConfig?.providerId, contentConfig?.model);
content = generated.content;
}
}
@@ -208,6 +212,8 @@ async function executeVote(client, params) {
async function executeEngage(client, agent, params) {
const { maxComments = 1, maxVotes = 3 } = params;
+ const engagementConfig = agent.aiConfig?.engagement || agent.aiConfig;
+
console.log(`🤝 Starting engage for "${agent.name}" (maxComments=${maxComments}, maxVotes=${maxVotes})`);
const relevantPosts = await findRelevantPosts(client, agent, {
@@ -250,7 +256,7 @@ async function executeEngage(client, agent, params) {
const rateCheck = checkRateLimit(client.apiKey, 'comment');
if (!rateCheck.allowed) break;
- const generated = await generateComment(agent, opportunity.post, opportunity.comments, null, agent.aiConfig?.providerId, agent.aiConfig?.model);
+ const generated = await generateComment(agent, opportunity.post, opportunity.comments, null, engagementConfig?.providerId, engagementConfig?.model);
await client.createComment(opportunity.post.id, generated.content).catch(e => {
if (isAccountSuspended(e)) suspended = true;
});
@@ -286,6 +292,8 @@ async function executeEngage(client, agent, params) {
async function executeMonitor(client, agent, schedule, params) {
const { days = 7, maxReplies = 2, maxUpvotes = 10 } = params;
+ const engagementConfig = agent.aiConfig?.engagement || agent.aiConfig;
+
console.log(`👀 Starting monitor for "${agent.name}" (days=${days}, maxReplies=${maxReplies}, maxUpvotes=${maxUpvotes})`);
const account = await platformAccounts.getAccountWithCredentials(schedule.accountId);
@@ -342,7 +350,7 @@ async function executeMonitor(client, agent, schedule, params) {
if (!suspended && replied.length < maxReplies) {
const rateCheck = checkRateLimit(client.apiKey, 'comment');
if (rateCheck.allowed) {
- const generated = await generateReply(agent, post, comment, null, agent.aiConfig?.providerId, agent.aiConfig?.model);
+ const generated = await generateReply(agent, post, comment, null, engagementConfig?.providerId, engagementConfig?.model);
await client.replyToComment(postId, comment.id, generated.content).catch(e => {
if (isAccountSuspended(e)) suspended = true;
});