polyergon 0.0.0-stage → 0.1.1

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 (239) hide show
  1. package/.next/BUILD_ID +1 -0
  2. package/.next/app-build-manifest.json +35 -0
  3. package/.next/app-path-routes-manifest.json +1 -0
  4. package/.next/build-manifest.json +32 -0
  5. package/.next/export-marker.json +1 -0
  6. package/.next/images-manifest.json +1 -0
  7. package/.next/next-minimal-server.js.nft.json +1 -0
  8. package/.next/next-server.js.nft.json +1 -0
  9. package/.next/package.json +1 -0
  10. package/.next/prerender-manifest.json +1 -0
  11. package/.next/react-loadable-manifest.json +10 -0
  12. package/.next/required-server-files.json +1 -0
  13. package/.next/routes-manifest.json +1 -0
  14. package/.next/server/app/_not-found/page.js +1 -0
  15. package/.next/server/app/_not-found/page.js.nft.json +1 -0
  16. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -0
  17. package/.next/server/app/_not-found.html +1 -0
  18. package/.next/server/app/_not-found.meta +6 -0
  19. package/.next/server/app/_not-found.rsc +9 -0
  20. package/.next/server/app/api/automations/existing/route.js +1 -0
  21. package/.next/server/app/api/automations/existing/route.js.nft.json +1 -0
  22. package/.next/server/app/api/backends/route.js +1 -0
  23. package/.next/server/app/api/backends/route.js.nft.json +1 -0
  24. package/.next/server/app/api/diff/route.js +1 -0
  25. package/.next/server/app/api/diff/route.js.nft.json +1 -0
  26. package/.next/server/app/api/limits/route.js +1 -0
  27. package/.next/server/app/api/limits/route.js.nft.json +1 -0
  28. package/.next/server/app/api/meetings/[id]/route.js +1 -0
  29. package/.next/server/app/api/meetings/[id]/route.js.nft.json +1 -0
  30. package/.next/server/app/api/meetings/[id]/slack/route.js +3 -0
  31. package/.next/server/app/api/meetings/[id]/slack/route.js.nft.json +1 -0
  32. package/.next/server/app/api/meetings/library/route.js +1 -0
  33. package/.next/server/app/api/meetings/library/route.js.nft.json +1 -0
  34. package/.next/server/app/api/meetings/route.js +1 -0
  35. package/.next/server/app/api/meetings/route.js.nft.json +1 -0
  36. package/.next/server/app/api/models/route.js +1 -0
  37. package/.next/server/app/api/models/route.js.nft.json +1 -0
  38. package/.next/server/app/api/notes/route.js +1 -0
  39. package/.next/server/app/api/notes/route.js.nft.json +1 -0
  40. package/.next/server/app/api/orgs/[id]/route.js +1 -0
  41. package/.next/server/app/api/orgs/[id]/route.js.nft.json +1 -0
  42. package/.next/server/app/api/orgs/route.js +1 -0
  43. package/.next/server/app/api/orgs/route.js.nft.json +1 -0
  44. package/.next/server/app/api/prs/inbox/route.js +1 -0
  45. package/.next/server/app/api/prs/inbox/route.js.nft.json +1 -0
  46. package/.next/server/app/api/prs/refresh/route.js +1 -0
  47. package/.next/server/app/api/prs/refresh/route.js.nft.json +1 -0
  48. package/.next/server/app/api/prs/route.js +1 -0
  49. package/.next/server/app/api/prs/route.js.nft.json +1 -0
  50. package/.next/server/app/api/session-names/route.js +1 -0
  51. package/.next/server/app/api/session-names/route.js.nft.json +1 -0
  52. package/.next/server/app/api/sessions/[id]/route.js +1 -0
  53. package/.next/server/app/api/sessions/[id]/route.js.nft.json +1 -0
  54. package/.next/server/app/api/sessions/route.js +1 -0
  55. package/.next/server/app/api/sessions/route.js.nft.json +1 -0
  56. package/.next/server/app/api/settings/auth/route.js +1 -0
  57. package/.next/server/app/api/settings/auth/route.js.nft.json +1 -0
  58. package/.next/server/app/api/settings/route.js +1 -0
  59. package/.next/server/app/api/settings/route.js.nft.json +1 -0
  60. package/.next/server/app/api/settings/transcription/route.js +1 -0
  61. package/.next/server/app/api/settings/transcription/route.js.nft.json +1 -0
  62. package/.next/server/app/api/skills/[name]/route.js +8 -0
  63. package/.next/server/app/api/skills/[name]/route.js.nft.json +1 -0
  64. package/.next/server/app/api/skills/marketplace/route.js +2 -0
  65. package/.next/server/app/api/skills/marketplace/route.js.nft.json +1 -0
  66. package/.next/server/app/api/skills/route.js +8 -0
  67. package/.next/server/app/api/skills/route.js.nft.json +1 -0
  68. package/.next/server/app/api/skills/view/route.js +8 -0
  69. package/.next/server/app/api/skills/view/route.js.nft.json +1 -0
  70. package/.next/server/app/api/slack/channels/route.js +1 -0
  71. package/.next/server/app/api/slack/channels/route.js.nft.json +1 -0
  72. package/.next/server/app/api/slack/configured/route.js +1 -0
  73. package/.next/server/app/api/slack/configured/route.js.nft.json +1 -0
  74. package/.next/server/app/api/slack/inbox/route.js +1 -0
  75. package/.next/server/app/api/slack/inbox/route.js.nft.json +1 -0
  76. package/.next/server/app/api/tasks/route.js +1 -0
  77. package/.next/server/app/api/tasks/route.js.nft.json +1 -0
  78. package/.next/server/app/api/usage/route.js +1 -0
  79. package/.next/server/app/api/usage/route.js.nft.json +1 -0
  80. package/.next/server/app/demo/page.js +1 -0
  81. package/.next/server/app/demo/page.js.nft.json +1 -0
  82. package/.next/server/app/demo/page_client-reference-manifest.js +1 -0
  83. package/.next/server/app/demo.html +1 -0
  84. package/.next/server/app/demo.meta +6 -0
  85. package/.next/server/app/demo.rsc +7 -0
  86. package/.next/server/app/favicon.ico/route.js +12 -0
  87. package/.next/server/app/favicon.ico/route.js.nft.json +1 -0
  88. package/.next/server/app/favicon.ico.body +0 -0
  89. package/.next/server/app/favicon.ico.meta +1 -0
  90. package/.next/server/app/index.html +1 -0
  91. package/.next/server/app/index.meta +5 -0
  92. package/.next/server/app/index.rsc +7 -0
  93. package/.next/server/app/page.js +10 -0
  94. package/.next/server/app/page.js.nft.json +1 -0
  95. package/.next/server/app/page_client-reference-manifest.js +1 -0
  96. package/.next/server/app-paths-manifest.json +36 -0
  97. package/.next/server/chunks/36.js +1 -0
  98. package/.next/server/chunks/471.js +2 -0
  99. package/.next/server/chunks/590.js +7 -0
  100. package/.next/server/chunks/621.js +1 -0
  101. package/.next/server/chunks/682.js +6 -0
  102. package/.next/server/chunks/904.js +1 -0
  103. package/.next/server/chunks/948.js +2 -0
  104. package/.next/server/chunks/972.js +12 -0
  105. package/.next/server/chunks/font-manifest.json +1 -0
  106. package/.next/server/font-manifest.json +1 -0
  107. package/.next/server/functions-config-manifest.json +1 -0
  108. package/.next/server/interception-route-rewrite-manifest.js +1 -0
  109. package/.next/server/middleware-build-manifest.js +1 -0
  110. package/.next/server/middleware-manifest.json +6 -0
  111. package/.next/server/middleware-react-loadable-manifest.js +1 -0
  112. package/.next/server/next-font-manifest.js +1 -0
  113. package/.next/server/next-font-manifest.json +1 -0
  114. package/.next/server/pages/404.html +1 -0
  115. package/.next/server/pages/500.html +1 -0
  116. package/.next/server/pages/_app.js +1 -0
  117. package/.next/server/pages/_app.js.nft.json +1 -0
  118. package/.next/server/pages/_document.js +1 -0
  119. package/.next/server/pages/_document.js.nft.json +1 -0
  120. package/.next/server/pages/_error.js +1 -0
  121. package/.next/server/pages/_error.js.nft.json +1 -0
  122. package/.next/server/pages-manifest.json +1 -0
  123. package/.next/server/server-reference-manifest.js +1 -0
  124. package/.next/server/server-reference-manifest.json +1 -0
  125. package/.next/server/webpack-runtime.js +1 -0
  126. package/.next/static/2gHioRND6aAzT4OB5OHDV/_buildManifest.js +1 -0
  127. package/.next/static/2gHioRND6aAzT4OB5OHDV/_ssgManifest.js +1 -0
  128. package/.next/static/chunks/117-0f4ac3c2c1871d4c.js +2 -0
  129. package/.next/static/chunks/171-d325f9625379d70a.js +1 -0
  130. package/.next/static/chunks/235.aef4cdc783360b73.js +1 -0
  131. package/.next/static/chunks/30d07d85.9045c666bb43d9e1.js +3 -0
  132. package/.next/static/chunks/app/_not-found/page-8ff6572bc7c9bc61.js +1 -0
  133. package/.next/static/chunks/app/demo/page-6711b34cd2af0e4a.js +1 -0
  134. package/.next/static/chunks/app/layout-d058836232e72324.js +1 -0
  135. package/.next/static/chunks/app/page-fedaef1e63f186c2.js +1 -0
  136. package/.next/static/chunks/fd9d1056-26bd8d656b496dba.js +1 -0
  137. package/.next/static/chunks/framework-f66176bb897dc684.js +1 -0
  138. package/.next/static/chunks/main-app-4b855ea14675b961.js +1 -0
  139. package/.next/static/chunks/main-e88dbd51c3bdafca.js +1 -0
  140. package/.next/static/chunks/pages/_app-72b849fbd24ac258.js +1 -0
  141. package/.next/static/chunks/pages/_error-7ba65e1336b92748.js +1 -0
  142. package/.next/static/chunks/polyfills-42372ed130431b0a.js +1 -0
  143. package/.next/static/chunks/webpack-1f89b7cb1fca69c4.js +1 -0
  144. package/.next/static/css/6e83ef44d507c857.css +3 -0
  145. package/.next/static/css/ab3e4b0f5035257a.css +1 -0
  146. package/.next/trace +23 -0
  147. package/.next/types/app/api/automations/existing/route.ts +343 -0
  148. package/.next/types/app/api/backends/route.ts +343 -0
  149. package/.next/types/app/api/diff/route.ts +343 -0
  150. package/.next/types/app/api/limits/route.ts +343 -0
  151. package/.next/types/app/api/meetings/[id]/route.ts +343 -0
  152. package/.next/types/app/api/meetings/[id]/slack/route.ts +343 -0
  153. package/.next/types/app/api/meetings/library/route.ts +343 -0
  154. package/.next/types/app/api/meetings/route.ts +343 -0
  155. package/.next/types/app/api/models/route.ts +343 -0
  156. package/.next/types/app/api/notes/route.ts +343 -0
  157. package/.next/types/app/api/orgs/[id]/route.ts +343 -0
  158. package/.next/types/app/api/orgs/route.ts +343 -0
  159. package/.next/types/app/api/prs/inbox/route.ts +343 -0
  160. package/.next/types/app/api/prs/refresh/route.ts +343 -0
  161. package/.next/types/app/api/prs/route.ts +343 -0
  162. package/.next/types/app/api/session-names/route.ts +343 -0
  163. package/.next/types/app/api/sessions/[id]/route.ts +343 -0
  164. package/.next/types/app/api/sessions/route.ts +343 -0
  165. package/.next/types/app/api/settings/auth/route.ts +343 -0
  166. package/.next/types/app/api/settings/route.ts +343 -0
  167. package/.next/types/app/api/settings/transcription/route.ts +343 -0
  168. package/.next/types/app/api/skills/[name]/route.ts +343 -0
  169. package/.next/types/app/api/skills/marketplace/route.ts +343 -0
  170. package/.next/types/app/api/skills/route.ts +343 -0
  171. package/.next/types/app/api/skills/view/route.ts +343 -0
  172. package/.next/types/app/api/slack/channels/route.ts +343 -0
  173. package/.next/types/app/api/slack/configured/route.ts +343 -0
  174. package/.next/types/app/api/slack/inbox/route.ts +343 -0
  175. package/.next/types/app/api/tasks/route.ts +343 -0
  176. package/.next/types/app/api/usage/route.ts +343 -0
  177. package/.next/types/app/demo/page.ts +79 -0
  178. package/.next/types/app/layout.ts +79 -0
  179. package/.next/types/app/page.ts +79 -0
  180. package/.next/types/package.json +1 -0
  181. package/.server-dist/server.js +600 -0
  182. package/.server-dist/src/lib/activeOrg.js +11 -0
  183. package/.server-dist/src/lib/audioCapture.js +157 -0
  184. package/.server-dist/src/lib/backends.js +209 -0
  185. package/.server-dist/src/lib/claudeAuth.js +57 -0
  186. package/.server-dist/src/lib/configFile.js +23 -0
  187. package/.server-dist/src/lib/dataDir.js +7 -0
  188. package/.server-dist/src/lib/diffReview.js +116 -0
  189. package/.server-dist/src/lib/existingAutomations.js +132 -0
  190. package/.server-dist/src/lib/ghInbox.js +151 -0
  191. package/.server-dist/src/lib/ghPrStatus.js +86 -0
  192. package/.server-dist/src/lib/gitUtils.js +27 -0
  193. package/.server-dist/src/lib/keepAwake.js +32 -0
  194. package/.server-dist/src/lib/liveSessionStore.js +89 -0
  195. package/.server-dist/src/lib/marketplace.js +63 -0
  196. package/.server-dist/src/lib/meetingAssistant.js +138 -0
  197. package/.server-dist/src/lib/meetingConfig.js +81 -0
  198. package/.server-dist/src/lib/meetingContext.js +82 -0
  199. package/.server-dist/src/lib/meetingManager.js +246 -0
  200. package/.server-dist/src/lib/meetingStore.js +198 -0
  201. package/.server-dist/src/lib/modelCatalog.js +114 -0
  202. package/.server-dist/src/lib/notesStore.js +67 -0
  203. package/.server-dist/src/lib/orgFilter.js +19 -0
  204. package/.server-dist/src/lib/orgParam.js +15 -0
  205. package/.server-dist/src/lib/orgRegistry.js +93 -0
  206. package/.server-dist/src/lib/pipelineView.js +62 -0
  207. package/.server-dist/src/lib/pipelines.js +427 -0
  208. package/.server-dist/src/lib/planLimits.js +101 -0
  209. package/.server-dist/src/lib/prDetector.js +16 -0
  210. package/.server-dist/src/lib/prScanCache.js +144 -0
  211. package/.server-dist/src/lib/prSessionEntries.js +96 -0
  212. package/.server-dist/src/lib/prTypes.js +2 -0
  213. package/.server-dist/src/lib/ptyManager.js +437 -0
  214. package/.server-dist/src/lib/reminders.js +10 -0
  215. package/.server-dist/src/lib/requestGuard.js +29 -0
  216. package/.server-dist/src/lib/sessionNameStore.js +69 -0
  217. package/.server-dist/src/lib/sessionStore.js +215 -0
  218. package/.server-dist/src/lib/settingsStore.js +51 -0
  219. package/.server-dist/src/lib/skillsReader.js +200 -0
  220. package/.server-dist/src/lib/slackBridge.js +270 -0
  221. package/.server-dist/src/lib/slackInbox.js +96 -0
  222. package/.server-dist/src/lib/slackWatchers.js +210 -0
  223. package/.server-dist/src/lib/statusDetector.js +50 -0
  224. package/.server-dist/src/lib/taskStore.js +42 -0
  225. package/.server-dist/src/lib/transcriber.js +61 -0
  226. package/.server-dist/src/lib/usageStore.js +254 -0
  227. package/.server-dist/src/lib/worktrees.js +42 -0
  228. package/.server-dist/tsconfig.server.tsbuildinfo +1 -0
  229. package/LICENSE +21 -0
  230. package/README.md +111 -2
  231. package/bin/polyergon.js +34 -0
  232. package/next.config.mjs +4 -0
  233. package/package.json +81 -4
  234. package/public/.gitkeep +0 -0
  235. package/public/apple-touch-icon.png +0 -0
  236. package/public/icon-192.png +0 -0
  237. package/public/icon-512.png +0 -0
  238. package/public/icon.svg +1 -0
  239. package/public/manifest.webmanifest +15 -0
