Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

feat(slack): autonomous request protocol + poller dedup for Slack-origin work

Chaitanya Giri4a6b4fdd64c3
diff --git a/src/main/hive.ts b/src/main/hive.ts
index 07f2820e..4c0724bb 100644
--- a/src/main/hive.ts
+++ b/src/main/hive.ts
@@ -557,7 +557,7 @@ export class HiveManager {
const guardrailsLine = 'Guardrails: a circuit breaker watches the floor — a "Circuit breaker: steer/constrain" message means you are looping or overspending, so STOP repeating, summarize what you tried, and follow it. Be token-frugal (a floor-wide or per-agent token budget can pause you). The shared plan has two parts: board.md (freeform; god is the sole scribe) and tasks.json (structured kanban — todo/doing/blocked/done).';
const slackLine = meta.isGod
? 'SLACK REPLIES: When composing a Slack reply (or writing the `result` field of a Slack-origin kanban card), you MUST: (1) directly address what the user asked — never a bare "done"; (2) include the relevant specifics, outcome, and details; (3) format for Slack mrkdwn — open with a short *bold* headline, use bullet points for multiple items, wrap code/paths in `backtick` blocks, keep it concise (no walls of text). When finishing a Slack-origin task, always write a complete, user-facing, well-formatted `result` on the kanban card — the system posts it verbatim to Slack as the done reply.'
- : '';
+ : 'SLACK REPLIES: If god dispatches you a task that came from Slack, it will include an exact `node "<helper>" --channel … --thread … --text "…"` reply command — when you finish, run it to post your result back to that thread yourself. The reply must be SUBSTANTIVE Slack mrkdwn (a short *bold* headline + the actual outcome/specifics/links), NEVER a bare "done".';
return [
`You are "${meta.name}" (${meta.id}), an autonomous agent in a collaborating hive of Claude agents.`,
`Your private workspace is ${dir}. The shared hive is ${root}. Full protocol: ${root}/PROTOCOL.md.`,
diff --git a/src/main/index.ts b/src/main/index.ts
index 2cb876eb..d868dcc5 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -589,14 +589,26 @@ let slackReplyServer: SlackReplyServer | null = null;
* Request URL after a reopen (Slack reuses it until the server is stopped). */
let lastSlackUrl: string | undefined;
-/** Fixed policy preamble prepended (server-side, authoritatively) to the working
- * instruction god reads for any Slack-origin request. It tells god there is no
- * interactive human at the keyboard: act autonomously, pausing only for the
- * enumerated high-severity actions, and route genuine decisions back as a Slack
- * reply. This is prepended to god's PROMPT only — the human-facing kanban card
- * TITLE stays the user's raw text (the renderer keeps them split). Trailing
- * space is intentional so the user's message reads naturally after it. */
-const SLACK_AUTONOMY_PREAMBLE = `[SLACK-ORIGIN REQUEST — AUTONOMOUS MODE] This task arrived via Slack; there is no interactive human at the keyboard. Do NOT ask interactive questions and do NOT wait on the human — execute it autonomously end to end, doing reads and normal work freely. PAUSE and ask ONLY for these HIGH-SEVERITY actions: (1) pushing to main or any remote, (2) buying or spawning infrastructure or paid services, (3) deleting an existing repo, file, or folder you did NOT create. For critical infrastructure and git-push-type changes, stay READ-ONLY unless explicitly approved. If a genuine DECISION is needed to proceed, do NOT block: complete everything you safely can, then ASK YOUR QUESTION AS THE SLACK REPLY — phrase it clearly with explicit numbered OPTIONS — using the Slack reply helper, and record it on this task's humanQA as {q, options, askedAt (ISO + human-readable day & time), thread_ts}. When a later Slack message arrives in a thread that already has a pending recorded question (match by thread_ts), treat it as the answer and resume. The user's message starts now: `;
+/** AUTONOMOUS REQUEST PROTOCOL — built PER MESSAGE (not a static const) so it can
+ * embed the request's concrete `channel`, `thread_ts`, and the resolved helper
+ * path. Prepended (server-side, authoritatively) to the working instruction god
+ * reads for any Slack-origin request: there is no interactive human at the
+ * keyboard, so god must route fast, delegate WITH the exact reply command (so the
+ * worker posts its real result back into THIS thread itself), stay autonomous,
+ * and only block on enumerated high-severity actions. Prepended to god's PROMPT
+ * only — the human-facing kanban card TITLE stays the user's raw text (the
+ * renderer keeps them split). Trailing space is intentional so the user's message
+ * reads naturally after it. */
+function buildAutonomousRequestProtocol(channel: string, threadTs: string, helperPath: string): string {
+ return `[AUTONOMOUS REQUEST PROTOCOL — this request arrived via Slack; no interactive human is watching] Handle it under this protocol:
+1. ROUTE FAST — triage and hand this to the single most-relevant agent right away (decompose only if it genuinely needs several). Don't sit on it.
+2. DELEGATE WITH THE REPLY HANDLE — tell that agent to do the work autonomously AND to post its result back to THIS Slack thread itself when done, using exactly: node "${helperPath}" --channel ${channel} --thread ${threadTs} --text "<substantive result>"
+3. AUTONOMOUS EXECUTION — no interactive questions. PAUSE/ask ONLY for high-severity actions: pushing to main or any remote; buying or spawning infrastructure or paid services; deleting an existing repo, file, or folder it did not create. Stay READ-ONLY at critical infrastructure and git-push-type changes unless explicitly approved.
+4. DIRECT, SUBSTANTIVE REPLY — the agent posts a real Slack-mrkdwn answer (short *bold* headline + the actual outcome/specifics/links), NEVER a bare "done"/":white_check_mark:".
+5. REPORT TO GOD — the agent then tells you (Michael) what it did.
+6. ASYNC QUESTIONS — if a decision is genuinely needed, don't block: post the question + numbered OPTIONS to the thread via that reply command, and record {q, options, askedAt (ISO + day & time), thread_ts ${threadTs}} so the threaded human reply correlates back and resumes.
+The user's message starts now: `;
+}
// ─── Slack done-notifier (Slack-origin task → done → one summary reply) ───────
/** Polls the shared kanban (hive/tasks.json) for Slack-origin tasks that reach
@@ -611,6 +623,11 @@ let slackDoneNotified: Set<string> | null = null;
/** Ids already 'done' when the observer started — baselined (never notified) so a
* summary only ever fires on a live …→done transition, not on pre-existing dones. */
let slackDoneBaseline: Set<string> | null = null;
+/** thread_ts values an agent has ALREADY answered directly via the loopback
+ * `/reply` endpoint. The done-summary poller skips these — the agent's own
+ * substantive reply already landed in-thread, so the poller is a fallback, not a
+ * duplicator (this is what stops the bare/duplicate `:white_check_mark:` posts). */
+const directlyRepliedThreads = new Set<string>();
/** Absolute path to the bundled `md-slack-reply.cjs` helper. Packaged: under
* `process.resourcesPath` (electron-builder extraResources). Dev: the repo's
@@ -799,6 +816,13 @@ async function pollSlackDoneTasks(): Promise<void> {
if (baseline.has(t.id) || notified.has(t.id)) continue; // already handled
const slack = t.slack;
if (!slack || !slack.channel || !slack.thread_ts) continue; // non-Slack-origin → leave alone
+ // FALLBACK-ONLY: if the agent already posted a DIRECT reply into this thread
+ // (loopback /reply), the human has its substantive answer — don't double-post.
+ if (directlyRepliedThreads.has(slack.thread_ts)) { notified.add(t.id); persistSlackDoneNotified(notified); continue; }
+ // Never post a bare `:white_check_mark: *title*` with no substance: if the card
+ // carries neither a result nor a description, there is nothing meaningful to
+ // deliver — skip it (still under the FALLBACK contract).
+ if (!(t.result ?? t.description ?? '').trim()) { notified.add(t.id); persistSlackDoneNotified(notified); continue; }
const res = await postSlackReply({
botToken, channel: slack.channel, thread_ts: slack.thread_ts, text: slackDoneSummary(t)
});
@@ -863,10 +887,13 @@ async function startSlackServer(): Promise<{ ok: boolean; url?: string; error?:
// `text` stays the user's RAW Slack text → drives the readable kanban card
// title. `autonomyPreamble` is the authoritative policy block the renderer
// prepends ONLY to god's working instruction (his PTY prompt), keeping the
- // card title human-facing-clean. Server-side so it applies to every session.
+ // card title human-facing-clean. Built PER MESSAGE so the AUTONOMOUS REQUEST
+ // PROTOCOL carries THIS request's concrete channel, thread_ts, and the
+ // resolved helper path — god hands the worker an exact reply command.
+ // Server-side so it applies to every session.
const ipcMsg: { text: string; channel: string; ts: string; thread_ts: string; autonomyPreamble: string; files?: typeof localFiles } = {
text: m.text, channel: m.channel, ts: m.ts, thread_ts: m.thread_ts,
- autonomyPreamble: SLACK_AUTONOMY_PREAMBLE
+ autonomyPreamble: buildAutonomousRequestProtocol(m.channel, m.thread_ts, slackReplyScriptPath())
};
if (localFiles.length > 0) ipcMsg.files = localFiles;
try { liveWebContents()?.send('slack:incomingMessage', ipcMsg); }
@@ -896,7 +923,10 @@ async function startSlackReplyServer(): Promise<void> {
const token = randomBytes(24).toString('hex');
slackReplyServer = new SlackReplyServer({
token,
- getBotToken: () => readConfig().slackBotToken
+ getBotToken: () => readConfig().slackBotToken,
+ // An agent posted a DIRECT substantive reply into this thread → record it so the
+ // done-summary poller skips it (the poller is a fallback, not a duplicator).
+ onReplied: (thread_ts) => { directlyRepliedThreads.add(thread_ts); }
});
const r = await slackReplyServer.start();
if (!r.ok || r.port === undefined) {
diff --git a/src/main/slack.ts b/src/main/slack.ts
index fb033784..062bee15 100644
--- a/src/main/slack.ts
+++ b/src/main/slack.ts
@@ -365,6 +365,10 @@ export interface SlackReplyServerOptions {
token: string;
/** Latest bot token, read lazily so a config change is picked up at reply time. */
getBotToken: () => string | undefined;
+ /** Fired with a thread_ts after an agent's DIRECT reply posts successfully through
+ * this loopback. Lets main record that the thread was already answered so the
+ * done-summary poller can skip it (the poller is a fallback, not a duplicator). */
+ onReplied?: (thread_ts: string) => void;
}
/**
@@ -380,10 +384,12 @@ export class SlackReplyServer {
private server: Server | null = null;
private readonly token: string;
private readonly getBotToken: () => string | undefined;
+ private readonly onReplied?: (thread_ts: string) => void;
constructor(opts: SlackReplyServerOptions) {
this.token = opts.token;
this.getBotToken = opts.getBotToken;
+ this.onReplied = opts.onReplied;
}
/** Bind a loopback port (0 ⇒ OS-assigned). Resolves the actual bound port. */
@@ -438,8 +444,14 @@ export class SlackReplyServer {
if (!parsed.channel || !parsed.thread_ts || !parsed.text) {
res.writeHead(400); res.end(JSON.stringify({ ok: false, error: 'channel, thread, text required' })); return;
}
- postSlackReply({ botToken, channel: parsed.channel, thread_ts: parsed.thread_ts, text: parsed.text })
- .then((r) => { res.writeHead(r.ok ? 200 : 502, { 'content-type': 'application/json' }); res.end(JSON.stringify(r)); })
+ const thread_ts = parsed.thread_ts;
+ postSlackReply({ botToken, channel: parsed.channel, thread_ts, text: parsed.text })
+ .then((r) => {
+ // A successful DIRECT reply means the agent already answered this thread —
+ // tell main so the done-summary poller treats it as a fallback and skips it.
+ if (r.ok) { try { this.onReplied?.(thread_ts); } catch { /* never break the reply */ } }
+ res.writeHead(r.ok ? 200 : 502, { 'content-type': 'application/json' }); res.end(JSON.stringify(r));
+ })
.catch((e) => { res.writeHead(500); res.end(JSON.stringify({ ok: false, error: errMsg(e) })); });
});
req.on('error', () => { if (!aborted) { try { res.writeHead(400); res.end(); } catch { /* socket gone */ } } });