@interactive-inc/claude-funnel 0.8.0 → 0.10.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.
Files changed (54) hide show
  1. package/README.md +179 -80
  2. package/dist/bin.js +693 -698
  3. package/dist/connector-adapter-CXB-q_XC.d.ts +11 -0
  4. package/dist/connector-adapter-D5Utumgz.js +4 -0
  5. package/dist/connectors/discord.d.ts +76 -0
  6. package/dist/connectors/discord.js +2 -0
  7. package/dist/connectors/gh.d.ts +38 -0
  8. package/dist/connectors/gh.js +2 -0
  9. package/dist/connectors/schedule.d.ts +53 -0
  10. package/dist/connectors/schedule.js +2 -0
  11. package/dist/connectors/slack.d.ts +62 -0
  12. package/dist/connectors/slack.js +2 -0
  13. package/dist/discord-connector-schema-Dww2I4zH.d.ts +14 -0
  14. package/dist/discord-connector-schema-ygf5Df-2.js +173 -0
  15. package/dist/file-system-Co60LrmR.d.ts +74 -0
  16. package/dist/gateway/daemon.js +243 -221
  17. package/dist/gh-connector-schema-2ml29MBC.js +218 -0
  18. package/dist/gh-connector-schema-BZFAS-p-.d.ts +45 -0
  19. package/dist/index.d.ts +3888 -0
  20. package/dist/index.js +6296 -0
  21. package/dist/logger-CTlXs7z4.d.ts +33 -0
  22. package/dist/node-logger-DQz_BGOD.js +61 -0
  23. package/dist/schedule-connector-schema-CkuIQ0JQ.js +325 -0
  24. package/dist/slack-connector-schema-Cd22WiHB.js +153 -0
  25. package/dist/slack-connector-schema-D7zAHN8k.d.ts +15 -0
  26. package/lib/bin.ts +1 -76
  27. package/lib/cli/index.ts +85 -0
  28. package/lib/cli/router/to-request.ts +1 -0
  29. package/lib/cli/routes/channels.$channel.publish.ts +52 -0
  30. package/lib/cli/routes/claude.ts +1 -0
  31. package/lib/cli/routes/index.ts +35 -18
  32. package/lib/cli/routes/profiles.add.$profile.ts +5 -2
  33. package/lib/cli/routes/profiles.set.$profile.ts +10 -11
  34. package/lib/connectors/discord.ts +4 -0
  35. package/lib/connectors/gh.ts +3 -0
  36. package/lib/connectors/schedule.ts +4 -0
  37. package/lib/connectors/slack.ts +4 -0
  38. package/lib/engine/claude/claude.ts +6 -0
  39. package/lib/engine/mcp/channel-server.ts +34 -115
  40. package/lib/engine/mcp/channel-subscriber.ts +82 -0
  41. package/lib/engine/mcp/read-channel-connectors.ts +34 -0
  42. package/lib/engine/mcp/read-gateway-token.ts +16 -0
  43. package/lib/engine/mcp/usage-hint-for-type.ts +15 -0
  44. package/lib/engine/settings/settings-schema.ts +2 -0
  45. package/lib/funnel.ts +162 -55
  46. package/lib/gateway/broadcaster.ts +1 -1
  47. package/lib/gateway/channel-publisher.ts +67 -0
  48. package/lib/gateway/gateway-server.ts +28 -16
  49. package/lib/gateway/publish-schema.ts +27 -0
  50. package/lib/gateway/routes/channels.publish.ts +44 -0
  51. package/lib/gateway/routes/index.ts +2 -0
  52. package/lib/gateway/routes/route-deps.ts +8 -0
  53. package/lib/index.ts +17 -0
  54. package/package.json +41 -25
