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(cos): add BTW messaging for running agents

Adam Eivy7b7b2d34653d
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index acb1cf7d89..bfa450aa47 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -13,7 +13,8 @@ import {
ThumbsUp,
ThumbsDown,
MessageSquare,
- ExternalLink
+ ExternalLink,
+ Send
} from 'lucide-react';
import * as api from '../../../services/api';
import OutputBlocks from '../OutputBlocks';
@@ -96,11 +97,19 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
const [processStats, setProcessStats] = useState(null);
const [killing, setKilling] = useState(false);
const [feedbackState, setFeedbackState] = useState(agent.feedback?.rating || null);
+ const [btwInput, setBtwInput] = useState('');
+ const [sendingBtw, setSendingBtw] = useState(false);
+ const [btwMessages, setBtwMessages] = useState(agent.btwMessages || []);
// Sync feedback state when parent refreshes agent data
useEffect(() => {
if (agent.feedback?.rating) setFeedbackState(agent.feedback.rating);
}, [agent.feedback?.rating]);
+
+ // Sync btw messages from parent when agent data refreshes
+ useEffect(() => {
+ if (agent.btwMessages?.length) setBtwMessages(agent.btwMessages);
+ }, [agent.btwMessages]);
const [submittingFeedback, setSubmittingFeedback] = useState(false);
const [showFeedbackComment, setShowFeedbackComment] = useState(false);
const [feedbackComment, setFeedbackComment] = useState('');
@@ -132,6 +141,25 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
}
}, [agent.id, feedbackComment, submittingFeedback, onFeedbackChange]);
+ // Send BTW message to running agent
+ const sendBtw = useCallback(async () => {
+ if (sendingBtw || !btwInput.trim()) return;
+ setSendingBtw(true);
+
+ const result = await api.sendCosAgentBtw(agent.id, btwInput.trim()).catch(err => {
+ toast.error(`Failed to send: ${err.message}`);
+ return null;
+ });
+
+ setSendingBtw(false);
+
+ if (result?.success) {
+ setBtwMessages(prev => [...prev, { message: btwInput.trim(), timestamp: new Date().toISOString() }]);
+ setBtwInput('');
+ toast.success('BTW message sent to agent');
+ }
+ }, [agent.id, btwInput, sendingBtw]);
+
// Update duration display for running agents
useEffect(() => {
if (completed) return;
@@ -457,6 +485,46 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
</div>
)}
+ {/* BTW messages sent to this agent */}
+ {btwMessages.length > 0 && (
+ <div className="mt-2 space-y-1">
+ {btwMessages.map((btw, i) => (
+ <div key={i} className="flex items-start gap-2 text-xs bg-yellow-500/10 border border-yellow-500/20 rounded px-2 py-1.5">
+ <MessageSquare size={12} className="text-yellow-400 shrink-0 mt-0.5" aria-hidden="true" />
+ <div className="min-w-0">
+ <span className="text-yellow-400">BTW:</span>{' '}
+ <span className="text-gray-300">{btw.message}</span>
+ <span className="text-gray-600 ml-2">{new Date(btw.timestamp).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })}</span>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {!completed && !remote && (
+ <div className="mt-2 flex gap-2">
+ <input
+ type="text"
+ value={btwInput}
+ onChange={(e) => setBtwInput(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && !e.shiftKey && sendBtw()}
+ placeholder="Send additional context to agent..."
+ className="flex-1 px-2 py-1 text-sm bg-port-bg border border-port-border rounded text-white placeholder-gray-600 focus:outline-hidden focus:border-yellow-500/50 min-h-[32px]"
+ maxLength={5000}
+ disabled={sendingBtw}
+ />
+ <button
+ onClick={sendBtw}
+ disabled={sendingBtw || !btwInput.trim()}
+ className="flex items-center gap-1.5 px-3 py-1 text-xs bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 rounded transition-colors disabled:opacity-50 min-h-[32px]"
+ title="Send BTW message to agent"
+ >
+ {sendingBtw ? <Loader2 size={12} className="animate-spin" aria-hidden="true" /> : <Send size={12} aria-hidden="true" />}
+ BTW
+ </button>
+ </div>
+ )}
+
{/* Progress bar and ETA for running agents with estimates */}
{!completed && durationEstimate && progress !== null && (
<div className="mt-2">
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 963ba509aa..7afb361c1c 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -684,6 +684,10 @@ export const submitCosAgentFeedback = (id, feedback) => request(`/cos/agents/${i
method: 'POST',
body: JSON.stringify(feedback)
});
+export const sendCosAgentBtw = (id, message) => request(`/cos/agents/${id}/btw`, {
+ method: 'POST',
+ body: JSON.stringify({ message })
+});
export const getCosFeedbackStats = () => request('/cos/feedback/stats');
export const getCosReports = () => request('/cos/reports');
export const getCosTodayReport = () => request('/cos/reports/today');
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index 863517447d..606bca814c 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -683,6 +683,45 @@ app.post('/terminate-all', async (req, res) => {
res.json({ success: true, killed: agentIds.length });
});
+/**
+ * Send a BTW (additional context) message to a running agent.
+ * Writes the message to a BTW.md file in the agent's workspace so the
+ * agent can discover it during file operations.
+ */
+app.post('/btw/:agentId', async (req, res) => {
+ const { agentId } = req.params;
+ const { message, workspacePath } = req.body;
+ const agent = activeAgents.get(agentId);
+
+ if (!agent) {
+ return res.status(404).json({ error: 'Agent not found or not running' });
+ }
+
+ if (!message || typeof message !== 'string') {
+ return res.status(400).json({ error: 'Missing or invalid message' });
+ }
+
+ if (!workspacePath || typeof workspacePath !== 'string') {
+ return res.status(400).json({ error: 'Missing workspacePath' });
+ }
+
+ const timestamp = new Date().toISOString();
+ const entry = `\n---\n**[${timestamp}]** ${message}\n`;
+ const btwPath = join(workspacePath, 'BTW.md');
+
+ // Append to BTW.md (create if first message)
+ const existing = await readFile(btwPath, 'utf-8').catch(() => '');
+ const header = existing ? '' : '# Additional Context from User\n\nThe user has sent you additional context while you are working. Read and incorporate this information.\n';
+ await writeFile(btwPath, header + existing + entry);
+
+ console.log(`💬 BTW message delivered to agent ${agentId}: ${message.substring(0, 80)}`);
+
+ // Emit the btw event so the main server can track it
+ emitToServer('agent:btw', { agentId, message, timestamp });
+
+ res.json({ success: true, agentId, btwPath });
+});
+
/**
* Get agent output
*/
diff --git a/server/routes/cos.js b/server/routes/cos.js
index 3139973af0..73602c5140 100644
--- a/server/routes/cos.js
+++ b/server/routes/cos.js
@@ -378,6 +378,29 @@ router.post('/agents/:id/feedback', asyncHandler(async (req, res) => {
res.json(result);
}));
+// POST /api/cos/agents/:id/btw - Send additional context to a running agent
+router.post('/agents/:id/btw', asyncHandler(async (req, res) => {
+ const { message } = req.body;
+
+ if (!message || typeof message !== 'string' || message.trim().length === 0) {
+ throw new ServerError('message is required and must be a non-empty string', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+
+ if (message.length > 5000) {
+ throw new ServerError('message must be 5000 characters or less', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+
+ const result = await cos.sendBtwToAgent(req.params.id, message.trim());
+ if (result?.error) {
+ const isNotFound = result.error === 'Agent not found';
+ throw new ServerError(result.error, {
+ status: isNotFound ? 404 : 400,
+ code: isNotFound ? 'NOT_FOUND' : 'INVALID_STATE'
+ });
+ }
+ res.json(result);
+}));
+
// GET /api/cos/feedback/stats - Get feedback statistics
router.get('/feedback/stats', asyncHandler(async (req, res) => {
const stats = await cos.getFeedbackStats();
diff --git a/server/services/cos.js b/server/services/cos.js
index e11d8b1bd3..001c622f33 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -2528,6 +2528,46 @@ export async function killAgent(agentId) {
return killAgentFromSpawner(agentId);
}
+/**
+ * Send a BTW (additional context) message to a running agent.
+ * Writes the message to a file in the agent's workspace and tracks it in state.
+ */
+export async function sendBtwToAgent(agentId, message) {
+ // Single locked read to validate agent and extract workspacePath
+ const agentInfo = await withStateLock(async () => {
+ const state = await loadState();
+ const agent = state.agents[agentId];
+ if (!agent) return { error: 'Agent not found' };
+ if (agent.status !== 'running') return { error: 'Agent is not running' };
+ if (!agent.metadata?.workspacePath) return { error: 'Agent has no workspace path' };
+ return { workspacePath: agent.metadata.workspacePath };
+ });
+
+ if (agentInfo.error) return agentInfo;
+
+ // Send to runner to write the BTW.md file
+ const { sendBtwToAgent: sendViaRunner } = await import('./cosRunnerClient.js');
+ const result = await sendViaRunner(agentId, message, agentInfo.workspacePath);
+
+ // Track in agent state (cap at 50 messages)
+ const timestamp = new Date().toISOString();
+ await withStateLock(async () => {
+ const state = await loadState();
+ if (!state.agents[agentId]) return;
+ if (!state.agents[agentId].btwMessages) {
+ state.agents[agentId].btwMessages = [];
+ }
+ state.agents[agentId].btwMessages.push({ message, timestamp });
+ if (state.agents[agentId].btwMessages.length > 50) {
+ state.agents[agentId].btwMessages = state.agents[agentId].btwMessages.slice(-50);
+ }
+ await saveState(state);
+ });
+
+ cosEvents.emit('agent:btw', { agentId, message, timestamp });
+ return { success: true, ...result };
+}
+
/**
* Get process stats for an agent (CPU, memory)
*/
diff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.js
index 19a454be4e..5cc2130fa9 100644
--- a/server/services/cosRunnerClient.js
+++ b/server/services/cosRunnerClient.js
@@ -59,6 +59,11 @@ export function initCosRunnerConnection() {
if (handler) handler(data);
});
+ socket.on('agent:btw', (data) => {
+ const handler = eventHandlers.get('agent:btw');
+ if (handler) handler(data);
+ });
+
// Batch orphaned agents event (startup cleanup)
socket.on('agents:orphaned', (data) => {
const handler = eventHandlers.get('agents:orphaned');
@@ -215,6 +220,22 @@ export async function terminateAllAgentsViaRunner() {
return response.json();
}
+/**
+ * Send a BTW (additional context) message to a running agent via the runner
+ */
+export async function sendBtwToAgent(agentId, message, workspacePath) {
+ const response = await fetchWithTimeout(`${COS_RUNNER_URL}/btw/${agentId}`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ message, workspacePath }),
+ }, 30000);
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to send BTW message');
+ }
+ return response.json();
+}
+
/**
* Get agent output from runner
*/
diff --git a/server/services/socket.js b/server/services/socket.js
index 4a262d7a01..eb40b9d7c6 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -549,6 +549,7 @@ function setupCosEventForwarding() {
cosEvents.on('agent:updated', (data) => broadcastToCos('cos:agent:updated', data));
cosEvents.on('agent:completed', (data) => broadcastToCos('cos:agent:completed', data));
cosEvents.on('agent:output', (data) => broadcastToCos('cos:agent:output', data));
+ cosEvents.on('agent:btw', (data) => broadcastToCos('cos:agent:btw', data));
// Memory events
cosEvents.on('memory:created', (data) => broadcastToCos('cos:memory:created', data));
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index f303a99d6d..15c5386605 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -2804,6 +2804,7 @@ ${skillSection ? `## Task-Type Skill Guidelines\n\n${skillSection}\n` : ''}${pla
- Do not make unrelated changes
- If blocked, explain clearly why
- Never update the PortOS changelog (\`.changelog/\`) for work on managed apps — the PortOS changelog tracks PortOS core changes only
+- **BTW Messages**: The user may send you additional context while you work. Check for a \`BTW.md\` file in your working directory root — if it exists, read it for important messages from the user. Incorporate that context into your work. Do not delete or modify BTW.md.
${task.metadata?.app && worktreeInfo && willOpenPR ? `- Commit code after each feature or bug fix using the git tools or /cam skill. A pull request will be automatically created when your task completes — do NOT open a PR manually.` : task.metadata?.app && worktreeInfo ? `- Commit code after each feature or bug fix using the git tools or /cam skill. Your worktree branch will be automatically merged back to the source branch when your task completes — do NOT open a PR.` : `- Commit code after each feature or bug fix using the git tools or /cam skill`}
## Git Hygiene (CRITICAL)