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
HTML agent-harnessagent-orchestrationagentsai-agentsautonomous-agentsclaude-codecodexcoding-agentsdesktop-appdeveloper-toolselectrongemini-cliharnessharness-engineeringlocal-firstmemorymulti-agentopencodeorchestrationtypescript
feat(slack): pipe Slack channel messages into Michael's queue
Chaitanya Girid179a9a67062
diff --git a/package-lock.json b/package-lock.jsonindex 503e8034..7df58571 100644--- a/package-lock.json+++ b/package-lock.json@@ -24,6 +24,7 @@"@xterm/addon-fit": "^0.10.0","@xterm/xterm": "^5.5.0","commit-graph": "^2.4.0",+ "localtunnel": "^2.0.2","node-pty": "^1.0.0","pixi.js": "^8.5.1","react": "^18.3.1",@@ -33,6 +34,7 @@"devDependencies": {"@electron/notarize": "^2.5.0","@electron/rebuild": "^3.7.0",+ "@types/localtunnel": "^2.0.4","@types/node": "^22.7.5","@types/react": "^18.3.11","@types/react-dom": "^18.3.0",@@ -2284,6 +2286,16 @@"@types/node": "*"}},+ "node_modules/@types/localtunnel": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/@types/localtunnel/-/localtunnel-2.0.4.tgz",+ "integrity": "sha512-7WM5nlEfEKp8MpwthPa2utdy+f/7ZBxMPzu8qw6EijFFTcpzh5CXgt2YoncxWAZNOPNieMofXCKFudtDEY4bag==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@types/ms": {"version": "2.1.0","resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",@@ -2559,7 +2571,6 @@"version": "5.0.1","resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz","integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",- "dev": true,"license": "MIT","engines": {"node": ">=8"@@ -2569,7 +2580,6 @@"version": "4.3.0","resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz","integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",- "dev": true,"license": "MIT","dependencies": {"color-convert": "^2.0.1"@@ -2968,6 +2978,15 @@"node": ">= 4.0.0"}},+ "node_modules/axios": {+ "version": "0.21.4",+ "resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz",+ "integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==",+ "license": "MIT",+ "dependencies": {+ "follow-redirects": "^1.14.0"+ }+ },"node_modules/balanced-match": {"version": "1.0.2","resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",@@ -3529,7 +3548,6 @@"version": "2.0.1","resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz","integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",- "dev": true,"license": "MIT","dependencies": {"color-name": "~1.1.4"@@ -3542,7 +3560,6 @@"version": "1.1.4","resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz","integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",- "dev": true,"license": "MIT"},"node_modules/color-support": {@@ -4355,7 +4372,6 @@"version": "8.0.0","resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz","integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",- "dev": true,"license": "MIT"},"node_modules/encoding": {@@ -4496,7 +4512,6 @@"version": "3.2.0","resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz","integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",- "dev": true,"license": "MIT","engines": {"node": ">=6"@@ -4595,6 +4610,26 @@"minimatch": "^5.0.1"}},+ "node_modules/follow-redirects": {+ "version": "1.16.0",+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz",+ "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==",+ "funding": [+ {+ "type": "individual",+ "url": "https://github.com/sponsors/RubenVerborgh"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=4.0"+ },+ "peerDependenciesMeta": {+ "debug": {+ "optional": true+ }+ }+ },"node_modules/foreground-child": {"version": "3.3.1","resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz",@@ -4745,7 +4780,6 @@"version": "2.0.5","resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz","integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",- "dev": true,"license": "ISC","engines": {"node": "6.* || 8.* || >= 10.*"@@ -5232,7 +5266,6 @@"version": "3.0.0","resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz","integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",- "dev": true,"license": "MIT","engines": {"node": ">=8"@@ -5486,6 +5519,85 @@"safe-buffer": "~5.1.0"}},+ "node_modules/localtunnel": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/localtunnel/-/localtunnel-2.0.2.tgz",+ "integrity": "sha512-n418Cn5ynvJd7m/N1d9WVJISLJF/ellZnfsLnx8WBWGzxv/ntNcFkJ1o6se5quUhCplfLGBNL5tYHiq5WF3Nug==",+ "license": "MIT",+ "dependencies": {+ "axios": "0.21.4",+ "debug": "4.3.2",+ "openurl": "1.1.1",+ "yargs": "17.1.1"+ },+ "bin": {+ "lt": "bin/lt.js"+ },+ "engines": {+ "node": ">=8.3.0"+ }+ },+ "node_modules/localtunnel/node_modules/cliui": {+ "version": "7.0.4",+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz",+ "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==",+ "license": "ISC",+ "dependencies": {+ "string-width": "^4.2.0",+ "strip-ansi": "^6.0.0",+ "wrap-ansi": "^7.0.0"+ }+ },+ "node_modules/localtunnel/node_modules/debug": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz",+ "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==",+ "license": "MIT",+ "dependencies": {+ "ms": "2.1.2"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/localtunnel/node_modules/ms": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",+ "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==",+ "license": "MIT"+ },+ "node_modules/localtunnel/node_modules/yargs": {+ "version": "17.1.1",+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.1.1.tgz",+ "integrity": "sha512-c2k48R0PwKIqKhPMWjeiF6y2xY/gPMUlro0sgxqXpbOIohWiLNXWslsootttv7E1e73QPAMQSg5FeySbVcpsPQ==",+ "license": "MIT",+ "dependencies": {+ "cliui": "^7.0.2",+ "escalade": "^3.1.1",+ "get-caller-file": "^2.0.5",+ "require-directory": "^2.1.1",+ "string-width": "^4.2.0",+ "y18n": "^5.0.5",+ "yargs-parser": "^20.2.2"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/localtunnel/node_modules/yargs-parser": {+ "version": "20.2.9",+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz",+ "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==",+ "license": "ISC",+ "engines": {+ "node": ">=10"+ }+ },"node_modules/lodash": {"version": "4.18.1","resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",@@ -6156,6 +6268,12 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/openurl": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/openurl/-/openurl-1.1.1.tgz",+ "integrity": "sha512-d/gTkTb1i1GKz5k3XE3XFV/PxQ1k45zDqGP2OA7YhgsaLoqm6qRvARAZOFer1fcXritWlGBRCu/UgeS4HAnXAA==",+ "license": "MIT"+ },"node_modules/ora": {"version": "5.4.1","resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz",@@ -6624,7 +6742,6 @@"version": "2.1.1","resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz","integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",- "dev": true,"license": "MIT","engines": {"node": ">=0.10.0"@@ -7107,7 +7224,6 @@"version": "4.2.3","resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz","integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",- "dev": true,"license": "MIT","dependencies": {"emoji-regex": "^8.0.0",@@ -7138,7 +7254,6 @@"version": "6.0.1","resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz","integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",- "dev": true,"license": "MIT","dependencies": {"ansi-regex": "^5.0.1"@@ -7592,7 +7707,6 @@"version": "7.0.0","resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz","integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",- "dev": true,"license": "MIT","dependencies": {"ansi-styles": "^4.0.0",@@ -7646,7 +7760,6 @@"version": "5.0.8","resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz","integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",- "dev": true,"license": "ISC","engines": {"node": ">=10"diff --git a/package.json b/package.jsonindex ff858003..15df98f4 100644--- a/package.json+++ b/package.json@@ -39,6 +39,7 @@"@xterm/addon-fit": "^0.10.0","@xterm/xterm": "^5.5.0","commit-graph": "^2.4.0",+ "localtunnel": "^2.0.2","node-pty": "^1.0.0","pixi.js": "^8.5.1","react": "^18.3.1",@@ -48,6 +49,7 @@"devDependencies": {"@electron/notarize": "^2.5.0","@electron/rebuild": "^3.7.0",+ "@types/localtunnel": "^2.0.4","@types/node": "^22.7.5","@types/react": "^18.3.11","@types/react-dom": "^18.3.0",diff --git a/src/main/config.ts b/src/main/config.tsindex aa712955..3e5e83e8 100644--- a/src/main/config.ts+++ b/src/main/config.ts@@ -34,6 +34,16 @@ export interface HarnessConfig {missions?: ScheduledMission[];/** Fire native desktop notifications on agent lifecycle events (idle finish / waiting for input). */notifications?: boolean;+ /** Master toggle for the Slack → Michael's-queue integration. */+ slackEnabled?: boolean;+ /** Slack app signing secret (Basic Information → Signing Secret). Never logged. */+ slackSigningSecret?: string;+ /** Bot token (xoxb-…) — only needed if the bot ever replies; optional for now. */+ slackBotToken?: string;+ /** Restrict ingestion to one channel id; empty/undefined = any channel. */+ slackChannelId?: string;+ /** Local HTTP port the webhook server binds to (default 3847). */+ slackPort?: number;}const DEFAULTS: HarnessConfig = {@@ -45,7 +55,12 @@ const DEFAULTS: HarnessConfig = {semanticMemory: true,embeddingModel: 'minilm',missions: [],- notifications: false+ notifications: false,+ slackEnabled: false,+ slackSigningSecret: undefined,+ slackBotToken: undefined,+ slackChannelId: undefined,+ slackPort: undefined};function configPath(): string {diff --git a/src/main/index.ts b/src/main/index.tsindex 02966d0e..8782723e 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -18,6 +18,7 @@ import { MemoryManager } from './memory';import { enrichMessage } from './assistant';import { readAgentUsage } from './transcript';import { listIssues, listCIRuns } from './github';+import { SlackWebhookServer } from './slack';const isDev = !!process.env.ELECTRON_RENDERER_URL;const ptyManager = new PtyManager();@@ -153,6 +154,44 @@ function liveWebContents(): Electron.WebContents | null {return wc && !wc.isDestroyed() ? wc : null;}+// ─── Slack webhook server (Slack message → Michael's queue) ──────────────────+/** The running Slack ingestion server, or null when disabled/stopped. */+let slackServer: SlackWebhookServer | null = null;++/** Build a SlackWebhookServer from the current config and start it, replacing+ * any running instance, and return the start result (incl. the public tunnel+ * URL the user pastes into Slack). No-op + error result when the integration is+ * disabled or the signing secret is unset. */+async function startSlackServer(): Promise<{ ok: boolean; url?: string; error?: string }> {+ const cfg = readConfig();+ if (!cfg.slackEnabled || !cfg.slackSigningSecret) {+ return { ok: false, error: 'slack disabled or missing signing secret' };+ }+ slackServer?.stop();+ slackServer = new SlackWebhookServer({+ port: cfg.slackPort && cfg.slackPort > 0 ? cfg.slackPort : 3847,+ signingSecret: cfg.slackSigningSecret,+ channelId: cfg.slackChannelId,+ // Fires from the HTTP server's event loop (not the IPC thread); route through+ // liveWebContents() so a message arriving during window teardown can't throw.+ onMessage: (text) => {+ try { liveWebContents()?.send('slack:incomingMessage', { text }); }+ catch { /* window torn down */ }+ }+ });+ const res = await slackServer.start();+ // ok:false means we never bound the port → drop the instance. ok:true with no+ // url just means the tunnel is unavailable; the local handler is still live.+ if (!res.ok) slackServer = null;+ return res;+}++/** Stop and forget the Slack server. Best-effort; safe to call when not running. */+function stopSlackServer(): void {+ try { slackServer?.stop(); } catch (e) { console.error('[slack] stop failed:', e); }+ slackServer = null;+}+function createWindow(): void {const win = new BrowserWindow({width: 1440,@@ -435,6 +474,7 @@ ipcMain.handle('app:confirmClose', () => {try { clearMissionTimers(); } catch (e) { console.error('[quit] clearMissionTimers:', e); }try { hive.stopRouter(); } catch (e) { console.error('[quit] stopRouter:', e); }try { hookServer.stop(); } catch (e) { console.error('[quit] hookServer.stop:', e); }+ try { stopSlackServer(); } catch (e) { console.error('[quit] slack.stop:', e); }try { memory.stop(); } catch (e) { console.error('[quit] memory.stop:', e); }try { ptyManager.killAll(); } catch (e) { console.error('[quit] killAll:', e); }app.quit();@@ -450,6 +490,7 @@ ipcMain.handle('app:resetAll', () => {try { clearMissionTimers(); } catch (e) { console.error('[reset] clearMissionTimers:', e); }try { hive.stopRouter(); } catch (e) { console.error('[reset] stopRouter:', e); }try { hookServer.stop(); } catch (e) { console.error('[reset] hookServer.stop:', e); }+ try { stopSlackServer(); } catch (e) { console.error('[reset] slack.stop:', e); }try { memory.stop(); } catch (e) { console.error('[reset] memory.stop:', e); }try { ptyManager.killAll(); } catch (e) { console.error('[reset] killAll:', e); }// Erase the hive (Michael's + every agent's memory, inboxes, tasks, board,@@ -539,6 +580,29 @@ ipcMain.handle('github:ciRuns', (_evt, cwd: unknown) =>// ─── IPC: desktop notifications toggle ──────────────────────────────────────ipcMain.handle('app:setNotifications', (_evt, val) => writeConfig({ notifications: val === true }));+// ─── IPC: Slack integration ─────────────────────────────────────────────────+ipcMain.handle('slack:start', () => startSlackServer());+ipcMain.handle('slack:stop', () => { stopSlackServer(); return { ok: true }; });+ipcMain.handle('slack:setConfig', (_evt, patch: unknown) => {+ const p = (patch ?? {}) as {+ signingSecret?: unknown; botToken?: unknown; channelId?: unknown; port?: unknown; enabled?: unknown;+ };+ const next: Partial<HarnessConfig> = {};+ // Trim string fields; an emptied field clears back to undefined.+ if (typeof p.signingSecret === 'string') next.slackSigningSecret = p.signingSecret.trim() || undefined;+ if (typeof p.botToken === 'string') next.slackBotToken = p.botToken.trim() || undefined;+ if (typeof p.channelId === 'string') next.slackChannelId = p.channelId.trim() || undefined;+ if (typeof p.port === 'number' && Number.isFinite(p.port)) next.slackPort = p.port;+ if (typeof p.enabled === 'boolean') next.slackEnabled = p.enabled;+ writeConfig(next);+ // Reconcile the running server: disabling (or clearing the secret) stops it. We+ // deliberately do NOT auto-(re)start here — the user presses Start in Settings+ // to fetch the fresh (ephemeral) tunnel URL.+ const cfg = readConfig();+ if (!cfg.slackEnabled || !cfg.slackSigningSecret) stopSlackServer();+ return { ok: true };+});+app.whenReady().then(() => {// Bootstrap the hive (if harnessHome is configured) and start the message router.if (hive.enabled()) {@@ -549,6 +613,16 @@ app.whenReady().then(() => {memory.start(); // init shared palace + mine loop (no-op without mempalace)}createWindow();+ // Auto-start the Slack webhook server when configured. Best-effort: a tunnel+ // failure (offline) is logged, not fatal. The tunnel URL is ephemeral and+ // changes per restart, so the user re-pastes it via Settings → Start.+ const slackCfg = readConfig();+ if (slackCfg.slackEnabled && slackCfg.slackSigningSecret) {+ void startSlackServer().then((r) => {+ if (!r.ok) console.error('[slack] auto-start failed:', r.error);+ else console.log('[slack] webhook listening', r.url ? `(tunnel: ${r.url})` : '(no tunnel)');+ });+ }app.on('activate', () => {if (BrowserWindow.getAllWindows().length === 0) createWindow();});diff --git a/src/main/slack.ts b/src/main/slack.tsnew file mode 100644index 00000000..2e5f9cf3--- /dev/null+++ b/src/main/slack.ts@@ -0,0 +1,228 @@+/**+ * SlackWebhookServer — receive Slack messages and hand them to the harness.+ *+ * A bare `node:http` server (no @slack/bolt) that implements just enough of the+ * Slack Events API to let the user pipe a channel's messages into Michael's+ * message queue:+ * - verifies EVERY request with Slack's signing-secret HMAC over the RAW body+ * plus a 5-minute replay-timestamp guard (403 on any failure),+ * - answers the one-time `url_verification` challenge handshake,+ * - on a plain `message` event, strips a leading bot mention and emits the+ * text via `onMessage`.+ *+ * It also opens a `localtunnel` so the local port is reachable from Slack's+ * servers; the tunnel URL is what the user pastes into their Slack app's Event+ * Subscriptions → Request URL. The tunnel is best-effort: the local handler is+ * the security boundary and stays up even if the tunnel can't be established.+ *+ * Runs in the Electron main process. Deliberately free of any `electron`+ * import so it can be unit-/smoke-tested as a plain Node module.+ */+import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';+import { createHmac, timingSafeEqual } from 'node:crypto';+import localtunnel from 'localtunnel';++/** The live tunnel handle returned by localtunnel (has `url` + `close()` + EventEmitter). */+type Tunnel = Awaited<ReturnType<typeof localtunnel>>;++export interface SlackWebhookServerOptions {+ /** Local TCP port the HTTP server binds to (and the tunnel forwards to). */+ port: number;+ /** Slack app signing secret (Basic Information → Signing Secret). Required. */+ signingSecret: string;+ /** Optional channel id filter — when set, events from other channels are dropped. */+ channelId?: string;+ /** Called once per accepted, de-mentioned message body. */+ onMessage: (text: string) => void;+}++/** Reject request bodies larger than this — Slack event payloads are tiny; the+ * cap stops an unauthenticated peer from forcing unbounded memory use before+ * we've even checked the signature. */+const MAX_BODY_BYTES = 1024 * 1024; // 1 MB+/** Slack's recommended replay window: reject timestamps more than 5 min off. */+const REPLAY_WINDOW_SECONDS = 60 * 5;+/** Cap how long we wait for the public tunnel before giving up (server stays up). */+const TUNNEL_START_TIMEOUT_MS = 10_000;++export class SlackWebhookServer {+ private server: Server | null = null;+ private tunnel: Tunnel | null = null;+ private readonly port: number;+ private readonly signingSecret: string;+ private readonly channelId?: string;+ private readonly onMessage: (text: string) => void;++ constructor(opts: SlackWebhookServerOptions) {+ this.port = opts.port;+ this.signingSecret = opts.signingSecret;+ this.channelId = opts.channelId?.trim() || undefined;+ this.onMessage = opts.onMessage;+ }++ /**+ * Bind the local HTTP server, then open a public tunnel to it. The HTTP+ * handler (the security boundary) is live the instant `listen` resolves; the+ * tunnel is opened afterwards and is non-fatal — if it can't be established+ * (offline, loca.lt down, timed out) the server keeps running and we report+ * the tunnel error without a URL.+ */+ async start(): Promise<{ ok: boolean; url?: string; error?: string }> {+ if (this.server) return { ok: false, error: 'already running' };+ if (!this.signingSecret) return { ok: false, error: 'missing signing secret' };+ try {+ await this.listen();+ } catch (e) {+ this.stop();+ return { ok: false, error: `failed to bind port ${this.port}: ${errMsg(e)}` };+ }+ try {+ const tunnel = await this.openTunnel();+ this.tunnel = tunnel;+ // A dropped tunnel must not crash the main process; the local server stays up.+ tunnel.on('error', () => { /* tunnel hiccup — ignore, server still listening */ });+ return { ok: true, url: tunnel.url };+ } catch (e) {+ return { ok: true, error: `tunnel unavailable: ${errMsg(e)}` };+ }+ }++ /** Close the tunnel and HTTP server. Idempotent and best-effort. */+ stop(): void {+ try { this.tunnel?.close(); } catch { /* noop */ }+ this.tunnel = null;+ try { this.server?.close(); } catch { /* noop */ }+ this.server = null;+ }++ private listen(): Promise<void> {+ return new Promise<void>((resolve, reject) => {+ const server = createServer((req, res) => this.handleRequest(req, res));+ const onError = (e: Error): void => reject(e);+ server.once('error', onError);+ server.listen(this.port, () => {+ server.off('error', onError);+ this.server = server;+ resolve();+ });+ });+ }++ private openTunnel(): Promise<Tunnel> {+ return new Promise<Tunnel>((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error('timed out')), TUNNEL_START_TIMEOUT_MS);+ Promise.resolve(localtunnel({ port: this.port }))+ .then((t) => { clearTimeout(timer); resolve(t); })+ .catch((e) => { clearTimeout(timer); reject(e); });+ });+ }++ /** Buffer the raw body (needed verbatim for the HMAC) under a size cap, then+ * verify + dispatch. Only POST is accepted. */+ private handleRequest(req: IncomingMessage, res: ServerResponse): void {+ if (req.method !== 'POST') { res.writeHead(405); res.end(); return; }+ const chunks: Buffer[] = [];+ let size = 0;+ let aborted = false;+ req.on('data', (c: Buffer) => {+ if (aborted) return;+ size += c.length;+ if (size > MAX_BODY_BYTES) {+ aborted = true;+ res.writeHead(413); res.end();+ req.destroy();+ return;+ }+ chunks.push(c);+ });+ req.on('end', () => {+ if (aborted) return;+ this.handleBody(req, res, Buffer.concat(chunks).toString('utf8'));+ });+ req.on('error', () => {+ if (aborted) return;+ try { res.writeHead(400); res.end(); } catch { /* socket already gone */ }+ });+ }++ private handleBody(req: IncomingMessage, res: ServerResponse, rawBody: string): void {+ // 1) Authenticate over the RAW body BEFORE parsing. Any failure → 403.+ if (!this.verify(req, rawBody)) { res.writeHead(403); res.end(); return; }++ let payload: SlackPayload;+ try { payload = JSON.parse(rawBody) as SlackPayload; }+ catch { res.writeHead(400); res.end(); return; }++ // 2) URL verification handshake — echo the challenge back.+ if (payload.type === 'url_verification' && typeof payload.challenge === 'string') {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ challenge: payload.challenge }));+ return;+ }++ // 3) Real events: only plain user messages (no subtype = not an edit/join/+ // bot post), optionally filtered to one channel.+ if (payload.type === 'event_callback' && payload.event) {+ const ev = payload.event;+ const isPlainMessage = ev.type === 'message' && !ev.subtype && !ev.bot_id;+ const channelOk = !this.channelId || ev.channel === this.channelId;+ if (isPlainMessage && channelOk) {+ const text = stripLeadingMention(typeof ev.text === 'string' ? ev.text : '');+ if (text) {+ try { this.onMessage(text); } catch { /* delivery is best-effort */ }+ }+ }+ }++ // Always 200 so Slack treats the event as delivered and doesn't retry.+ res.writeHead(200); res.end();+ }++ /**+ * Verify a request is genuinely from Slack: HMAC-SHA256 of `v0:<ts>:<rawBody>`+ * with the signing secret must equal the `X-Slack-Signature` header (compared+ * in constant time), AND the timestamp must be within the replay window.+ */+ private verify(req: IncomingMessage, rawBody: string): boolean {+ const sig = req.headers['x-slack-signature'];+ const ts = req.headers['x-slack-request-timestamp'];+ if (typeof sig !== 'string' || typeof ts !== 'string') return false;++ // Replay guard: reject stale or non-numeric timestamps (> 5 min skew).+ const tsNum = Number(ts);+ if (!Number.isFinite(tsNum)) return false;+ if (Math.abs(Date.now() / 1000 - tsNum) > REPLAY_WINDOW_SECONDS) return false;++ const expected = 'v0=' + createHmac('sha256', this.signingSecret)+ .update(`v0:${ts}:${rawBody}`)+ .digest('hex');+ const provided = Buffer.from(sig);+ const computed = Buffer.from(expected);+ // timingSafeEqual throws on length mismatch — guard, and a differing length+ // is itself a mismatch, so bail before the constant-time compare.+ if (provided.length !== computed.length) return false;+ return timingSafeEqual(provided, computed);+ }+}++/** Minimal shape of the Slack Events API payloads we handle. */+interface SlackPayload {+ type?: string;+ challenge?: string;+ event?: {+ type?: string;+ subtype?: string;+ bot_id?: string;+ channel?: string;+ text?: string;+ };+}++/** Strip a single leading `<@BOTID>` app-mention so "@bot do X" enqueues "do X". */+function stripLeadingMention(text: string): string {+ return text.replace(/^\s*<@[A-Z0-9]+>\s*/i, '').trim();+}++function errMsg(e: unknown): string {+ return e instanceof Error ? e.message : String(e);+}diff --git a/src/preload/index.ts b/src/preload/index.tsindex ed63ea61..c822489e 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -320,7 +320,28 @@ const api = {/** Archive/unarchive a hive agent in the registry. Closing a terminal tab* archives it automatically via pty:kill; this is the explicit primitive. */hiveSetArchived: (id: string, archived: boolean): Promise<{ ok: boolean; error?: string }> =>- ipcRenderer.invoke('hive:setArchived', id, archived)+ ipcRenderer.invoke('hive:setArchived', id, archived),++ // ─── Slack integration (Slack message → Michael's queue) ─────────────────────+ /** Register a listener for inbound Slack messages; returns an unsubscribe fn.+ * Same pattern as onHiveHookEvent. */+ onSlackMessage: (cb: (msg: { text: string }) => void): (() => void) => {+ const listener = (_e: IpcRendererEvent, msg: { text: string }) => cb(msg);+ ipcRenderer.on('slack:incomingMessage', listener);+ return () => ipcRenderer.removeListener('slack:incomingMessage', listener);+ },+ /** Start the Slack webhook server; returns the public tunnel URL to paste into+ * the Slack app's Event Subscriptions → Request URL. */+ slackStart: (): Promise<{ ok: boolean; url?: string; error?: string }> =>+ ipcRenderer.invoke('slack:start'),+ /** Stop the Slack webhook server + tunnel. */+ slackStop: (): Promise<{ ok: boolean }> =>+ ipcRenderer.invoke('slack:stop'),+ /** Persist Slack settings (and stop the server if disabled / secret cleared). */+ slackSetConfig: (patch: {+ signingSecret?: string; botToken?: string; channelId?: string; port?: number; enabled?: boolean;+ }): Promise<{ ok: boolean }> =>+ ipcRenderer.invoke('slack:setConfig', patch)};contextBridge.exposeInMainWorld('cth', api);diff --git a/src/renderer/src/components/SettingsModal.tsx b/src/renderer/src/components/SettingsModal.tsxindex 8a470a74..6665e841 100644--- a/src/renderer/src/components/SettingsModal.tsx+++ b/src/renderer/src/components/SettingsModal.tsx@@ -1,4 +1,4 @@-import { useState } from 'react';+import { useState, type CSSProperties } from 'react';import type { HarnessConfig } from '@/store/config';import { PixelPanel } from './PixelPanel';import { PixelButton } from './PixelButton';@@ -9,6 +9,36 @@ export interface SettingsModalProps {onClose: () => void;}+/** Slack fields live on the main-process config; the renderer mirror type doesn't+ * declare them yet (same as `notifications`), so read them off a widened view. */+type SlackConfig = HarnessConfig & {+ slackEnabled?: boolean;+ slackSigningSecret?: string;+ slackChannelId?: string;+ slackPort?: number;+};++/** Pixel-aesthetic text input, mirroring AddAgentModal's inputStyle. */+const slackInputStyle: CSSProperties = {+ width: '100%',+ padding: '6px 8px 4px',+ background: 'var(--cth-paper-100)',+ border: 'none',+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)',+ fontFamily: 'var(--cth-font-ui)',+ fontSize: 14,+ color: 'var(--cth-ink-900)',+ outline: 'none'+};++const slackLabelStyle: CSSProperties = {+ fontFamily: 'var(--cth-font-display)',+ fontSize: 8,+ lineHeight: '12px',+ color: 'var(--cth-ink-700)',+ textTransform: 'uppercase'+};+/** Clear every renderer-side persisted key so a relaunch starts truly empty. */function clearLocalState(): void {try {@@ -37,6 +67,61 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {catch { setNotifications(!next); /* revert on failure */ }};+ // ─── Slack integration ─────────────────────────────────────────────────────+ const slackCfg = config as SlackConfig;+ const [slackEnabled, setSlackEnabled] = useState(slackCfg.slackEnabled ?? false);+ const [slackSecret, setSlackSecret] = useState(slackCfg.slackSigningSecret ?? '');+ const [slackChannel, setSlackChannel] = useState(slackCfg.slackChannelId ?? '');+ const [slackPort, setSlackPort] = useState(String(slackCfg.slackPort ?? 3847));+ const [tunnelUrl, setTunnelUrl] = useState('');+ const [slackBusy, setSlackBusy] = useState(false);+ const [slackNote, setSlackNote] = useState('');++ /** Persist the current Slack inputs. Returns the resolved config patch. */+ const slackPatch = (enabled: boolean) => ({+ signingSecret: slackSecret,+ channelId: slackChannel,+ port: Number(slackPort) || 3847,+ enabled+ });++ const saveSlack = async () => {+ setSlackBusy(true); setSlackNote('');+ try {+ await window.cth.slackSetConfig(slackPatch(slackEnabled));+ setSlackNote('saved');+ } catch (e) {+ setSlackNote(e instanceof Error ? e.message : String(e));+ } finally { setSlackBusy(false); }+ };++ const startSlack = async () => {+ setSlackBusy(true); setSlackNote('');+ try {+ // Persist first so the server starts with the latest secret/port/channel.+ await window.cth.slackSetConfig(slackPatch(true));+ setSlackEnabled(true);+ const res = await window.cth.slackStart();+ if (res.ok) {+ setTunnelUrl(res.url ?? '');+ setSlackNote(res.url ? 'listening' : (res.error ?? 'started, but tunnel unavailable'));+ } else {+ setSlackNote(res.error ?? 'failed to start');+ }+ } catch (e) {+ setSlackNote(e instanceof Error ? e.message : String(e));+ } finally { setSlackBusy(false); }+ };++ const stopSlack = async () => {+ setSlackBusy(true); setSlackNote('');+ try { await window.cth.slackStop(); setTunnelUrl(''); setSlackNote('stopped'); }+ catch (e) { setSlackNote(e instanceof Error ? e.message : String(e)); }+ finally { setSlackBusy(false); }+ };++ const copyTunnel = () => { void window.cth.copyToClipboard(tunnelUrl); };+const reset = async () => {setBusy(true);clearLocalState();@@ -99,6 +184,103 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {<div style={{ height: 2, background: 'var(--cth-ink-300)' }} />+ {/* Slack integration */}+ <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>+ <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>+ <span style={{ fontSize: 14, lineHeight: '20px', color: 'var(--cth-ink-900)' }}>+ Slack integration+ </span>+ <span style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>+ Pipe a Slack channel's messages straight into Michael's queue.+ </span>+ </div>+ <PixelButton+ variant={slackEnabled ? 'primary' : 'secondary'}+ size="sm"+ onClick={() => setSlackEnabled((v) => !v)}+ >+ {slackEnabled ? 'on' : 'off'}+ </PixelButton>+ </div>++ {slackEnabled && (+ <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>+ <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>+ <span style={slackLabelStyle}>Signing secret</span>+ <input+ type="password"+ value={slackSecret}+ onChange={(e) => setSlackSecret(e.target.value)}+ placeholder="Slack app → Basic Information → Signing Secret"+ style={{ ...slackInputStyle, fontFamily: 'var(--cth-font-mono)' }}+ />+ </label>++ <div style={{ display: 'flex', gap: 10 }}>+ <label style={{ display: 'flex', flexDirection: 'column', gap: 4, flex: 1 }}>+ <span style={slackLabelStyle}>Channel id (optional)</span>+ <input+ value={slackChannel}+ onChange={(e) => setSlackChannel(e.target.value)}+ placeholder="C0123… or blank for any"+ style={{ ...slackInputStyle, fontFamily: 'var(--cth-font-mono)' }}+ />+ </label>+ <label style={{ display: 'flex', flexDirection: 'column', gap: 4, width: 92 }}>+ <span style={slackLabelStyle}>Port</span>+ <input+ type="number"+ value={slackPort}+ onChange={(e) => setSlackPort(e.target.value)}+ placeholder="3847"+ style={{ ...slackInputStyle, fontFamily: 'var(--cth-font-mono)' }}+ />+ </label>+ </div>++ <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>+ <PixelButton variant="primary" size="sm" onClick={startSlack} disabled={slackBusy || !slackSecret.trim()}>+ {slackBusy ? '…' : 'start'}+ </PixelButton>+ <PixelButton variant="secondary" size="sm" onClick={stopSlack} disabled={slackBusy}>+ stop+ </PixelButton>+ <PixelButton variant="ghost" size="sm" onClick={saveSlack} disabled={slackBusy}>+ save+ </PixelButton>+ {slackNote && (+ <span style={{ fontSize: 12, color: 'var(--cth-ink-500)' }}>{slackNote}</span>+ )}+ </div>++ {tunnelUrl && (+ <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>+ <span style={slackLabelStyle}>Request URL — paste into Slack Event Subscriptions</span>+ <div style={{ display: 'flex', gap: 6 }}>+ <input+ readOnly+ value={tunnelUrl}+ onFocus={(e) => e.currentTarget.select()}+ style={{ ...slackInputStyle, fontFamily: 'var(--cth-font-mono)', fontSize: 12 }}+ />+ <PixelButton variant="secondary" size="sm" onClick={copyTunnel}>copy</PixelButton>+ </div>+ </div>+ )}++ <span style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>+ In your Slack app: enable Event Subscriptions → add the{' '}+ <code>message.channels</code> / <code>message.groups</code> bot event → set the+ Request URL above → reinstall to your workspace. The tunnel URL changes on every+ restart, so re-paste it after pressing Start again.+ </span>+ </div>+ )}+ </div>++ <div style={{ height: 2, background: 'var(--cth-ink-300)' }} />+<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}><div style={{fontFamily: 'var(--cth-font-display)', fontSize: 10, lineHeight: '14px',diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.tsindex 7cc08dba..267a1e57 100644--- a/src/renderer/src/hooks/useHive.ts+++ b/src/renderer/src/hooks/useHive.ts@@ -322,4 +322,16 @@ export function useHive(config: HarnessConfig | null): void {schedule();return () => { unsub(); if (debounce) clearTimeout(debounce); clearInterval(iv); };}, [config?.onboardingComplete]);++ // 5) Pipe inbound Slack messages into Michael's queue. The main-process Slack+ // webhook server pushes each verified message here via IPC; enqueueing to+ // GOD_ID lands it in Michael's queue exactly as if the user had typed it+ // into the composer — effect #4 above then drains it to his PTY.+ useEffect(() => {+ if (!config?.onboardingComplete) return;+ return window.cth.onSlackMessage((msg) => {+ if (!msg?.text?.trim()) return;+ useStore.getState().enqueueMessage(GOD_ID, msg.text.trim());+ });+ }, [config?.onboardingComplete]);}