@@ -0,0 +1,33 @@
1
+ //#region lib/connectors/connector-listener.d.ts
2
+ type NotifyFn = (content: string, meta?: Record<string, string>) => Promise<void>;
3
+ /**
4
+ * Long-lived event source for one connector.
5
+ *
6
+ * `start()` opens the underlying connection (Slack Socket Mode, Discord
7
+ * Gateway, GH polling, schedule tick) and pushes events through `notify`.
8
+ * `stop()` releases the resources so the supervisor can recreate the listener
9
+ * with new config without restarting the whole gateway. `isAlive()` lets the
10
+ * supervisor periodically health-check and auto-restart dead listeners; the
11
+ * default optimistic implementation is fine for poll/tick-based listeners
12
+ * that self-heal.
13
+ */
14
+ declare abstract class FunnelConnectorListener {
15
+ abstract start(notify: NotifyFn): Promise<void>;
16
+ abstract stop(): Promise<void>;
17
+ isAlive(): boolean;
18
+ }
19
+ //#endregion
20
+ //#region lib/engine/logger/logger.d.ts
21
+ /**
22
+ * Structured logger with three levels and an optional log-file path.
23
+ * Defaults to NodeFunnelLogger (appends to /tmp/funnel/funnel.log);
24
+ * MemoryFunnelLogger captures entries in memory and NoopFunnelLogger silences output.
25
+ */
26
+ declare abstract class FunnelLogger {
27
+ abstract info(message: string, meta?: Record<string, unknown>): void;
28
+ abstract warn(message: string, meta?: Record<string, unknown>): void;
29
+ abstract error(message: string, meta?: Record<string, unknown>): void;
30
+ abstract readonly file: string | null;
31
+ }
32
+ //#endregion
33
+ export { FunnelConnectorListener as n, NotifyFn as r, FunnelLogger as t };
@@ -0,0 +1,61 @@
1
+ import { dirname, join } from "node:path";
2
+ import { appendFileSync, mkdirSync } from "node:fs";
3
+ //#region lib/connectors/connector-listener.ts
4
+ /**
5
+ * Long-lived event source for one connector.
6
+ *
7
+ * `start()` opens the underlying connection (Slack Socket Mode, Discord
8
+ * Gateway, GH polling, schedule tick) and pushes events through `notify`.
9
+ * `stop()` releases the resources so the supervisor can recreate the listener
10
+ * with new config without restarting the whole gateway. `isAlive()` lets the
11
+ * supervisor periodically health-check and auto-restart dead listeners; the
12
+ * default optimistic implementation is fine for poll/tick-based listeners
13
+ * that self-heal.
14
+ */
15
+ var FunnelConnectorListener = class {
16
+ isAlive() {
17
+ return true;
18
+ }
19
+ };
20
+ //#endregion
21
+ //#region lib/engine/logger/logger.ts
22
+ /**
23
+ * Structured logger with three levels and an optional log-file path.
24
+ * Defaults to NodeFunnelLogger (appends to /tmp/funnel/funnel.log);
25
+ * MemoryFunnelLogger captures entries in memory and NoopFunnelLogger silences output.
26
+ */
27
+ var FunnelLogger = class {};
28
+ //#endregion
29
+ //#region lib/engine/logger/node-logger.ts
30
+ const DEFAULT_LOG_FILE = join("/tmp/funnel", "funnel.log");
31
+ var NodeFunnelLogger = class extends FunnelLogger {
32
+ file;
33
+ now;
34
+ constructor(props = {}) {
35
+ super();
36
+ this.file = props.file ?? DEFAULT_LOG_FILE;
37
+ this.now = props.now ?? (() => /* @__PURE__ */ new Date());
38
+ Object.freeze(this);
39
+ }
40
+ info(message, meta) {
41
+ this.write("info", message, meta);
42
+ }
43
+ warn(message, meta) {
44
+ this.write("warn", message, meta);
45
+ }
46
+ error(message, meta) {
47
+ this.write("error", message, meta);
48
+ }
49
+ write(level, message, meta) {
50
+ mkdirSync(dirname(this.file), { recursive: true });
51
+ const entry = {
52
+ time: this.now().toISOString(),
53
+ level,
54
+ message,
55
+ ...meta ? { meta } : {}
56
+ };
57
+ appendFileSync(this.file, `${JSON.stringify(entry)}\n`);
58
+ }
59
+ };
60
+ //#endregion
61
+ export { FunnelLogger as n, FunnelConnectorListener as r, NodeFunnelLogger as t };
@@ -0,0 +1,325 @@
1
+ import { r as FunnelConnectorListener, t as NodeFunnelLogger } from "./node-logger-DQz_BGOD.js";
2
+ import { dirname } from "node:path";
3
+ import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import { z } from "zod";
5
+ //#region lib/connectors/match-cron.ts
6
+ const parseField = (expr, min, max) => {
7
+ const values = /* @__PURE__ */ new Set();
8
+ for (const part of expr.split(",")) {
9
+ const [rangePart, stepPart] = part.split("/");
10
+ const step = stepPart ? Number(stepPart) : 1;
11
+ if (!Number.isFinite(step) || step <= 0) throw new Error(`invalid cron step: "${stepPart}"`);
12
+ let lo = min;
13
+ let hi = max;
14
+ if (rangePart === "*" || rangePart === void 0 || rangePart === "") {
15
+ lo = min;
16
+ hi = max;
17
+ } else if (rangePart.includes("-")) {
18
+ const [aStr, bStr] = rangePart.split("-");
19
+ const a = Number(aStr);
20
+ const b = Number(bStr);
21
+ if (!Number.isFinite(a) || !Number.isFinite(b)) throw new Error(`invalid cron range: "${rangePart}"`);
22
+ lo = a;
23
+ hi = b;
24
+ } else {
25
+ const n = Number(rangePart);
26
+ if (!Number.isFinite(n)) throw new Error(`invalid cron value: "${rangePart}"`);
27
+ lo = n;
28
+ hi = stepPart ? max : n;
29
+ }
30
+ if (lo < min || hi > max || lo > hi) throw new Error(`cron value out of range: ${rangePart} (must be ${min}-${max})`);
31
+ for (let i = lo; i <= hi; i += step) values.add(i);
32
+ }
33
+ return {
34
+ min,
35
+ max,
36
+ values
37
+ };
38
+ };
39
+ const matchCron = (expr, date) => {
40
+ const parts = expr.trim().split(/\s+/);
41
+ if (parts.length !== 5) throw new Error(`cron must have 5 fields (got ${parts.length}): "${expr}"`);
42
+ const [minute, hour, dom, month, dow] = parts;
43
+ if (!minute || !hour || !dom || !month || !dow) throw new Error(`cron has empty fields: "${expr}"`);
44
+ const fields = [
45
+ {
46
+ field: parseField(minute, 0, 59),
47
+ value: date.getMinutes()
48
+ },
49
+ {
50
+ field: parseField(hour, 0, 23),
51
+ value: date.getHours()
52
+ },
53
+ {
54
+ field: parseField(dom, 1, 31),
55
+ value: date.getDate()
56
+ },
57
+ {
58
+ field: parseField(month, 1, 12),
59
+ value: date.getMonth() + 1
60
+ },
61
+ {
62
+ field: parseField(dow, 0, 6),
63
+ value: date.getDay()
64
+ }
65
+ ];
66
+ for (const { field, value } of fields) if (!field.values.has(value)) return false;
67
+ return true;
68
+ };
69
+ //#endregion
70
+ //#region lib/engine/fs/file-system.ts
71
+ /**
72
+ * Filesystem boundary used everywhere funnel reads or writes.
73
+ * Default is NodeFunnelFileSystem (real `node:fs`); MemoryFunnelFileSystem
74
+ * provides a sandbox for tests and embedded use.
75
+ */
76
+ var FunnelFileSystem = class {};
77
+ //#endregion
78
+ //#region lib/engine/fs/node-file-system.ts
79
+ const SECRET_MODE = 384;
80
+ var NodeFunnelFileSystem = class extends FunnelFileSystem {
81
+ constructor() {
82
+ super();
83
+ Object.freeze(this);
84
+ }
85
+ existsSync(path) {
86
+ return existsSync(path);
87
+ }
88
+ readFileSync(path) {
89
+ return readFileSync(path, "utf-8");
90
+ }
91
+ writeFileSync(path, data) {
92
+ writeFileSync(path, data);
93
+ }
94
+ writeSecretFileSync(path, data) {
95
+ writeFileSync(path, data, { mode: SECRET_MODE });
96
+ try {
97
+ chmodSync(path, SECRET_MODE);
98
+ } catch {}
99
+ }
100
+ appendFileSync(path, data) {
101
+ appendFileSync(path, data);
102
+ }
103
+ unlink(path) {
104
+ try {
105
+ unlinkSync(path);
106
+ } catch {}
107
+ }
108
+ mkdirSync(path, options) {
109
+ mkdirSync(path, { recursive: options?.recursive ?? false });
110
+ }
111
+ readdirSync(path) {
112
+ return readdirSync(path);
113
+ }
114
+ statSync(path) {
115
+ const stat = statSync(path);
116
+ return {
117
+ mtimeMs: stat.mtimeMs,
118
+ mode: stat.mode & 511
119
+ };
120
+ }
121
+ };
122
+ //#endregion
123
+ //#region lib/connectors/schedule-state-store.ts
124
+ const defaultFs = new NodeFunnelFileSystem();
125
+ /**
126
+ * Per-connector lastFiredAt persistence for the schedule listener. The path is
127
+ * passed in by FunnelConnectorFactory so this store does not know about the
128
+ * funnel directory layout (`channels/<id>/connectors/<id>/state.json` lives
129
+ * outside this class).
130
+ */
131
+ var ScheduleStateStore = class {
132
+ path;
133
+ fs;
134
+ constructor(deps) {
135
+ this.path = deps.path;
136
+ this.fs = deps.fs ?? defaultFs;
137
+ Object.freeze(this);
138
+ }
139
+ load() {
140
+ const map = /* @__PURE__ */ new Map();
141
+ if (!this.fs.existsSync(this.path)) return map;
142
+ const raw = JSON.parse(this.fs.readFileSync(this.path));
143
+ if (raw === null || typeof raw !== "object") return map;
144
+ for (const [id, iso] of Object.entries(raw)) if (typeof iso === "string") map.set(id, new Date(iso));
145
+ return map;
146
+ }
147
+ save(state) {
148
+ const obj = {};
149
+ for (const [id, date] of state) obj[id] = date.toISOString();
150
+ this.fs.mkdirSync(dirname(this.path), { recursive: true });
151
+ this.fs.writeFileSync(this.path, `${JSON.stringify(obj, null, 2)}\n`);
152
+ }
153
+ };
154
+ //#endregion
155
+ //#region lib/connectors/schedule-listener.ts
156
+ const defaultLogger = new NodeFunnelLogger();
157
+ const MAX_CATCHUP_MINUTES = 1440;
158
+ var FunnelScheduleListener = class extends FunnelConnectorListener {
159
+ config;
160
+ lastFiredStore;
161
+ logger;
162
+ now;
163
+ timer = null;
164
+ stopped = false;
165
+ constructor(deps) {
166
+ super();
167
+ this.config = deps.config;
168
+ this.lastFiredStore = deps.lastFiredStore;
169
+ this.logger = deps.logger ?? defaultLogger;
170
+ this.now = deps.now ?? (() => /* @__PURE__ */ new Date());
171
+ }
172
+ async start(notify) {
173
+ this.stopped = false;
174
+ const scheduleNext = () => {
175
+ if (this.stopped) return;
176
+ const date = this.now();
177
+ const msUntilNextMinute = 6e4 - (date.getSeconds() * 1e3 + date.getMilliseconds());
178
+ this.timer = setTimeout(async () => {
179
+ if (this.stopped) return;
180
+ await this.tick(notify);
181
+ scheduleNext();
182
+ }, msUntilNextMinute);
183
+ this.timer.unref();
184
+ };
185
+ await this.tick(notify);
186
+ scheduleNext();
187
+ }
188
+ async stop() {
189
+ this.stopped = true;
190
+ if (this.timer) {
191
+ clearTimeout(this.timer);
192
+ this.timer = null;
193
+ }
194
+ }
195
+ isAlive() {
196
+ return !this.stopped && this.timer !== null;
197
+ }
198
+ async tick(notify) {
199
+ const now = this.truncateToMinute(this.now());
200
+ const state = this.lastFiredStore.load();
201
+ let changed = false;
202
+ for (const entry of this.config.entries) {
203
+ if (!entry.enabled) continue;
204
+ if (await this.fireEntry(entry, now, state, notify)) changed = true;
205
+ }
206
+ if (changed) this.lastFiredStore.save(state);
207
+ }
208
+ async fireEntry(entry, now, state, notify) {
209
+ const lastFired = state.get(entry.id);
210
+ const searchFrom = lastFired ? new Date(lastFired.getTime() + 6e4) : now;
211
+ if (searchFrom.getTime() > now.getTime()) return false;
212
+ if (entry.catchupPolicy === "skip") {
213
+ try {
214
+ if (!matchCron(entry.cron, now)) return false;
215
+ } catch (error) {
216
+ this.logInvalidCron(entry, error);
217
+ return false;
218
+ }
219
+ await this.notifyOne(entry, now, notify, false);
220
+ state.set(entry.id, now);
221
+ return true;
222
+ }
223
+ if (entry.catchupPolicy === "all") {
224
+ const matches = this.findAllMatches(entry.cron, searchFrom, now, entry.id);
225
+ if (matches.length === 0) return false;
226
+ for (const match of matches) await this.notifyOne(entry, match, notify, match.getTime() !== now.getTime());
227
+ state.set(entry.id, matches[matches.length - 1] ?? now);
228
+ return true;
229
+ }
230
+ const match = this.findMostRecentMatch(entry.cron, searchFrom, now, entry.id);
231
+ if (!match) return false;
232
+ await this.notifyOne(entry, match, notify, match.getTime() !== now.getTime());
233
+ state.set(entry.id, match);
234
+ return true;
235
+ }
236
+ async notifyOne(entry, firedAt, notify, catchup) {
237
+ const meta = {
238
+ event_type: "schedule",
239
+ schedule_id: entry.id,
240
+ cron: entry.cron,
241
+ fired_at: firedAt.toISOString(),
242
+ catchup_policy: entry.catchupPolicy
243
+ };
244
+ if (catchup) meta.catchup = "true";
245
+ await notify(entry.prompt, meta);
246
+ }
247
+ findMostRecentMatch(cron, from, until, entryId) {
248
+ const maxIterations = Math.min(MAX_CATCHUP_MINUTES, Math.floor((until.getTime() - from.getTime()) / 6e4) + 1);
249
+ for (let i = 0; i < maxIterations; i++) {
250
+ const candidate = /* @__PURE__ */ new Date(until.getTime() - i * 6e4);
251
+ try {
252
+ if (matchCron(cron, candidate)) return candidate;
253
+ } catch (error) {
254
+ this.logInvalidCron({
255
+ id: entryId,
256
+ cron
257
+ }, error);
258
+ return null;
259
+ }
260
+ }
261
+ return null;
262
+ }
263
+ findAllMatches(cron, from, until, entryId) {
264
+ const maxIterations = Math.min(MAX_CATCHUP_MINUTES, Math.floor((until.getTime() - from.getTime()) / 6e4) + 1);
265
+ const matches = [];
266
+ for (let i = 0; i < maxIterations; i++) {
267
+ const candidate = new Date(from.getTime() + i * 6e4);
268
+ if (candidate.getTime() > until.getTime()) break;
269
+ try {
270
+ if (matchCron(cron, candidate)) matches.push(candidate);
271
+ } catch (error) {
272
+ this.logInvalidCron({
273
+ id: entryId,
274
+ cron
275
+ }, error);
276
+ return [];
277
+ }
278
+ }
279
+ return matches;
280
+ }
281
+ logInvalidCron(entry, error) {
282
+ this.logger.error("invalid cron expression in schedule", {
283
+ connector: this.config.name,
284
+ id: entry.id,
285
+ cron: entry.cron,
286
+ error: error instanceof Error ? error.message : String(error)
287
+ });
288
+ }
289
+ truncateToMinute(date) {
290
+ const copy = new Date(date.getTime());
291
+ copy.setSeconds(0, 0);
292
+ return copy;
293
+ }
294
+ };
295
+ //#endregion
296
+ //#region lib/connectors/schedule-connector-schema.ts
297
+ /**
298
+ * Catch-up behavior when the daemon was down past one or more matching minutes.
299
+ *
300
+ * - `latest`: fire once with the most recent missed match (default; preserves prior behavior).
301
+ * - `all`: fire once per missed minute, oldest first (capped at 24 h).
302
+ * - `skip`: never fire missed matches; only fire when the current minute matches.
303
+ */
304
+ const scheduleCatchupPolicySchema = z.enum([
305
+ "latest",
306
+ "all",
307
+ "skip"
308
+ ]);
309
+ const scheduleEntrySchema = z.object({
310
+ id: z.string(),
311
+ cron: z.string(),
312
+ prompt: z.string(),
313
+ enabled: z.boolean().default(true),
314
+ catchupPolicy: scheduleCatchupPolicySchema.default("latest")
315
+ });
316
+ const scheduleConnectorSchema = z.object({
317
+ id: z.string(),
318
+ name: z.string(),
319
+ type: z.literal("schedule"),
320
+ entries: z.array(scheduleEntrySchema).default([]),
321
+ createdAt: z.string().datetime().optional(),
322
+ updatedAt: z.string().datetime().optional()
323
+ });
324
+ //#endregion
325
+ export { ScheduleStateStore as a, matchCron as c, FunnelScheduleListener as i, scheduleConnectorSchema as n, NodeFunnelFileSystem as o, scheduleEntrySchema as r, FunnelFileSystem as s, scheduleCatchupPolicySchema as t };
@@ -0,0 +1,153 @@
1
+ import { t as FunnelConnectorAdapter } from "./connector-adapter-D5Utumgz.js";
2
+ import { r as FunnelConnectorListener, t as NodeFunnelLogger } from "./node-logger-DQz_BGOD.js";
3
+ import { z } from "zod";
4
+ import { WebClient } from "@slack/web-api";
5
+ import { App, LogLevel } from "@slack/bolt";
6
+ //#region lib/connectors/slack-adapter.ts
7
+ const toRecord = (value) => {
8
+ const result = {};
9
+ for (const [key, val] of Object.entries(value)) result[key] = val;
10
+ return result;
11
+ };
12
+ var FunnelSlackAdapter = class extends FunnelConnectorAdapter {
13
+ client;
14
+ constructor(deps) {
15
+ super();
16
+ this.client = deps.client ?? new WebClient(deps.config.botToken);
17
+ Object.freeze(this);
18
+ }
19
+ async call(input) {
20
+ const body = input.body !== null && typeof input.body === "object" ? toRecord(input.body) : {};
21
+ return await this.client.apiCall(input.path, body);
22
+ }
23
+ };
24
+ //#endregion
25
+ //#region lib/connectors/slack-event-processor.ts
26
+ const ALLOWED_EVENTS = new Set(["message", "app_mention"]);
27
+ const ALLOWED_SUBTYPES = new Set([
28
+ void 0,
29
+ "thread_broadcast",
30
+ "bot_message",
31
+ "file_share"
32
+ ]);
33
+ const DEDUP_WINDOW = 1e4;
34
+ const getString = (event, key) => {
35
+ const value = event[key];
36
+ return typeof value === "string" ? value : void 0;
37
+ };
38
+ var FunnelSlackEventProcessor = class {
39
+ ownBotUserId;
40
+ ownBotId;
41
+ now;
42
+ dedup = /* @__PURE__ */ new Map();
43
+ constructor(props) {
44
+ this.ownBotUserId = props.ownBotUserId;
45
+ this.ownBotId = props.ownBotId;
46
+ this.now = props.now ?? (() => Date.now());
47
+ }
48
+ process(event) {
49
+ const eventType = getString(event, "type");
50
+ if (!eventType || !ALLOWED_EVENTS.has(eventType)) return { skip: true };
51
+ const subtype = getString(event, "subtype");
52
+ if (!ALLOWED_SUBTYPES.has(subtype)) return { skip: true };
53
+ const channelId = getString(event, "channel") ?? "";
54
+ const dedupKey = `${channelId}:${getString(event, "event_ts") ?? getString(event, "ts") ?? ""}`;
55
+ const now = this.now();
56
+ if (this.dedup.has(dedupKey)) return { skip: true };
57
+ this.dedup.set(dedupKey, now);
58
+ for (const key of this.dedup.keys()) if ((this.dedup.get(key) ?? 0) < now - DEDUP_WINDOW) this.dedup.delete(key);
59
+ const userId = getString(event, "user");
60
+ const botId = getString(event, "bot_id");
61
+ if (userId === this.ownBotUserId) return { skip: true };
62
+ if (botId === this.ownBotId) return { skip: true };
63
+ const mentioned = (getString(event, "text") ?? "").includes(`<@${this.ownBotUserId}>`);
64
+ const threadTs = getString(event, "thread_ts") ?? getString(event, "ts") ?? "";
65
+ return {
66
+ skip: false,
67
+ content: JSON.stringify(event),
68
+ meta: {
69
+ event_type: "slack",
70
+ channel_id: channelId,
71
+ user_id: userId ?? "",
72
+ mentioned: String(mentioned),
73
+ thread_ts: threadTs
74
+ },
75
+ shouldReact: mentioned,
76
+ channel: channelId,
77
+ timestamp: getString(event, "ts") ?? ""
78
+ };
79
+ }
80
+ };
81
+ //#endregion
82
+ //#region lib/connectors/slack-listener.ts
83
+ const middlewareArgsSchema = z.object({ event: z.record(z.string(), z.unknown()).optional() });
84
+ const defaultLogger = new NodeFunnelLogger();
85
+ var FunnelSlackListener = class extends FunnelConnectorListener {
86
+ config;
87
+ logger;
88
+ app = null;
89
+ constructor(deps) {
90
+ super();
91
+ this.config = deps.config;
92
+ this.logger = deps.logger ?? defaultLogger;
93
+ }
94
+ async start(notify) {
95
+ const app = new App({
96
+ token: this.config.botToken,
97
+ appToken: this.config.appToken,
98
+ socketMode: true,
99
+ logLevel: LogLevel.ERROR
100
+ });
101
+ const authResult = await app.client.auth.test({ token: this.config.botToken });
102
+ const processor = new FunnelSlackEventProcessor({
103
+ ownBotUserId: authResult.user_id ?? "",
104
+ ownBotId: authResult.bot_id ?? ""
105
+ });
106
+ app.use(async (args) => {
107
+ const parsed = middlewareArgsSchema.safeParse(args);
108
+ if (!parsed.success || !parsed.data.event) return;
109
+ const result = processor.process(parsed.data.event);
110
+ if (result.skip) return;
111
+ if (result.shouldReact) try {
112
+ await app.client.reactions.add({
113
+ token: this.config.botToken,
114
+ channel: result.channel,
115
+ timestamp: result.timestamp,
116
+ name: "eyes"
117
+ });
118
+ } catch {}
119
+ await notify(result.content, result.meta);
120
+ });
121
+ app.error(async (error) => {
122
+ this.logger.error("Slack error", { error: error instanceof Error ? error.message : String(error) });
123
+ });
124
+ await app.start();
125
+ this.app = app;
126
+ }
127
+ async stop() {
128
+ if (!this.app) return;
129
+ try {
130
+ await this.app.stop();
131
+ } catch (error) {
132
+ this.logger.error("Slack stop error", { error: error instanceof Error ? error.message : String(error) });
133
+ } finally {
134
+ this.app = null;
135
+ }
136
+ }
137
+ isAlive() {
138
+ return this.app !== null;
139
+ }
140
+ };
141
+ //#endregion
142
+ //#region lib/connectors/slack-connector-schema.ts
143
+ const slackConnectorSchema = z.object({
144
+ id: z.string(),
145
+ name: z.string(),
146
+ type: z.literal("slack"),
147
+ botToken: z.string().startsWith("xoxb-"),
148
+ appToken: z.string().startsWith("xapp-"),
149
+ createdAt: z.string().datetime().optional(),
150
+ updatedAt: z.string().datetime().optional()
151
+ });
152
+ //#endregion
153
+ export { FunnelSlackAdapter as i, FunnelSlackListener as n, FunnelSlackEventProcessor as r, slackConnectorSchema as t };
@@ -0,0 +1,15 @@
1
+ import { z } from "zod";
2
+
3
+ //#region lib/connectors/slack-connector-schema.d.ts
4
+ declare const slackConnectorSchema: z.ZodObject<{
5
+ id: z.ZodString;
6
+ name: z.ZodString;
7
+ type: z.ZodLiteral<"slack">;
8
+ botToken: z.ZodString;
9
+ appToken: z.ZodString;
10
+ createdAt: z.ZodOptional<z.ZodString>;
11
+ updatedAt: z.ZodOptional<z.ZodString>;
12
+ }, z.core.$strip>;
13
+ type SlackConnectorConfig = z.infer<typeof slackConnectorSchema>;
14
+ //#endregion
15
+ export { slackConnectorSchema as n, SlackConnectorConfig as t };
package/lib/bin.ts CHANGED
@@ -1,78 +1,3 @@
1
1
  #!/usr/bin/env bun