@@ -0,0 +1,270 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.orgFile = exports.SlackError = void 0;
4
+ exports.classifySlackFailure = classifySlackFailure;
5
+ exports.parseChannels = parseChannels;
6
+ exports.listSlackChannels = listSlackChannels;
7
+ exports.toSlackMarkdown = toSlackMarkdown;
8
+ exports.postToSlack = postToSlack;
9
+ exports.parseThread = parseThread;
10
+ exports.readSlackThread = readSlackThread;
11
+ exports.timeFromPermalink = timeFromPermalink;
12
+ exports.parseMentions = parseMentions;
13
+ exports.fetchMentions = fetchMentions;
14
+ exports.slackMe = slackMe;
15
+ exports.parseAnswered = parseAnswered;
16
+ exports.isAnswered = isAnswered;
17
+ exports.replyInThread = replyInThread;
18
+ exports.addReaction = addReaction;
19
+ exports.draftReply = draftReply;
20
+ exports.parseRequests = parseRequests;
21
+ exports.newChannelRequests = newChannelRequests;
22
+ exports.draftChannelReply = draftChannelReply;
23
+ exports.slackConfigured = slackConfigured;
24
+ const fs_1 = require("fs");
25
+ const os_1 = require("os");
26
+ const path_1 = require("path");
27
+ const dataDir_1 = require("./dataDir");
28
+ const meetingAssistant_1 = require("./meetingAssistant");
29
+ const orgRegistry_1 = require("./orgRegistry");
30
+ function classifySlackFailure(text) {
31
+ if (/sign(ed)? ?in|log(ged)? ?in|re-?auth|authenticat|authori[sz]|reconnect|refused the connection|expired|token/i.test(text))
32
+ return 'auth';
33
+ if (/no slack|not (available|configured|connected|installed)|don'?t have (access to )?(a |the )?slack|no .*slack (tool|connector)/i.test(text))
34
+ return 'missing';
35
+ return 'other';
36
+ }
37
+ class SlackError extends Error {
38
+ constructor(message, problem) {
39
+ super(message);
40
+ this.problem = problem;
41
+ }
42
+ }
43
+ exports.SlackError = SlackError;
44
+ // Per-org cache file; Default keeps the original name
45
+ const orgFile = (base, orgId = orgRegistry_1.DEFAULT_ORG_ID) => (0, path_1.join)(dataDir_1.DATA_DIR, orgId === orgRegistry_1.DEFAULT_ORG_ID ? `${base}.json` : `${base}.${orgId.replace(/[^\w-]/g, '')}.json`);
46
+ exports.orgFile = orgFile;
47
+ const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
48
+ // Slack runs under the ORG's Claude config, so each org uses its own Slack connector/workspace.
49
+ function opts(model = 'claude-haiku-5-5', orgId = orgRegistry_1.DEFAULT_ORG_ID) {
50
+ var _a, _b, _c;
51
+ const org = (_a = orgRegistry_1.orgRegistry.get(orgId)) !== null && _a !== void 0 ? _a : orgRegistry_1.orgRegistry.get(orgRegistry_1.DEFAULT_ORG_ID);
52
+ (0, fs_1.mkdirSync)(dataDir_1.DATA_DIR, { recursive: true });
53
+ return { cwd: dataDir_1.DATA_DIR, configDir: (_b = org === null || org === void 0 ? void 0 : org.configDir) !== null && _b !== void 0 ? _b : null, model, extraEnv: slackEnv((_c = org === null || org === void 0 ? void 0 : org.configDir) !== null && _c !== void 0 ? _c : null) };
54
+ }
55
+ // In -p, Claude dedups the Slack plugin against the "claude.ai Slack" connector; when that
56
+ // connector isn't signed in, BOTH get dropped. Orgs with their own config use the plugin, so
57
+ // turn the claude.ai connectors off there. Default keeps its signed-in claude.ai Slack.
58
+ const slackEnv = (configDir) => configDir ? { ENABLE_CLAUDEAI_MCP_SERVERS: 'false' } : undefined;
59
+ // Pulls the first JSON array out of a reply (tolerates fences / prose).
60
+ function parseChannels(raw) {
61
+ const start = raw.indexOf('['), end = raw.lastIndexOf(']');
62
+ if (start === -1 || end <= start)
63
+ return [];
64
+ try {
65
+ const arr = JSON.parse(raw.slice(start, end + 1));
66
+ return (Array.isArray(arr) ? arr : [])
67
+ .filter((c) => !!c && typeof c.name === 'string')
68
+ .map(c => { var _a; return ({ id: String((_a = c.id) !== null && _a !== void 0 ? _a : ''), name: c.name.replace(/^#/, '') }); })
69
+ .sort((a, b) => a.name.localeCompare(b.name));
70
+ }
71
+ catch (_a) {
72
+ return [];
73
+ }
74
+ }
75
+ async function listSlackChannels(refresh = false, orgId = orgRegistry_1.DEFAULT_ORG_ID) {
76
+ var _a;
77
+ if (!refresh) {
78
+ try {
79
+ const cached = JSON.parse((0, fs_1.readFileSync)((0, exports.orgFile)('slack-channels', orgId), 'utf-8'));
80
+ if (Date.now() - cached.fetchedAt < CACHE_TTL_MS && ((_a = cached.channels) === null || _a === void 0 ? void 0 : _a.length))
81
+ return cached;
82
+ }
83
+ catch ( /* no cache */_b) { /* no cache */ }
84
+ }
85
+ const { result } = await (0, meetingAssistant_1.runClaude)('Use the Slack connector to list every Slack channel I am a member of (public and private, not DMs). ' +
86
+ 'Page through all results. Respond with ONLY a JSON array, no prose: [{"id": "C123", "name": "channel-name"}, ...]', opts(undefined, orgId));
87
+ const channels = parseChannels(result);
88
+ if (!channels.length)
89
+ throw new SlackError(result.trim().slice(0, 300) || 'No channels came back', classifySlackFailure(result));
90
+ const data = { channels, fetchedAt: Date.now() };
91
+ (0, fs_1.writeFileSync)((0, exports.orgFile)('slack-channels', orgId), JSON.stringify(data));
92
+ return data;
93
+ }
94
+ // Meeting summary markdown → Slack mrkdwn
95
+ function toSlackMarkdown(md) {
96
+ return md
97
+ .replace(/^#{1,6}\s+(.*)$/gm, '*$1*')
98
+ .replace(/\*\*([^*]+)\*\*/g, '*$1*')
99
+ .replace(/^(\s*)[-*]\s+/gm, '$1• ')
100
+ .trim();
101
+ }
102
+ // Posts and returns the message permalink when Slack reports one.
103
+ async function postToSlack(channel, text, orgId = orgRegistry_1.DEFAULT_ORG_ID) {
104
+ var _a, _b;
105
+ const target = channel.id ? `${channel.id} (#${channel.name})` : `#${channel.name}`;
106
+ const { result } = await (0, meetingAssistant_1.runClaude)(`Use the Slack connector to post the message below to the Slack channel ${target}. ` +
107
+ 'Post it exactly as written, as one message, without changes or additions. ' +
108
+ 'Reply with only "OK <the posted message permalink>" when posted, or "FAILED: <reason>".\n\n<message>\n' + text + '\n</message>', opts(undefined, orgId));
109
+ const reply = result.trim();
110
+ if (!/^OK\b/i.test(reply))
111
+ throw new Error(reply.replace(/^FAILED:?\s*/i, '') || 'Slack did not confirm the post');
112
+ return { permalink: (_b = (_a = reply.match(/https:\/\/\S+slack\.com\/archives\/\S+/)) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : null };
113
+ }
114
+ function parseThread(raw) {
115
+ const start = raw.indexOf('{'), end = raw.lastIndexOf('}');
116
+ if (start === -1 || end <= start)
117
+ return null;
118
+ try {
119
+ const j = JSON.parse(raw.slice(start, end + 1));
120
+ const strs = (x) => (Array.isArray(x) ? x.filter((v) => typeof v === 'string') : []);
121
+ return {
122
+ reviewers: strs(j.reviewers),
123
+ reactions: (Array.isArray(j.reactions) ? j.reactions : []).map((r) => { var _a; return ({ emoji: String((_a = r.emoji) !== null && _a !== void 0 ? _a : ''), users: strs(r.users) }); }).filter((r) => r.emoji),
124
+ replies: (Array.isArray(j.replies) ? j.replies : []).map((r) => { var _a, _b; return ({ user: String((_a = r.user) !== null && _a !== void 0 ? _a : ''), text: String((_b = r.text) !== null && _b !== void 0 ? _b : '').slice(0, 300) }); }).slice(-5),
125
+ };
126
+ }
127
+ catch (_a) {
128
+ return null;
129
+ }
130
+ }
131
+ // Reads replies and reactions on a posted message and picks out who is reviewing.
132
+ async function readSlackThread(permalink, orgId = orgRegistry_1.DEFAULT_ORG_ID) {
133
+ const { result } = await (0, meetingAssistant_1.runClaude)(`Use the Slack connector to read the Slack message at ${permalink}: its reactions and all thread replies. ` +
134
+ 'Respond with ONLY a JSON object, no prose: {"reviewers": [display names of people who said they will review, are reviewing, or reacted with eyes], ' +
135
+ '"reactions": [{"emoji": "eyes", "users": ["Name"]}], "replies": [{"user": "Name", "text": "..."}]}', opts(undefined, orgId));
136
+ return parseThread(result);
137
+ }
138
+ // Slack permalinks carry the message time: …/p1795174145426439 → 1795174145.426439 s
139
+ function timeFromPermalink(permalink) {
140
+ const m = permalink.match(/\/p(\d{10})(\d{6})/);
141
+ return m ? new Date(Number(m[1]) * 1000).toISOString() : '';
142
+ }
143
+ function parseMentions(raw) {
144
+ const start = raw.indexOf('['), end = raw.lastIndexOf(']');
145
+ if (start === -1 || end <= start)
146
+ return [];
147
+ try {
148
+ const arr = JSON.parse(raw.slice(start, end + 1));
149
+ const seen = new Set();
150
+ return (Array.isArray(arr) ? arr : [])
151
+ .filter((m) => typeof (m === null || m === void 0 ? void 0 : m.permalink) === 'string' && /slack\.com\/archives\//.test(m.permalink) && !seen.has(m.permalink) && !!seen.add(m.permalink))
152
+ .map((m) => { var _a, _b, _c; return ({ permalink: m.permalink, channel: String((_a = m.channel) !== null && _a !== void 0 ? _a : '').replace(/^#/, ''), author: String((_b = m.author) !== null && _b !== void 0 ? _b : ''), text: String((_c = m.text) !== null && _c !== void 0 ? _c : '').slice(0, 2000), time: timeFromPermalink(m.permalink), isDm: !!m.isDm, checked: false }); })
153
+ .sort((a, b) => b.time.localeCompare(a.time));
154
+ }
155
+ catch (_a) {
156
+ return [];
157
+ }
158
+ }
159
+ // Step 1 (fast): every recent mention and DM, answered or not.
160
+ async function fetchMentions(days = 7, orgId = orgRegistry_1.DEFAULT_ORG_ID) {
161
+ const { result } = await (0, meetingAssistant_1.runClaude)(`Use the Slack connector. Find messages from the last ${days} days that @-mention me (the signed-in Slack user), and direct messages sent to me. ` +
162
+ 'Skip bot and automated messages. At most 40, newest first. ' +
163
+ 'Respond with ONLY a JSON array, no prose: [{"permalink": "https://…slack.com/archives/…", "channel": "channel name, or the person for a DM", "author": "display name", "text": "the message text", "isDm": false}]', Object.assign(Object.assign({}, opts('claude-sonnet-5-5', orgId)), { timeoutMs: 240000 }));
164
+ const found = parseMentions(result);
165
+ if (!found.length && !/^\s*\[\s*\]\s*$/.test(result.replace(/```(json)?/g, '')))
166
+ throw new SlackError(result.trim().slice(0, 300), classifySlackFailure(result));
167
+ return found;
168
+ }
169
+ // Who "me" is in Slack, looked up once and cached (the checks below need it).
170
+ async function slackMe(orgId = orgRegistry_1.DEFAULT_ORG_ID) {
171
+ try {
172
+ return JSON.parse((0, fs_1.readFileSync)((0, exports.orgFile)('slack-me', orgId), 'utf-8'));
173
+ }
174
+ catch ( /* look it up */_a) { /* look it up */ }
175
+ const { result } = await (0, meetingAssistant_1.runClaude)('Use the Slack connector to look up the profile of the signed-in Slack user (me). Respond with ONLY JSON: {"id": "U…", "name": "display name"}', opts(undefined, orgId));
176
+ const m = result.match(/\{[\s\S]*\}/);
177
+ const me = m ? JSON.parse(m[0]) : null;
178
+ if (!(me === null || me === void 0 ? void 0 : me.id))
179
+ throw new SlackError(result.trim().slice(0, 300) || 'Could not find your Slack user', classifySlackFailure(result));
180
+ (0, fs_1.writeFileSync)((0, exports.orgFile)('slack-me', orgId), JSON.stringify(me));
181
+ return me;
182
+ }
183
+ function parseAnswered(raw) {
184
+ const m = raw.match(/\{[\s\S]*\}/);
185
+ if (!m)
186
+ throw new Error('Unreadable answer check');
187
+ const j = JSON.parse(m[0]);
188
+ const evidence = typeof j.evidence === 'string' && j.evidence.trim() ? j.evidence.trim() : null;
189
+ // Only trust "answered" when it comes with the actual reply as proof
190
+ return { answered: j.answered === true && (!!evidence || j.reacted === true), evidence };
191
+ }
192
+ // Step 2, one message at a time: did I answer it? Requires proof (my reply text).
193
+ async function isAnswered(m, me, orgId = orgRegistry_1.DEFAULT_ORG_ID) {
194
+ const where = m.isDm
195
+ ? 'This is a direct message: read the messages in that same DM conversation that come AFTER it (not just thread replies).'
196
+ : 'Read its thread replies, and also the next messages in the channel in case I answered there.';
197
+ const { result } = await (0, meetingAssistant_1.runClaude)(`Use the Slack connector. I am Slack user ${me.id} (${me.name}). Look at the Slack message at ${m.permalink}. ${where} ` +
198
+ `Decide whether I (${me.id}) already answered it after it was posted, or reacted to it with ✅ / white_check_mark. ` +
199
+ 'Respond with ONLY JSON: {"answered": true or false, "reacted": true or false, "evidence": "the exact text of my reply, or empty"}', Object.assign(Object.assign({}, opts(undefined, orgId)), { timeoutMs: 120000 }));
200
+ return parseAnswered(result).answered;
201
+ }
202
+ async function replyInThread(permalink, text, orgId = orgRegistry_1.DEFAULT_ORG_ID) {
203
+ const { result } = await (0, meetingAssistant_1.runClaude)(`Use the Slack connector to reply in the thread of the Slack message at ${permalink}. ` +
204
+ 'Post the reply below exactly as written, as one message. Reply with only "OK" when posted, or "FAILED: <reason>".\n\n<reply>\n' + text + '\n</reply>', opts(undefined, orgId));
205
+ if (!/^OK\b/i.test(result.trim()))
206
+ throw new Error(result.trim().replace(/^FAILED:?\s*/i, '') || 'Slack did not confirm the reply');
207
+ }
208
+ async function addReaction(permalink, emoji, orgId = orgRegistry_1.DEFAULT_ORG_ID) {
209
+ await (0, meetingAssistant_1.runClaude)(`Use the Slack connector to add the :${emoji}: reaction to the Slack message at ${permalink}. Reply with only "OK" or "FAILED: <reason>".`, opts(undefined, orgId));
210
+ }
211
+ // Suggested reply, in the user's voice, from the message and its thread.
212
+ // ctx: a related session. Drafts from a FORKED copy of it (knows the work; live session untouched).
213
+ async function draftReply(permalink, orgId = orgRegistry_1.DEFAULT_ORG_ID, ctx = null) {
214
+ const prompt = `Use the Slack connector to read the Slack message at ${permalink} and its whole thread. ` +
215
+ 'Write a short, helpful reply that I (the signed-in user, who was tagged) could send. Match the thread\'s language and tone. ' +
216
+ (ctx ? 'Use what you know from this conversation and the code here. ' : '') +
217
+ 'If you cannot know the answer, write a reply that says what I will check and by when. Respond with ONLY the reply text.';
218
+ const base = opts('claude-sonnet-5-5', orgId);
219
+ const { result } = ctx
220
+ ? await (0, meetingAssistant_1.runClaude)(prompt, Object.assign(Object.assign({}, base), { cwd: ctx.cwd, model: null, resumeId: ctx.resumeId, forkSession: true, timeoutMs: 300000 }))
221
+ : await (0, meetingAssistant_1.runClaude)(prompt, base);
222
+ return result.trim();
223
+ }
224
+ function parseRequests(raw) {
225
+ return parseMentions(raw).map(m => ({ permalink: m.permalink, author: m.author, text: m.text, time: m.time }));
226
+ }
227
+ // New questions/requests in a channel since a time that nobody has answered yet.
228
+ async function newChannelRequests(channel, sinceIso, orgId = orgRegistry_1.DEFAULT_ORG_ID) {
229
+ const target = channel.id ? `${channel.id} (#${channel.name})` : `#${channel.name}`;
230
+ const { result } = await (0, meetingAssistant_1.runClaude)(`Use the Slack connector to read the Slack channel ${target}: messages posted after ${sinceIso}. ` +
231
+ 'Channel history shows only top-level posts, so ALSO open every thread whose latest reply is after that time (even if the thread started earlier) and read its replies. ' +
232
+ 'Pick the messages (top-level or thread replies) that ask a question or request something and that nobody but the asker has answered since. ' +
233
+ 'Several follow-ups from the same person in one thread count as one request: return only their latest message, with the request summarized in "text". ' +
234
+ 'Skip bots, my own messages, and chatter that needs no answer. ' +
235
+ 'Respond with ONLY a JSON array, no prose: [{"permalink": "https://…slack.com/archives/…", "author": "display name", "text": "the message text"}]', Object.assign(Object.assign({}, opts('claude-sonnet-5-5', orgId)), { timeoutMs: 240000 }));
236
+ return parseRequests(result);
237
+ }
238
+ // Draft a reply. With ctx, Claude answers from a forked copy of that session
239
+ // (its knowledge and repo), never touching the live session.
240
+ async function draftChannelReply(r, channel, ctx, orgId = orgRegistry_1.DEFAULT_ORG_ID, extra = {}) {
241
+ var _a, _b;
242
+ const prompt = `Someone asked in Slack #${channel} (${r.permalink}). ${r.author} wrote:\n"""\n${r.text}\n"""\n` +
243
+ 'Read the thread with the Slack connector if you need more context. Draft a short, accurate reply I could post in the thread. ' +
244
+ (((_a = extra.knowledge) === null || _a === void 0 ? void 0 : _a.trim()) ? `Knowledge sources to check first (web links, files/folders on this Mac, Slack channels, notes):\n${extra.knowledge.trim()}\n` : '') +
245
+ (((_b = extra.instructions) === null || _b === void 0 ? void 0 : _b.trim()) ? `How to answer (follow this):\n${extra.instructions.trim()}\n` : '') +
246
+ 'Use what you know from this conversation and the code here. If you are not sure, say what you would check instead of guessing. ' +
247
+ 'Respond with ONLY the reply text.';
248
+ const { result } = ctx
249
+ ? await (0, meetingAssistant_1.runClaude)(prompt, { cwd: ctx.cwd, configDir: ctx.configDir, model: null, extraEnv: slackEnv(ctx.configDir), resumeId: ctx.resumeId, forkSession: true, timeoutMs: 300000 })
250
+ : await (0, meetingAssistant_1.runClaude)(prompt, Object.assign(Object.assign({}, opts('claude-sonnet-5-5', orgId)), { timeoutMs: 240000 }));
251
+ return result.trim();
252
+ }
253
+ // Cheap check (no Claude call): Slack plugin enabled, a Slack MCP server configured,
254
+ // or Slack already worked for this org. claude.ai connectors aren't visible on disk,
255
+ // so the last check covers those after the first successful run.
256
+ function slackConfigured(orgId = orgRegistry_1.DEFAULT_ORG_ID) {
257
+ var _a, _b, _c, _d;
258
+ if ((0, fs_1.existsSync)((0, exports.orgFile)('slack-me', orgId)) || (0, fs_1.existsSync)((0, exports.orgFile)('slack-channels', orgId)))
259
+ return true;
260
+ const dir = (_b = (_a = orgRegistry_1.orgRegistry.get(orgId)) === null || _a === void 0 ? void 0 : _a.configDir) !== null && _b !== void 0 ? _b : null;
261
+ const read = (f) => { try {
262
+ return JSON.parse((0, fs_1.readFileSync)(f, 'utf-8'));
263
+ }
264
+ catch (_a) {
265
+ return {};
266
+ } };
267
+ const plugins = (_c = read((0, path_1.join)(dir !== null && dir !== void 0 ? dir : (0, path_1.join)((0, os_1.homedir)(), '.claude'), 'settings.json')).enabledPlugins) !== null && _c !== void 0 ? _c : {};
268
+ const servers = (_d = read(dir ? (0, path_1.join)(dir, '.claude.json') : (0, path_1.join)((0, os_1.homedir)(), '.claude.json')).mcpServers) !== null && _d !== void 0 ? _d : {};
269
+ return Object.entries(plugins).some(([k, on]) => on && /^slack@/.test(k)) || Object.keys(servers).some(k => /slack/i.test(k));
270
+ }
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getInbox = getInbox;
4
+ exports.refreshInbox = refreshInbox;
5
+ exports.markDone = markDone;
6
+ const fs_1 = require("fs");
7
+ const dataDir_1 = require("./dataDir");
8
+ const slackBridge_1 = require("./slackBridge");
9
+ const orgRegistry_1 = require("./orgRegistry");
10
+ // One inbox file per org (each org has its own Slack workspace)
11
+ function read(orgId) {
12
+ try {
13
+ return Object.assign({ items: [], fetchedAt: 0, done: [] }, JSON.parse((0, fs_1.readFileSync)((0, slackBridge_1.orgFile)('slack-inbox', orgId), 'utf-8')));
14
+ }
15
+ catch (_a) {
16
+ return { items: [], fetchedAt: 0, done: [] };
17
+ }
18
+ }
19
+ function write(orgId, f) {
20
+ (0, fs_1.mkdirSync)(dataDir_1.DATA_DIR, { recursive: true });
21
+ (0, fs_1.writeFileSync)((0, slackBridge_1.orgFile)('slack-inbox', orgId), JSON.stringify(f, null, 2));
22
+ }
23
+ // Refresh progress lives in the file, not module memory: dev-mode recompiles
24
+ // (and the server's separate module copy) would otherwise lose it.
25
+ const STALE_MS = 15 * 60000;
26
+ const IDLE = { stage: 'idle', startedAt: 0, error: null };
27
+ function progressOf(f) {
28
+ var _a;
29
+ const p = (_a = f.progress) !== null && _a !== void 0 ? _a : IDLE;
30
+ return p.stage !== 'idle' && Date.now() - p.startedAt > STALE_MS ? Object.assign(Object.assign({}, IDLE), { error: p.error }) : p;
31
+ }
32
+ function setProgress(orgId, patch) {
33
+ const f = read(orgId);
34
+ write(orgId, Object.assign(Object.assign({}, f), { progress: Object.assign(Object.assign({}, progressOf(f)), patch) }));
35
+ }
36
+ function getInbox(orgId = orgRegistry_1.DEFAULT_ORG_ID) {
37
+ const f = read(orgId);
38
+ const done = new Set(f.done);
39
+ const progress = progressOf(f);
40
+ return Object.assign({ items: f.items.filter(i => !done.has(i.permalink)), fetchedAt: f.fetchedAt, refreshing: progress.stage !== 'idle' }, progress);
41
+ }
42
+ // Two steps so cards appear fast: find mentions (~15s), then drop the answered ones.
43
+ async function refreshInbox(orgId = orgRegistry_1.DEFAULT_ORG_ID) {
44
+ if (progressOf(read(orgId)).stage !== 'idle')
45
+ return;
46
+ setProgress(orgId, { stage: 'searching', startedAt: Date.now(), error: null, problem: null });
47
+ try {
48
+ const found = await (0, slackBridge_1.fetchMentions)(7, orgId);
49
+ // Keep what we already know is open; new ones start unchecked
50
+ const known = new Map(read(orgId).items.filter(i => i.checked).map(i => [i.permalink, i]));
51
+ write(orgId, Object.assign(Object.assign({}, read(orgId)), { items: found.map(m => { var _a; return (_a = known.get(m.permalink)) !== null && _a !== void 0 ? _a : m; }), fetchedAt: Date.now() }));
52
+ setProgress(orgId, { stage: 'checking' });
53
+ // Re-check every card (you may have answered since), 4 at a time; answered
54
+ // ones disappear as each check lands. A failed check keeps the card.
55
+ const me = await (0, slackBridge_1.slackMe)(orgId);
56
+ const queue = [...found];
57
+ const checker = async () => {
58
+ for (let m = queue.shift(); m; m = queue.shift()) {
59
+ let answered = false;
60
+ try {
61
+ answered = await (0, slackBridge_1.isAnswered)(m, me, orgId);
62
+ }
63
+ catch ( /* keep it */_a) { /* keep it */ }
64
+ const f = read(orgId);
65
+ write(orgId, Object.assign(Object.assign({}, f), { items: answered ? f.items.filter(i => i.permalink !== m.permalink) : f.items.map(i => (i.permalink === m.permalink ? Object.assign(Object.assign({}, i), { checked: true }) : i)) }));
66
+ }
67
+ };
68
+ await Promise.all([checker(), checker(), checker(), checker()]);
69
+ // Step 3: a suggested reply per card, 4 at a time, saved as each one lands
70
+ setProgress(orgId, { stage: 'suggesting' });
71
+ const todo = read(orgId).items.filter(i => !i.suggestion);
72
+ const worker = async () => {
73
+ for (let m = todo.shift(); m; m = todo.shift()) {
74
+ try {
75
+ const suggestion = await (0, slackBridge_1.draftReply)(m.permalink, orgId);
76
+ const f = read(orgId);
77
+ write(orgId, Object.assign(Object.assign({}, f), { items: f.items.map(i => (i.permalink === m.permalink ? Object.assign(Object.assign({}, i), { suggestion }) : i)) }));
78
+ }
79
+ catch ( /* leave this card without a suggestion */_a) { /* leave this card without a suggestion */ }
80
+ }
81
+ };
82
+ await Promise.all([worker(), worker(), worker(), worker()]);
83
+ }
84
+ catch (e) {
85
+ const msg = e.message;
86
+ setProgress(orgId, { error: msg, problem: e instanceof slackBridge_1.SlackError ? e.problem : (0, slackBridge_1.classifySlackFailure)(msg) });
87
+ }
88
+ finally {
89
+ setProgress(orgId, { stage: 'idle' });
90
+ }
91
+ }
92
+ function markDone(permalink, orgId = orgRegistry_1.DEFAULT_ORG_ID) {
93
+ const f = read(orgId);
94
+ if (!f.done.includes(permalink))
95
+ write(orgId, Object.assign(Object.assign({}, f), { done: [...f.done, permalink].slice(-500) }));
96
+ }
@@ -0,0 +1,210 @@
1
+ "use strict";
2
+ var _a;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.slackWatchers = void 0;
5
+ const fs_1 = require("fs");
6
+ const path_1 = require("path");
7
+ const crypto_1 = require("crypto");
8
+ const dataDir_1 = require("./dataDir");
9
+ const liveSessionStore_1 = require("./liveSessionStore");
10
+ const orgRegistry_1 = require("./orgRegistry");
11
+ const slackBridge_1 = require("./slackBridge");
12
+ const FILE = (0, path_1.join)(dataDir_1.DATA_DIR, 'slack-watchers.json');
13
+ class SlackWatcherEngine {
14
+ constructor() {
15
+ this.items = [];
16
+ this.listeners = new Set();
17
+ this.started = false;
18
+ }
19
+ start() {
20
+ if (this.started)
21
+ return;
22
+ this.started = true;
23
+ try {
24
+ this.items = JSON.parse((0, fs_1.readFileSync)(FILE, 'utf-8')).map((w) => (Object.assign(Object.assign({}, w), { checking: false })));
25
+ }
26
+ catch (_a) {
27
+ this.items = [];
28
+ }
29
+ setInterval(() => this.items.filter(w => w.status === 'running' && Date.now() - w.lastRunAt >= w.intervalMin * 60000).forEach(w => this.run(w.id)), 60000);
30
+ }
31
+ on(fn) { this.listeners.add(fn); return () => { this.listeners.delete(fn); }; }
32
+ list() { return this.items; }
33
+ save(notify) {
34
+ (0, fs_1.mkdirSync)(dataDir_1.DATA_DIR, { recursive: true });
35
+ (0, fs_1.writeFileSync)(FILE, JSON.stringify(this.items, null, 2));
36
+ this.listeners.forEach(fn => fn({ type: 'slack-watchers', items: this.items, notify }));
37
+ }
38
+ log(w, text, notify, extra = {}) {
39
+ w.log = [...w.log, Object.assign({ t: Date.now(), text }, extra)].slice(-200);
40
+ this.save(notify);
41
+ }
42
+ create(input) {
43
+ var _a, _b, _c, _d, _e;
44
+ if (!((_a = input.channel) === null || _a === void 0 ? void 0 : _a.name))
45
+ return { error: 'Pick a channel' };
46
+ if (input.liveId && !((_b = liveSessionStore_1.liveSessionStore.get(input.liveId)) === null || _b === void 0 ? void 0 : _b.claudeSessionId))
47
+ return { error: 'That session has no Claude conversation yet' };
48
+ const w = {
49
+ id: (0, crypto_1.randomUUID)(), channel: input.channel, liveId: input.liveId, orgId: (input.liveId && ((_c = liveSessionStore_1.liveSessionStore.get(input.liveId)) === null || _c === void 0 ? void 0 : _c.orgId)) || input.orgId, mode: input.mode === 'auto' ? 'auto' : 'approve',
50
+ intervalMin: Math.min(60, Math.max(2, Math.round(input.intervalMin) || 5)), status: 'running',
51
+ lastRunAt: Date.now(), checking: false, items: [], log: [], createdAt: Date.now(),
52
+ knowledge: String((_d = input.knowledge) !== null && _d !== void 0 ? _d : '').slice(0, 4000), instructions: String((_e = input.instructions) !== null && _e !== void 0 ? _e : '').slice(0, 4000),
53
+ };
54
+ this.items = [...this.items, w];
55
+ this.log(w, `Watching #${w.channel.name} for new questions (every ${w.intervalMin} min)`);
56
+ return w;
57
+ }
58
+ // Edit: everything but the channel
59
+ update(id, patch) {
60
+ var _a;
61
+ const w = this.items.find(x => x.id === id);
62
+ if (!w)
63
+ return { error: 'Not found' };
64
+ if (patch.liveId && !((_a = liveSessionStore_1.liveSessionStore.get(patch.liveId)) === null || _a === void 0 ? void 0 : _a.claudeSessionId))
65
+ return { error: 'That session has no Claude conversation yet' };
66
+ if (patch.liveId !== undefined)
67
+ w.liveId = patch.liveId || null;
68
+ if (patch.mode)
69
+ w.mode = patch.mode === 'auto' ? 'auto' : 'approve';
70
+ if (patch.intervalMin !== undefined)
71
+ w.intervalMin = Math.min(60, Math.max(2, Math.round(patch.intervalMin) || 5));
72
+ if (patch.knowledge !== undefined)
73
+ w.knowledge = String(patch.knowledge).slice(0, 4000);
74
+ if (patch.instructions !== undefined)
75
+ w.instructions = String(patch.instructions).slice(0, 4000);
76
+ this.log(w, 'You edited the watcher', undefined, { detail: [`Mode: ${w.mode === 'auto' ? 'answer automatically' : 'you approve'}`, `Every ${w.intervalMin} min`, w.knowledge ? `Knowledge:\n${w.knowledge}` : '', w.instructions ? `Instructions:\n${w.instructions}` : ''].filter(Boolean).join('\n') });
77
+ return null;
78
+ }
79
+ setSession(id, liveId) {
80
+ var _a;
81
+ const w = this.items.find(x => x.id === id);
82
+ if (!w)
83
+ return;
84
+ if (liveId && !((_a = liveSessionStore_1.liveSessionStore.get(liveId)) === null || _a === void 0 ? void 0 : _a.claudeSessionId))
85
+ return;
86
+ w.liveId = liveId;
87
+ this.log(w, liveId ? 'Drafts now use a session\'s knowledge' : 'Drafts now use general knowledge');
88
+ }
89
+ stop(id) {
90
+ const w = this.items.find(x => x.id === id);
91
+ if (w && w.status === 'running') {
92
+ w.status = 'stopped';
93
+ this.log(w, 'Stopped by you');
94
+ }
95
+ }
96
+ // Check the channel now (also runs on the interval).
97
+ async run(id) {
98
+ var _a;
99
+ const w = this.items.find(x => x.id === id);
100
+ if (!w || w.status !== 'running' || w.checking)
101
+ return;
102
+ // First check: last 24h too, so questions already waiting are caught. Later: since last check (small overlap; dedupe below)
103
+ const since = new Date(w.checkedOnce ? w.lastRunAt - 2 * 60000 : w.createdAt - SlackWatcherEngine.BACKLOG_MS).toISOString();
104
+ w.checking = true;
105
+ w.lastRunAt = Date.now();
106
+ this.save();
107
+ try {
108
+ const seen = new Set(w.items.map(i => i.permalink));
109
+ const fresh = (await (0, slackBridge_1.newChannelRequests)(w.channel, since, w.orgId)).filter(r => !seen.has(r.permalink));
110
+ if (fresh.length) {
111
+ w.items = [...fresh.map(r => (Object.assign(Object.assign({}, r), { state: 'drafting', draft: null }))), ...w.items].slice(0, 100);
112
+ this.log(w, `Found ${fresh.length} question${fresh.length > 1 ? 's' : ''} in #${w.channel.name}`, undefined, { detail: fresh.map(r => `${r.author}: ${r.text}`).join('\n\n') });
113
+ for (const r of fresh)
114
+ await this.draft(w, r.permalink);
115
+ }
116
+ else {
117
+ // One rolling line, not one per check
118
+ const line = `Checked ${new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}: no new questions`;
119
+ if ((_a = w.log.at(-1)) === null || _a === void 0 ? void 0 : _a.text.startsWith('Checked '))
120
+ w.log = w.log.slice(0, -1);
121
+ this.log(w, line);
122
+ }
123
+ w.checkedOnce = true;
124
+ }
125
+ catch (e) {
126
+ this.log(w, `Check failed: ${e.message}`);
127
+ }
128
+ finally {
129
+ w.checking = false;
130
+ this.save();
131
+ }
132
+ }
133
+ ctxFor(w) {
134
+ var _a, _b;
135
+ const s = w.liveId ? liveSessionStore_1.liveSessionStore.get(w.liveId) : null;
136
+ return (s === null || s === void 0 ? void 0 : s.claudeSessionId) ? { resumeId: s.claudeSessionId, cwd: s.cwd, configDir: (_b = (_a = orgRegistry_1.orgRegistry.get(s.orgId)) === null || _a === void 0 ? void 0 : _a.configDir) !== null && _b !== void 0 ? _b : null } : null;
137
+ }
138
+ async draft(w, permalink) {
139
+ const it = w.items.find(i => i.permalink === permalink);
140
+ if (!it)
141
+ return;
142
+ try {
143
+ it.draft = await (0, slackBridge_1.draftChannelReply)(it, w.channel.name, this.ctxFor(w), w.orgId, { knowledge: w.knowledge, instructions: w.instructions });
144
+ // Auto-answer only messages posted after you started the watcher; older backlog waits for your approval
145
+ const backlog = !(Date.parse((0, slackBridge_1.timeFromPermalink)(it.permalink) || '') >= w.createdAt); // unknown time counts as backlog
146
+ if (w.mode === 'auto' && !backlog) {
147
+ await (0, slackBridge_1.replyInThread)(it.permalink, it.draft, w.orgId);
148
+ it.state = 'sent';
149
+ this.log(w, `Answered ${it.author} automatically`, undefined, { detail: it.draft, link: it.permalink });
150
+ }
151
+ else {
152
+ it.state = 'pending';
153
+ this.log(w, `Drafted a reply to ${it.author}${backlog && w.mode === 'auto' ? ' (older message: waits for your OK)' : ''}`, { title: `#${w.channel.name}: reply ready`, body: `${it.author}: ${it.text.slice(0, 80)}` }, { detail: it.draft, link: it.permalink });
154
+ }
155
+ }
156
+ catch (e) {
157
+ it.state = 'failed';
158
+ it.error = e.message;
159
+ this.log(w, `Couldn't draft for ${it.author}`, undefined, { detail: it.error, link: it.permalink });
160
+ }
161
+ }
162
+ // Your click: post the (possibly edited) draft in the thread.
163
+ async send(id, permalink, text) {
164
+ const w = this.items.find(x => x.id === id);
165
+ const it = w === null || w === void 0 ? void 0 : w.items.find(i => i.permalink === permalink);
166
+ if (!w || !it)
167
+ return { error: 'Not found' };
168
+ // Only one send per question: a second click while posting (or after) does nothing
169
+ if (it.state !== 'pending' && it.state !== 'failed')
170
+ return { error: it.state === 'sent' ? 'Already answered' : 'Already sending' };
171
+ const body = (text || it.draft || '').trim();
172
+ if (!body)
173
+ return { error: 'Nothing to send' };
174
+ const before = it.state;
175
+ it.state = 'sending';
176
+ this.save();
177
+ try {
178
+ await (0, slackBridge_1.replyInThread)(permalink, body.slice(0, 4000), w.orgId);
179
+ it.draft = body;
180
+ it.state = 'sent';
181
+ this.log(w, `You sent a reply to ${it.author}`, undefined, { detail: body, link: permalink });
182
+ return null;
183
+ }
184
+ catch (e) {
185
+ it.state = before;
186
+ this.save();
187
+ return { error: e.message };
188
+ }
189
+ }
190
+ dismiss(id, permalink) {
191
+ const w = this.items.find(x => x.id === id);
192
+ const it = w === null || w === void 0 ? void 0 : w.items.find(i => i.permalink === permalink);
193
+ if (w && it) {
194
+ it.state = 'dismissed';
195
+ this.log(w, `You dismissed ${it.author}'s question`, undefined, { link: permalink });
196
+ }
197
+ }
198
+ redraft(id, permalink) {
199
+ const w = this.items.find(x => x.id === id);
200
+ const it = w === null || w === void 0 ? void 0 : w.items.find(i => i.permalink === permalink);
201
+ if (w && it) {
202
+ it.state = 'drafting';
203
+ it.error = undefined;
204
+ this.save();
205
+ this.draft(w, permalink);
206
+ }
207
+ }
208
+ }
209
+ SlackWatcherEngine.BACKLOG_MS = 24 * 60 * 60000;
210
+ exports.slackWatchers = (_a = global.__slackWatchers) !== null && _a !== void 0 ? _a : (global.__slackWatchers = new SlackWatcherEngine());
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.detectStatus = detectStatus;
4
+ const ANSI_RE = /\x1b\[[0-9;]*[a-zA-Z]|\x1b\][^\x07]*\x07|\x1b[()][A-Z0-9]/g;
5
+ // cursor-forward codes between words (\x1b[NC) — strip separately
6
+ const CURSOR_FWD_RE = /\x1b\[\d*C/g;
7
+ // Claude's spinner glyph, shown at the start of its working-status line
8
+ // (e.g. "✻ Vibing… (3s · thinking)") while actively processing. Deliberately
9
+ // excludes '·' (middle dot) — it's one real spinner frame, but it's also used
10
+ // as a plain decorative separator in the idle footer ("... · ← for agents"),
11
+ // which can land at column 0 if that line wraps and falsely read as thinking.
12
+ // The spinner cycles through several other frames, so missing this one frame
13
+ // doesn't hurt real detection.
14
+ const SPINNER_RE = /^[✢✳✶✻✽]\s/m;
15
+ // When a turn ends, newer Claude Code leaves a summary in the same spot with the
16
+ // same glyph: "✻ Brewed for 1s · done 14:49" / "✻ Cooked for 2m 3s". That's
17
+ // finished, not busy. Active lines read "✻ Vibing… (3s · thinking)".
18
+ const DONE_LINE_RE = /^[✢✳✶✻✽]\s+\S+ for \d[\dhms ]*(?:·|$)/;
19
+ // Copilot's TUI: the prompt glyph ❯ is on screen in EVERY state, so it can't
20
+ // signal "waiting". Its footer row says "◎ Working esc edit prompt" while
21
+ // busy and "← open sidebar · Interactive · …" when idle — that's the signal.
22
+ // Callers pass the bottom rows of the screen for copilot (not the cursor tail).
23
+ const COPILOT_WORKING_RE = /\bWorking\b[^\n]*esc edit prompt|◎ Working/;
24
+ function detectStatus(chunk, backend) {
25
+ const stripped = chunk.replace(ANSI_RE, '').replace(CURSOR_FWD_RE, '');
26
+ if (backend === 'copilot')
27
+ return COPILOT_WORKING_RE.test(stripped) ? 'thinking' : 'waiting';
28
+ // OpenCode ("esc interrupt"), Codex ("esc to interrupt"), Gemini ("esc to cancel"):
29
+ // the footer shows this only while a turn runs. Callers pass the screen bottom.
30
+ if (backend && backend !== 'claude')
31
+ return /\besc (?:to )?(?:interrupt|cancel)\b/i.test(stripped) ? 'thinking' : 'waiting';
32
+ // The ❯ prompt is rendered as permanent UI chrome below the status line
33
+ // regardless of state, so it can't distinguish thinking from waiting on its
34
+ // own — the spinner is the actual "busy" signal and must be checked first.
35
+ if (stripped.split('\n').some(l => SPINNER_RE.test(l) && !DONE_LINE_RE.test(l)))
36
+ return 'thinking';
37
+ // The footer shows "esc to interrupt" for as long as a turn is running
38
+ if (/esc to interrupt/i.test(stripped))
39
+ return 'thinking';
40
+ // Claude shows ❯ (U+276F) when waiting for input at the prompt.
41
+ // It appears mid-chunk (above the status bar), so we search anywhere.
42
+ if (stripped.includes('❯'))
43
+ return 'waiting';
44
+ // Fallback patterns for other prompts
45
+ if (/[>?]\s*$/.test(stripped.trimEnd()))
46
+ return 'waiting';
47
+ if (/\(y\/n\)\s*$/i.test(stripped.trimEnd()))
48
+ return 'waiting';
49
+ return 'thinking';
50
+ }