2
- import pkg from "../package.json" with { type: "json" }
3
- import { startChannelServer } from "@/engine/mcp/channel-server"
4
- import { toRequest } from "@/cli/router/to-request"
5
- import { launchTui } from "@/tui/tui"
6
- import { app } from "@/cli/routes"
7
- import { Funnel } from "@/funnel"
8
2
 
9
- process.title = "funnel"
10
-
11
- const HELP = `funnel — Open Claude Funnel
12
-
13
- usage: funnel [command]
14
-
15
- commands:
16
- (none) launch TUI
17
- claude launch Claude Code (default profile or --profile)
18
- channels manage subscription boxes (and their nested connectors)
19
- profiles manage launch profiles
20
- gateway manage the gateway daemon (HTTP + WS)
21
- status show overall connection status
22
- update update funnel to the latest version
23
- mcp run as an MCP server (invoked from .mcp.json)
24
-
25
- options:
26
- --help, -h show help
27
- --version, -v show version
28
-
29
- more: funnel <command> --help`
30
-
31
- const args = process.argv.slice(2)
32
-
33
- if (args.length === 0) {
34
- await launchTui(new Funnel())
35
- process.exit(0)
36
- }
37
-
38
- if (args[0] === "--version" || args[0] === "-v") {
39
- process.stdout.write(`${pkg.version}\n`)
40
- process.exit(0)
41
- }
42
-
43
- if (args[0] === "mcp") {
44
- await startChannelServer()
45
- } else {
46
- const { method, url } = toRequest(args)
47
- const parsed = new URL(url)
48
- const wantsHelp = parsed.searchParams.has("help")
49
-
50
- if (wantsHelp && parsed.pathname === "/") {
51
- process.stdout.write(`${HELP}\n`)
52
- process.exit(0)
53
- }
54
-
55
- const res = await app.request(url, { method })
56
-
57
- if (res.ok) {
58
- const body = await res.text()
59
- if (body) process.stdout.write(`${body}\n`)
60
- process.exit(0)
61
- }
62
-
63
- if (wantsHelp) {
64
- const segments = parsed.pathname.split("/").filter(Boolean)
65
- const group = segments[0]
66
- const fallback = group
67
- ? await app.request(`http://localhost/${group}?help=true`, { method: "GET" })
68
- : null
69
-
70
- const text = fallback?.ok ? await fallback.text() : HELP
71
- process.stdout.write(`${text}\n`)
72
- process.exit(0)
73
- }
74
-
75
- const text = await res.text()
76
- if (text) process.stderr.write(`${text}\n`)
77
- process.exit(1)
78
- }
3
+ import "@/cli"