polyergon 0.0.0-stage → 0.1.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 (230) 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/limits/route.js +1 -0
  25. package/.next/server/app/api/limits/route.js.nft.json +1 -0
  26. package/.next/server/app/api/meetings/[id]/route.js +1 -0
  27. package/.next/server/app/api/meetings/[id]/route.js.nft.json +1 -0
  28. package/.next/server/app/api/meetings/[id]/slack/route.js +3 -0
  29. package/.next/server/app/api/meetings/[id]/slack/route.js.nft.json +1 -0
  30. package/.next/server/app/api/meetings/library/route.js +1 -0
  31. package/.next/server/app/api/meetings/library/route.js.nft.json +1 -0
  32. package/.next/server/app/api/meetings/route.js +1 -0
  33. package/.next/server/app/api/meetings/route.js.nft.json +1 -0
  34. package/.next/server/app/api/models/route.js +1 -0
  35. package/.next/server/app/api/models/route.js.nft.json +1 -0
  36. package/.next/server/app/api/notes/route.js +1 -0
  37. package/.next/server/app/api/notes/route.js.nft.json +1 -0
  38. package/.next/server/app/api/orgs/[id]/route.js +1 -0
  39. package/.next/server/app/api/orgs/[id]/route.js.nft.json +1 -0
  40. package/.next/server/app/api/orgs/route.js +1 -0
  41. package/.next/server/app/api/orgs/route.js.nft.json +1 -0
  42. package/.next/server/app/api/prs/inbox/route.js +1 -0
  43. package/.next/server/app/api/prs/inbox/route.js.nft.json +1 -0
  44. package/.next/server/app/api/prs/refresh/route.js +1 -0
  45. package/.next/server/app/api/prs/refresh/route.js.nft.json +1 -0
  46. package/.next/server/app/api/prs/route.js +1 -0
  47. package/.next/server/app/api/prs/route.js.nft.json +1 -0
  48. package/.next/server/app/api/session-names/route.js +1 -0
  49. package/.next/server/app/api/session-names/route.js.nft.json +1 -0
  50. package/.next/server/app/api/sessions/[id]/route.js +1 -0
  51. package/.next/server/app/api/sessions/[id]/route.js.nft.json +1 -0
  52. package/.next/server/app/api/sessions/route.js +1 -0
  53. package/.next/server/app/api/sessions/route.js.nft.json +1 -0
  54. package/.next/server/app/api/settings/auth/route.js +1 -0
  55. package/.next/server/app/api/settings/auth/route.js.nft.json +1 -0
  56. package/.next/server/app/api/settings/route.js +1 -0
  57. package/.next/server/app/api/settings/route.js.nft.json +1 -0
  58. package/.next/server/app/api/settings/transcription/route.js +1 -0
  59. package/.next/server/app/api/settings/transcription/route.js.nft.json +1 -0
  60. package/.next/server/app/api/skills/[name]/route.js +8 -0
  61. package/.next/server/app/api/skills/[name]/route.js.nft.json +1 -0
  62. package/.next/server/app/api/skills/marketplace/route.js +2 -0
  63. package/.next/server/app/api/skills/marketplace/route.js.nft.json +1 -0
  64. package/.next/server/app/api/skills/route.js +8 -0
  65. package/.next/server/app/api/skills/route.js.nft.json +1 -0
  66. package/.next/server/app/api/skills/view/route.js +8 -0
  67. package/.next/server/app/api/skills/view/route.js.nft.json +1 -0
  68. package/.next/server/app/api/slack/channels/route.js +1 -0
  69. package/.next/server/app/api/slack/channels/route.js.nft.json +1 -0
  70. package/.next/server/app/api/slack/configured/route.js +1 -0
  71. package/.next/server/app/api/slack/configured/route.js.nft.json +1 -0
  72. package/.next/server/app/api/slack/inbox/route.js +1 -0
  73. package/.next/server/app/api/slack/inbox/route.js.nft.json +1 -0
  74. package/.next/server/app/api/usage/route.js +1 -0
  75. package/.next/server/app/api/usage/route.js.nft.json +1 -0
  76. package/.next/server/app/demo/page.js +1 -0
  77. package/.next/server/app/demo/page.js.nft.json +1 -0
  78. package/.next/server/app/demo/page_client-reference-manifest.js +1 -0
  79. package/.next/server/app/demo.html +1 -0
  80. package/.next/server/app/demo.meta +6 -0
  81. package/.next/server/app/demo.rsc +7 -0
  82. package/.next/server/app/favicon.ico/route.js +12 -0
  83. package/.next/server/app/favicon.ico/route.js.nft.json +1 -0
  84. package/.next/server/app/favicon.ico.body +0 -0
  85. package/.next/server/app/favicon.ico.meta +1 -0
  86. package/.next/server/app/index.html +1 -0
  87. package/.next/server/app/index.meta +5 -0
  88. package/.next/server/app/index.rsc +7 -0
  89. package/.next/server/app/page.js +1 -0
  90. package/.next/server/app/page.js.nft.json +1 -0
  91. package/.next/server/app/page_client-reference-manifest.js +1 -0
  92. package/.next/server/app-paths-manifest.json +34 -0
  93. package/.next/server/chunks/348.js +1 -0
  94. package/.next/server/chunks/471.js +2 -0
  95. package/.next/server/chunks/590.js +7 -0
  96. package/.next/server/chunks/621.js +1 -0
  97. package/.next/server/chunks/682.js +6 -0
  98. package/.next/server/chunks/904.js +1 -0
  99. package/.next/server/chunks/948.js +2 -0
  100. package/.next/server/chunks/972.js +12 -0
  101. package/.next/server/chunks/font-manifest.json +1 -0
  102. package/.next/server/font-manifest.json +1 -0
  103. package/.next/server/functions-config-manifest.json +1 -0
  104. package/.next/server/interception-route-rewrite-manifest.js +1 -0
  105. package/.next/server/middleware-build-manifest.js +1 -0
  106. package/.next/server/middleware-manifest.json +6 -0
  107. package/.next/server/middleware-react-loadable-manifest.js +1 -0
  108. package/.next/server/next-font-manifest.js +1 -0
  109. package/.next/server/next-font-manifest.json +1 -0
  110. package/.next/server/pages/404.html +1 -0
  111. package/.next/server/pages/500.html +1 -0
  112. package/.next/server/pages/_app.js +1 -0
  113. package/.next/server/pages/_app.js.nft.json +1 -0
  114. package/.next/server/pages/_document.js +1 -0
  115. package/.next/server/pages/_document.js.nft.json +1 -0
  116. package/.next/server/pages/_error.js +1 -0
  117. package/.next/server/pages/_error.js.nft.json +1 -0
  118. package/.next/server/pages-manifest.json +1 -0
  119. package/.next/server/server-reference-manifest.js +1 -0
  120. package/.next/server/server-reference-manifest.json +1 -0
  121. package/.next/server/webpack-runtime.js +1 -0
  122. package/.next/static/chunks/117-0f4ac3c2c1871d4c.js +2 -0
  123. package/.next/static/chunks/171-f72ed164561ba218.js +1 -0
  124. package/.next/static/chunks/235.aef4cdc783360b73.js +1 -0
  125. package/.next/static/chunks/30d07d85.9045c666bb43d9e1.js +3 -0
  126. package/.next/static/chunks/app/_not-found/page-8ff6572bc7c9bc61.js +1 -0
  127. package/.next/static/chunks/app/demo/page-6711b34cd2af0e4a.js +1 -0
  128. package/.next/static/chunks/app/layout-d058836232e72324.js +1 -0
  129. package/.next/static/chunks/app/page-cebeba7d6d08548a.js +1 -0
  130. package/.next/static/chunks/fd9d1056-26bd8d656b496dba.js +1 -0
  131. package/.next/static/chunks/framework-f66176bb897dc684.js +1 -0
  132. package/.next/static/chunks/main-960df1c7509a5a8b.js +1 -0
  133. package/.next/static/chunks/main-app-4b855ea14675b961.js +1 -0
  134. package/.next/static/chunks/pages/_app-72b849fbd24ac258.js +1 -0
  135. package/.next/static/chunks/pages/_error-7ba65e1336b92748.js +1 -0
  136. package/.next/static/chunks/polyfills-42372ed130431b0a.js +1 -0
  137. package/.next/static/chunks/webpack-1f89b7cb1fca69c4.js +1 -0
  138. package/.next/static/css/a537d3e86c0f36d2.css +3 -0
  139. package/.next/static/css/ab3e4b0f5035257a.css +1 -0
  140. package/.next/static/q-HMeHYZY36qljBJhsyS6/_buildManifest.js +1 -0
  141. package/.next/static/q-HMeHYZY36qljBJhsyS6/_ssgManifest.js +1 -0
  142. package/.next/trace +22 -0
  143. package/.next/types/app/api/automations/existing/route.ts +343 -0
  144. package/.next/types/app/api/backends/route.ts +343 -0
  145. package/.next/types/app/api/limits/route.ts +343 -0
  146. package/.next/types/app/api/meetings/[id]/route.ts +343 -0
  147. package/.next/types/app/api/meetings/[id]/slack/route.ts +343 -0
  148. package/.next/types/app/api/meetings/library/route.ts +343 -0
  149. package/.next/types/app/api/meetings/route.ts +343 -0
  150. package/.next/types/app/api/models/route.ts +343 -0
  151. package/.next/types/app/api/notes/route.ts +343 -0
  152. package/.next/types/app/api/orgs/[id]/route.ts +343 -0
  153. package/.next/types/app/api/orgs/route.ts +343 -0
  154. package/.next/types/app/api/prs/inbox/route.ts +343 -0
  155. package/.next/types/app/api/prs/refresh/route.ts +343 -0
  156. package/.next/types/app/api/prs/route.ts +343 -0
  157. package/.next/types/app/api/session-names/route.ts +343 -0
  158. package/.next/types/app/api/sessions/[id]/route.ts +343 -0
  159. package/.next/types/app/api/sessions/route.ts +343 -0
  160. package/.next/types/app/api/settings/auth/route.ts +343 -0
  161. package/.next/types/app/api/settings/route.ts +343 -0
  162. package/.next/types/app/api/settings/transcription/route.ts +343 -0
  163. package/.next/types/app/api/skills/[name]/route.ts +343 -0
  164. package/.next/types/app/api/skills/marketplace/route.ts +343 -0
  165. package/.next/types/app/api/skills/route.ts +343 -0
  166. package/.next/types/app/api/skills/view/route.ts +343 -0
  167. package/.next/types/app/api/slack/channels/route.ts +343 -0
  168. package/.next/types/app/api/slack/configured/route.ts +343 -0
  169. package/.next/types/app/api/slack/inbox/route.ts +343 -0
  170. package/.next/types/app/api/usage/route.ts +343 -0
  171. package/.next/types/app/demo/page.ts +79 -0
  172. package/.next/types/app/layout.ts +79 -0
  173. package/.next/types/app/page.ts +79 -0
  174. package/.next/types/package.json +1 -0
  175. package/.server-dist/server.js +554 -0
  176. package/.server-dist/src/lib/activeOrg.js +11 -0
  177. package/.server-dist/src/lib/audioCapture.js +157 -0
  178. package/.server-dist/src/lib/backends.js +111 -0
  179. package/.server-dist/src/lib/claudeAuth.js +57 -0
  180. package/.server-dist/src/lib/configFile.js +23 -0
  181. package/.server-dist/src/lib/dataDir.js +7 -0
  182. package/.server-dist/src/lib/existingAutomations.js +132 -0
  183. package/.server-dist/src/lib/ghInbox.js +151 -0
  184. package/.server-dist/src/lib/ghPrStatus.js +86 -0
  185. package/.server-dist/src/lib/gitUtils.js +27 -0
  186. package/.server-dist/src/lib/keepAwake.js +32 -0
  187. package/.server-dist/src/lib/liveSessionStore.js +89 -0
  188. package/.server-dist/src/lib/marketplace.js +63 -0
  189. package/.server-dist/src/lib/meetingAssistant.js +138 -0
  190. package/.server-dist/src/lib/meetingConfig.js +81 -0
  191. package/.server-dist/src/lib/meetingContext.js +82 -0
  192. package/.server-dist/src/lib/meetingManager.js +246 -0
  193. package/.server-dist/src/lib/meetingStore.js +198 -0
  194. package/.server-dist/src/lib/modelCatalog.js +107 -0
  195. package/.server-dist/src/lib/notesStore.js +67 -0
  196. package/.server-dist/src/lib/orgFilter.js +19 -0
  197. package/.server-dist/src/lib/orgParam.js +15 -0
  198. package/.server-dist/src/lib/orgRegistry.js +93 -0
  199. package/.server-dist/src/lib/pipelineView.js +62 -0
  200. package/.server-dist/src/lib/pipelines.js +401 -0
  201. package/.server-dist/src/lib/planLimits.js +101 -0
  202. package/.server-dist/src/lib/prDetector.js +16 -0
  203. package/.server-dist/src/lib/prScanCache.js +144 -0
  204. package/.server-dist/src/lib/prSessionEntries.js +96 -0
  205. package/.server-dist/src/lib/prTypes.js +2 -0
  206. package/.server-dist/src/lib/ptyManager.js +428 -0
  207. package/.server-dist/src/lib/reminders.js +10 -0
  208. package/.server-dist/src/lib/requestGuard.js +29 -0
  209. package/.server-dist/src/lib/sessionNameStore.js +69 -0
  210. package/.server-dist/src/lib/sessionStore.js +215 -0
  211. package/.server-dist/src/lib/settingsStore.js +51 -0
  212. package/.server-dist/src/lib/skillsReader.js +200 -0
  213. package/.server-dist/src/lib/slackBridge.js +270 -0
  214. package/.server-dist/src/lib/slackInbox.js +96 -0
  215. package/.server-dist/src/lib/slackWatchers.js +210 -0
  216. package/.server-dist/src/lib/statusDetector.js +46 -0
  217. package/.server-dist/src/lib/transcriber.js +61 -0
  218. package/.server-dist/src/lib/usageStore.js +254 -0
  219. package/.server-dist/tsconfig.server.tsbuildinfo +1 -0
  220. package/LICENSE +21 -0
  221. package/README.md +99 -2
  222. package/bin/polyergon.js +34 -0
  223. package/next.config.mjs +4 -0
  224. package/package.json +81 -4
  225. package/public/.gitkeep +0 -0
  226. package/public/apple-touch-icon.png +0 -0
  227. package/public/icon-192.png +0 -0
  228. package/public/icon-512.png +0 -0
  229. package/public/icon.svg +1 -0
  230. package/public/manifest.webmanifest +15 -0
@@ -0,0 +1,157 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SILENCE_RMS_THRESHOLD = void 0;
4
+ exports.wavRms = wavRms;
5
+ exports.startCapture = startCapture;
6
+ exports.micTest = micTest;
7
+ const child_process_1 = require("child_process");
8
+ const fs_1 = require("fs");
9
+ const path_1 = require("path");
10
+ const os_1 = require("os");
11
+ const crypto_1 = require("crypto");
12
+ // 10s balances transcript latency against transcription accuracy — short
13
+ // chunks give the model too little context (hurts Hebrew especially)
14
+ const CHUNK_SECONDS = 10;
15
+ // RMS of 16-bit PCM samples in a WAV file, 0..1. Locates the 'data' chunk
16
+ // instead of assuming a 44-byte header (ffmpeg sometimes writes LIST chunks).
17
+ function wavRms(buf) {
18
+ let offset = 12; // past RIFF header
19
+ while (offset + 8 <= buf.length) {
20
+ const chunkId = buf.toString('ascii', offset, offset + 4);
21
+ const chunkSize = buf.readUInt32LE(offset + 4);
22
+ if (chunkId === 'data') {
23
+ const start = offset + 8;
24
+ const end = Math.min(start + chunkSize, buf.length);
25
+ const sampleCount = Math.floor((end - start) / 2);
26
+ if (sampleCount === 0)
27
+ return 0;
28
+ let sumSq = 0;
29
+ for (let i = 0; i < sampleCount; i++) {
30
+ const s = buf.readInt16LE(start + i * 2) / 32768;
31
+ sumSq += s * s;
32
+ }
33
+ return Math.sqrt(sumSq / sampleCount);
34
+ }
35
+ offset += 8 + chunkSize + (chunkSize % 2);
36
+ }
37
+ return 0;
38
+ }
39
+ // Below this a chunk is treated as silence and never sent for transcription
40
+ exports.SILENCE_RMS_THRESHOLD = 0.004;
41
+ // Two avfoundation inputs mixed by ffmpeg itself — avoids needing a macOS
42
+ // aggregate input device (whose programmatic creation requires a working
43
+ // Swift toolchain).
44
+ function ffmpegInputArgs(devices) {
45
+ return [
46
+ '-hide_banner', '-loglevel', 'error',
47
+ '-f', 'avfoundation', '-i', `:${devices.system}`,
48
+ '-f', 'avfoundation', '-i', `:${devices.mic}`,
49
+ '-filter_complex', 'amix=inputs=2:duration=longest:normalize=0',
50
+ '-ar', '16000', '-ac', '1',
51
+ ];
52
+ }
53
+ function ffmpegArgs(devices, outPattern) {
54
+ return [
55
+ ...ffmpegInputArgs(devices),
56
+ '-f', 'segment', '-segment_time', String(CHUNK_SECONDS),
57
+ '-reset_timestamps', '1',
58
+ outPattern,
59
+ ];
60
+ }
61
+ // Records the device into 5s WAV chunks under <meetingDir>/audio and reports
62
+ // each chunk once it's complete (i.e. once the next chunk has appeared, or on
63
+ // stop). Polling instead of fs.watch — simpler and reliable enough at 5s
64
+ // granularity.
65
+ function startCapture(meetingDir, devices, cb) {
66
+ var _a;
67
+ const audioDir = (0, path_1.join)(meetingDir, 'audio');
68
+ (0, fs_1.mkdirSync)(audioDir, { recursive: true });
69
+ // Each capture run (first start, auto-restart, resume) gets its own prefix so
70
+ // it never overwrites or re-reports an earlier run's chunks.
71
+ const prefix = `chunk-${Date.now()}-`;
72
+ const proc = (0, child_process_1.spawn)('ffmpeg', ffmpegArgs(devices, (0, path_1.join)(audioDir, `${prefix}%05d.wav`)));
73
+ let stderrTail = '';
74
+ (_a = proc.stderr) === null || _a === void 0 ? void 0 : _a.on('data', (d) => { stderrTail = (stderrTail + d.toString()).slice(-2000); });
75
+ const reported = new Set();
76
+ let stopped = false;
77
+ function scan(includeLatest) {
78
+ let files;
79
+ try {
80
+ files = (0, fs_1.readdirSync)(audioDir).filter(f => f.startsWith(prefix) && f.endsWith('.wav')).sort();
81
+ }
82
+ catch (_a) {
83
+ return;
84
+ }
85
+ // The highest-numbered chunk is still being written unless capture ended
86
+ const complete = includeLatest ? files : files.slice(0, -1);
87
+ for (const f of complete) {
88
+ if (reported.has(f))
89
+ continue;
90
+ reported.add(f);
91
+ cb.onChunk((0, path_1.join)(audioDir, f));
92
+ }
93
+ }
94
+ const poll = setInterval(() => scan(false), 1000);
95
+ let exited = false;
96
+ const exitPromise = new Promise(resolve => {
97
+ proc.on('exit', (code) => {
98
+ exited = true;
99
+ clearInterval(poll);
100
+ scan(true); // flush the final partial chunk
101
+ if (!stopped)
102
+ cb.onExit(code, stderrTail);
103
+ resolve();
104
+ });
105
+ });
106
+ return {
107
+ async stop() {
108
+ stopped = true;
109
+ if (!exited) {
110
+ proc.kill('SIGINT'); // graceful: lets ffmpeg finalize the open segment
111
+ const timeout = new Promise(r => setTimeout(() => { proc.kill('SIGKILL'); r(); }, 3000));
112
+ await Promise.race([exitPromise, timeout]);
113
+ await exitPromise;
114
+ }
115
+ },
116
+ };
117
+ }
118
+ // Records ~2s from the device and returns the level, for the pre-meeting mic
119
+ // check. Errors (device missing, no permission) come back as { error }.
120
+ async function micTest(devices) {
121
+ const outFile = (0, path_1.join)((0, os_1.tmpdir)(), `mic-test-${(0, crypto_1.randomUUID)().slice(0, 8)}.wav`);
122
+ return new Promise((resolve) => {
123
+ var _a;
124
+ const proc = (0, child_process_1.spawn)('ffmpeg', [
125
+ ...ffmpegInputArgs(devices),
126
+ '-t', '2', outFile,
127
+ ]);
128
+ let stderr = '';
129
+ (_a = proc.stderr) === null || _a === void 0 ? void 0 : _a.on('data', (d) => { stderr += d.toString(); });
130
+ const killer = setTimeout(() => proc.kill('SIGKILL'), 8000);
131
+ proc.on('exit', (code) => {
132
+ var _a;
133
+ clearTimeout(killer);
134
+ try {
135
+ if (code !== 0) {
136
+ resolve({ error: (_a = stderr.trim().split('\n').at(-1)) !== null && _a !== void 0 ? _a : `ffmpeg exited ${code}` });
137
+ return;
138
+ }
139
+ const buf = (0, fs_1.readFileSync)(outFile);
140
+ if ((0, fs_1.statSync)(outFile).size < 100) {
141
+ resolve({ error: 'No audio captured' });
142
+ return;
143
+ }
144
+ resolve({ level: wavRms(buf) });
145
+ }
146
+ catch (e) {
147
+ resolve({ error: e instanceof Error ? e.message : 'mic test failed' });
148
+ }
149
+ finally {
150
+ try {
151
+ (0, fs_1.rmSync)(outFile, { force: true });
152
+ }
153
+ catch (_b) { }
154
+ }
155
+ });
156
+ });
157
+ }
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_BACKEND = exports.BACKENDS = void 0;
4
+ exports.getBackend = getBackend;
5
+ exports.availableBackends = availableBackends;
6
+ const child_process_1 = require("child_process");
7
+ const path_1 = require("path");
8
+ const CLAUDE = {
9
+ id: 'claude',
10
+ label: 'Claude',
11
+ bin: 'claude',
12
+ spawnArgs: ({ model, resumeId, rcName, rc, skipPermissions }) => [
13
+ ...(skipPermissions ? ['--permission-mode', 'bypassPermissions'] : []),
14
+ '--model', model,
15
+ // Remote Control is opt-in per session (📱 on the card) so the phone list
16
+ // only shows sessions you actually want there, labeled with their name.
17
+ ...(rc ? ['--remote-control', ...(rcName ? [rcName] : [])] : []),
18
+ ...(resumeId ? ['--resume', resumeId] : []),
19
+ ],
20
+ env: (model) =>
21
+ // CLI 2.1.241 doesn't recognize the `claude-fable-5-1` id yet and refuses
22
+ // to launch it without this; the flag just skips the unknown-model context
23
+ // guard (Fable is 1M-context anyway). Remove once the CLI knows the id.
24
+ model.startsWith('claude-fable-5-1')
25
+ ? { CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT: '1' }
26
+ : {},
27
+ };
28
+ // GitHub Copilot CLI (standalone `copilot`, @github/copilot). Interactive by
29
+ // default (no -p). --allow-all is the full bypassPermissions equivalent
30
+ // (= --allow-all-tools --allow-all-paths --allow-all-urls) so it never prompts;
31
+ // --allow-all-tools alone still asks about file paths and URLs. --resume=<id>
32
+ // resumes a prior session. Copilot has its own remote-control/export prompts
33
+ // that would block an unattended PTY, so we disable them here (unrelated to
34
+ // Claude's Remote Control feature).
35
+ // Copilot records each session in ~/.copilot/session-store.db (sqlite). We find
36
+ // the newest session row for this cwd created at/after spawn time — the direct
37
+ // analog of Claude's per-project .jsonl scan. Uses the sqlite3 CLI to avoid a
38
+ // native dependency; returns null on any error (DB locked, no row yet, etc.).
39
+ function findCopilotSessionIdSince(cwd, sinceMs) {
40
+ const db = (0, path_1.join)(process.env.HOME, '.copilot', 'session-store.db');
41
+ try {
42
+ // Copilot resolves symlinks in cwd (e.g. /tmp -> /private/tmp); match both
43
+ // the raw and realpath'd forms so detection isn't fooled by that.
44
+ let real = cwd;
45
+ try {
46
+ real = (0, child_process_1.execFileSync)('/usr/bin/readlink', ['-f', cwd], { timeout: 2000 }).toString().trim() || cwd;
47
+ }
48
+ catch (_a) { }
49
+ const since = new Date(sinceMs - 1000).toISOString(); // 1s tolerance for lag
50
+ const sql = `SELECT id FROM sessions WHERE cwd IN ('${cwd.replace(/'/g, "''")}','${real.replace(/'/g, "''")}') AND created_at >= '${since}' ORDER BY created_at DESC LIMIT 1;`;
51
+ const out = (0, child_process_1.execFileSync)('sqlite3', [db, sql], { timeout: 3000 }).toString().trim();
52
+ return out || null;
53
+ }
54
+ catch (_b) {
55
+ return null;
56
+ }
57
+ }
58
+ const COPILOT = {
59
+ id: 'copilot',
60
+ label: 'Copilot',
61
+ bin: 'copilot',
62
+ detectSessionId: findCopilotSessionIdSince,
63
+ spawnArgs: ({ model, cwd, resumeId, skipPermissions }) => [
64
+ '--model', model,
65
+ ...(skipPermissions ? ['--allow-all'] : []),
66
+ // Trust the session's folder up front. --allow-all covers tools/paths/URLs
67
+ // but NOT folder trust, so an interactive session in a new dir would pop a
68
+ // "Confirm folder trust" prompt every time; --add-dir pre-trusts it.
69
+ '--add-dir', cwd,
70
+ '--no-remote',
71
+ '--no-remote-export',
72
+ // Copilot enables terminal mouse tracking by default, which captures drag
73
+ // events so xterm.js can't select text (no copy). Disable it so click-drag
74
+ // selection + copy work the same as in Claude sessions.
75
+ '--no-mouse',
76
+ ...(resumeId ? [`--resume=${resumeId}`] : []),
77
+ ],
78
+ env: () => ({}),
79
+ };
80
+ exports.BACKENDS = {
81
+ claude: CLAUDE,
82
+ copilot: COPILOT,
83
+ };
84
+ exports.DEFAULT_BACKEND = 'claude';
85
+ function getBackend(id) {
86
+ var _a;
87
+ return (_a = exports.BACKENDS[id]) !== null && _a !== void 0 ? _a : exports.BACKENDS[exports.DEFAULT_BACKEND];
88
+ }
89
+ // Which backends are actually runnable on this machine — the UI only offers
90
+ // these, so a missing binary can never produce a failed spawn.
91
+ const availabilityCache = new Map();
92
+ function isBinaryAvailable(bin) {
93
+ if (availabilityCache.has(bin))
94
+ return availabilityCache.get(bin);
95
+ let ok = false;
96
+ try {
97
+ // login shell so PATH matches where the user's CLIs live (e.g. ~/.local/bin)
98
+ (0, child_process_1.execSync)(`zsh -lc 'command -v ${bin}'`, { stdio: 'ignore' });
99
+ ok = true;
100
+ }
101
+ catch (_a) {
102
+ ok = false;
103
+ }
104
+ availabilityCache.set(bin, ok);
105
+ return ok;
106
+ }
107
+ function availableBackends() {
108
+ return Object.values(exports.BACKENDS)
109
+ .filter(b => isBinaryAvailable(b.bin))
110
+ .map(b => ({ id: b.id, label: b.label }));
111
+ }
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getClaudeAuthStatus = getClaudeAuthStatus;
4
+ exports.saveClaudeAuth = saveClaudeAuth;
5
+ exports.claudeAuthEnv = claudeAuthEnv;
6
+ exports.claudeLoginStatus = claudeLoginStatus;
7
+ const child_process_1 = require("child_process");
8
+ const configFile_1 = require("./configFile");
9
+ function getClaudeAuthStatus(file = configFile_1.CONFIG_FILE) {
10
+ const cfg = (0, configFile_1.readConfig)(file);
11
+ const key = typeof cfg.anthropicApiKey === 'string' ? cfg.anthropicApiKey : '';
12
+ return cfg.claudeAuth === 'apiKey' && key ? { mode: 'apiKey', keyHint: '…' + key.slice(-4) } : { mode: 'login', keyHint: key ? '…' + key.slice(-4) : null };
13
+ }
14
+ // Blank apiKey keeps the saved key. Switching to login keeps the key on disk
15
+ // so switching back doesn't need it again.
16
+ function saveClaudeAuth(input, file = configFile_1.CONFIG_FILE) {
17
+ const cfg = (0, configFile_1.readConfig)(file);
18
+ if (input.mode === 'login') {
19
+ cfg.claudeAuth = 'login';
20
+ }
21
+ else if (input.mode === 'apiKey') {
22
+ const key = (typeof input.apiKey === 'string' ? input.apiKey.trim() : '') || (typeof cfg.anthropicApiKey === 'string' ? cfg.anthropicApiKey : '');
23
+ if (!key)
24
+ throw new Error('API key is required');
25
+ if (!key.startsWith('sk-ant-'))
26
+ throw new Error('That does not look like an Anthropic API key (it should start with sk-ant-)');
27
+ Object.assign(cfg, { claudeAuth: 'apiKey', anthropicApiKey: key });
28
+ }
29
+ else {
30
+ throw new Error('Unknown mode');
31
+ }
32
+ (0, configFile_1.writeConfig)(cfg, file);
33
+ return getClaudeAuthStatus(file);
34
+ }
35
+ // Env for a Claude spawn. Login mode adds nothing (the CLI uses its own login).
36
+ function claudeAuthEnv(file = configFile_1.CONFIG_FILE) {
37
+ const cfg = (0, configFile_1.readConfig)(file);
38
+ return cfg.claudeAuth === 'apiKey' && typeof cfg.anthropicApiKey === 'string' && cfg.anthropicApiKey
39
+ ? { ANTHROPIC_API_KEY: cfg.anthropicApiKey }
40
+ : {};
41
+ }
42
+ // `claude auth status` for a config folder (null = ~/.claude). Unknown → null.
43
+ function claudeLoginStatus(configDir) {
44
+ const env = Object.assign(Object.assign({}, process.env), (configDir ? { CLAUDE_CONFIG_DIR: configDir } : {}));
45
+ return new Promise(resolve => {
46
+ (0, child_process_1.execFile)('claude', ['auth', 'status'], { env, timeout: 20000 }, (_err, stdout) => {
47
+ var _a, _b, _c;
48
+ try {
49
+ const j = JSON.parse(stdout);
50
+ resolve({ loggedIn: !!j.loggedIn, email: (_a = j.email) !== null && _a !== void 0 ? _a : null, orgName: (_b = j.orgName) !== null && _b !== void 0 ? _b : null, plan: (_c = j.subscriptionType) !== null && _c !== void 0 ? _c : null });
51
+ }
52
+ catch (_d) {
53
+ resolve(null);
54
+ }
55
+ });
56
+ });
57
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CONFIG_FILE = void 0;
4
+ exports.readConfig = readConfig;
5
+ exports.writeConfig = writeConfig;
6
+ const dataDir_1 = require("./dataDir");
7
+ const fs_1 = require("fs");
8
+ const path_1 = require("path");
9
+ // <data>/config.json holds secrets (API keys), so it is always written 0600.
10
+ exports.CONFIG_FILE = (0, path_1.join)(dataDir_1.DATA_DIR, 'config.json');
11
+ function readConfig(file = exports.CONFIG_FILE) {
12
+ try {
13
+ return JSON.parse((0, fs_1.readFileSync)(file, 'utf-8'));
14
+ }
15
+ catch (_a) {
16
+ return {};
17
+ }
18
+ }
19
+ function writeConfig(cfg, file = exports.CONFIG_FILE) {
20
+ (0, fs_1.mkdirSync)((0, path_1.join)(file, '..'), { recursive: true });
21
+ (0, fs_1.writeFileSync)(file, JSON.stringify(cfg, null, 2), { mode: 0o600 });
22
+ (0, fs_1.chmodSync)(file, 0o600); // mode above only applies when the file is created
23
+ }
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DATA_DIR = void 0;
4
+ const path_1 = require("path");
5
+ // Where every server-side store lives. POLYERGON_DATA_DIR lets a second
6
+ // instance (e.g. a dev copy on another port) run without touching prod data.
7
+ exports.DATA_DIR = process.env.POLYERGON_DATA_DIR || (0, path_1.join)(process.env.HOME, '.claude-session-manager');
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseLoopLog = parseLoopLog;
4
+ exports.listLoops = listLoops;
5
+ exports.listHooks = listHooks;
6
+ exports.runLoopNow = runLoopNow;
7
+ exports.loopLogTail = loopLogTail;
8
+ const fs_1 = require("fs");
9
+ const path_1 = require("path");
10
+ const child_process_1 = require("child_process");
11
+ const util_1 = require("util");
12
+ const orgRegistry_1 = require("./orgRegistry");
13
+ const execFileAsync = (0, util_1.promisify)(child_process_1.execFile);
14
+ const HOME = () => process.env.HOME;
15
+ // Splits a loop log into runs: "=== 2026-11-20 16:10:04 board (model, prompt)" + output lines
16
+ function parseLoopLog(text) {
17
+ const runs = [];
18
+ for (const line of text.split('\n')) {
19
+ const m = line.match(/^=== (\d{4}-\d\d-\d\d \d\d:\d\d:\d\d) \S+ \(([^,)]+)/);
20
+ if (m)
21
+ runs.push({ at: m[1], model: m[2], output: '' });
22
+ else if (runs.length && line.trim())
23
+ runs[runs.length - 1].output += (runs[runs.length - 1].output ? '\n' : '') + line;
24
+ }
25
+ return runs;
26
+ }
27
+ async function launchdStatus() {
28
+ const out = await execFileAsync('launchctl', ['list'], { timeout: 5000 }).then(r => r.stdout).catch(() => '');
29
+ const map = new Map();
30
+ for (const line of out.split('\n').slice(1)) {
31
+ const [pid, exit, label] = line.split('\t');
32
+ if (label)
33
+ map.set(label, { pid: pid === '-' ? null : Number(pid), exit: exit === '-' ? null : Number(exit) });
34
+ }
35
+ return map;
36
+ }
37
+ async function listLoops() {
38
+ var _a, _b, _c, _d, _e;
39
+ const dir = (0, path_1.join)(HOME(), 'Library', 'LaunchAgents');
40
+ let files = [];
41
+ try {
42
+ files = (0, fs_1.readdirSync)(dir).filter(f => f.endsWith('.plist'));
43
+ }
44
+ catch (_f) {
45
+ return [];
46
+ }
47
+ const status = await launchdStatus();
48
+ const loops = [];
49
+ for (const f of files) {
50
+ const path = (0, path_1.join)(dir, f);
51
+ let raw = '';
52
+ try {
53
+ raw = (0, fs_1.readFileSync)(path, 'utf-8');
54
+ }
55
+ catch (_g) {
56
+ continue;
57
+ }
58
+ if (!/claude/i.test(raw))
59
+ continue;
60
+ let j;
61
+ try {
62
+ j = JSON.parse((await execFileAsync('plutil', ['-convert', 'json', '-o', '-', path], { timeout: 5000 })).stdout);
63
+ }
64
+ catch (_h) {
65
+ continue;
66
+ }
67
+ const args = (_a = j.ProgramArguments) !== null && _a !== void 0 ? _a : [];
68
+ const label = (_b = j.Label) !== null && _b !== void 0 ? _b : f.replace(/\.plist$/, '');
69
+ // ~/.claude/loops/run.sh <name> → prompts/<name>.md and logs/<name>.log
70
+ const runSh = args.findIndex(a => a.endsWith('/loops/run.sh'));
71
+ const name = runSh >= 0 ? args[runSh + 1] : null;
72
+ const loopsDir = runSh >= 0 ? args[runSh].replace(/\/run\.sh$/, '') : null;
73
+ const logFile = loopsDir && name ? (0, path_1.join)(loopsDir, 'logs', `${name}.log`) : (_c = j.StandardOutPath) !== null && _c !== void 0 ? _c : null;
74
+ let lastRun = null, model = null;
75
+ if (logFile && (0, fs_1.existsSync)(logFile)) {
76
+ const runs = parseLoopLog((0, fs_1.readFileSync)(logFile, 'utf-8').slice(-20000));
77
+ const last = runs.at(-1);
78
+ if (last) {
79
+ lastRun = { at: last.at, output: last.output.slice(0, 600) };
80
+ model = last.model;
81
+ }
82
+ }
83
+ let prompt = null;
84
+ if (loopsDir && name) {
85
+ try {
86
+ prompt = (0, fs_1.readFileSync)((0, path_1.join)(loopsDir, 'prompts', `${name}.md`), 'utf-8').slice(0, 1500);
87
+ }
88
+ catch ( /* none */_j) { /* none */ }
89
+ }
90
+ const st = status.get(label);
91
+ loops.push({
92
+ label, command: args.join(' '), everySec: (_d = j.StartInterval) !== null && _d !== void 0 ? _d : null,
93
+ calendar: j.StartCalendarInterval ? JSON.stringify(j.StartCalendarInterval) : null,
94
+ running: !!(st === null || st === void 0 ? void 0 : st.pid), lastExit: (_e = st === null || st === void 0 ? void 0 : st.exit) !== null && _e !== void 0 ? _e : null, model, prompt, lastRun, logFile,
95
+ });
96
+ }
97
+ return loops.sort((a, b) => a.label.localeCompare(b.label));
98
+ }
99
+ function listHooks() {
100
+ var _a, _b, _c, _d;
101
+ const out = [];
102
+ for (const org of orgRegistry_1.orgRegistry.list()) {
103
+ try {
104
+ const s = JSON.parse((0, fs_1.readFileSync)((0, path_1.join)(org.configDir || (0, path_1.join)(HOME(), '.claude'), 'settings.json'), 'utf-8'));
105
+ for (const [event, groups] of Object.entries((_a = s.hooks) !== null && _a !== void 0 ? _a : {})) {
106
+ for (const g of groups)
107
+ for (const h of (_b = g.hooks) !== null && _b !== void 0 ? _b : [])
108
+ out.push({ org: org.name, event, matcher: (_c = g.matcher) !== null && _c !== void 0 ? _c : '', command: String((_d = h.command) !== null && _d !== void 0 ? _d : '').slice(0, 300) });
109
+ }
110
+ }
111
+ catch ( /* no settings */_e) { /* no settings */ }
112
+ }
113
+ return out;
114
+ }
115
+ async function runLoopNow(label) {
116
+ var _a, _b;
117
+ if (!(await listLoops()).some(l => l.label === label))
118
+ throw new Error('Unknown loop');
119
+ const uid = (_b = (_a = process.getuid) === null || _a === void 0 ? void 0 : _a.call(process)) !== null && _b !== void 0 ? _b : 501;
120
+ await execFileAsync('launchctl', ['kickstart', `gui/${uid}/${label}`], { timeout: 10000 });
121
+ }
122
+ function loopLogTail(label, loops, lines = 80) {
123
+ const l = loops.find(x => x.label === label);
124
+ if (!(l === null || l === void 0 ? void 0 : l.logFile))
125
+ return '';
126
+ try {
127
+ return (0, fs_1.readFileSync)(l.logFile, 'utf-8').split('\n').slice(-lines).join('\n');
128
+ }
129
+ catch (_a) {
130
+ return '';
131
+ }
132
+ }
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+ var _a;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.buildInbox = buildInbox;
5
+ exports.getInbox = getInbox;
6
+ const child_process_1 = require("child_process");
7
+ const util_1 = require("util");
8
+ const ghPrStatus_1 = require("./ghPrStatus");
9
+ const prSessionEntries_1 = require("./prSessionEntries");
10
+ const execFileAsync = (0, util_1.promisify)(child_process_1.execFile);
11
+ const CACHE_TTL_MS = 5 * 60 * 1000;
12
+ const MERGED_SECTION_DAYS = 7;
13
+ const STATS_WINDOW_WEEKS = 8;
14
+ const SEARCH_LIMIT = '50';
15
+ const MERGED_SEARCH_LIMIT = '200';
16
+ // gh must use the local keyring credentials (which can see private orgs), so
17
+ // any GITHUB_TOKEN/GH_TOKEN in the server's environment is stripped.
18
+ function ghEnv() {
19
+ const env = Object.assign({}, process.env);
20
+ delete env.GITHUB_TOKEN;
21
+ delete env.GH_TOKEN;
22
+ return env;
23
+ }
24
+ async function ghSearchPrs(args, limit = SEARCH_LIMIT) {
25
+ const { stdout } = await execFileAsync('gh', [
26
+ 'search', 'prs', ...args,
27
+ '--json', 'url,title,repository,updatedAt,createdAt,closedAt,isDraft',
28
+ '--limit', limit,
29
+ ], { timeout: 30000, env: ghEnv(), maxBuffer: 10 * 1024 * 1024 });
30
+ return JSON.parse(stdout);
31
+ }
32
+ function parseMs(iso) {
33
+ const t = iso ? Date.parse(iso) : NaN;
34
+ return Number.isNaN(t) ? 0 : t;
35
+ }
36
+ function toInboxPr(item, sessionByUrl) {
37
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
38
+ const session = sessionByUrl.get(item.url);
39
+ // gh reports Go's zero time ("0001-01-01T00:00:00Z") for open PRs' closedAt
40
+ // — it parses to a large negative number, so only positive times count
41
+ const closedAt = parseMs(item.closedAt);
42
+ return {
43
+ url: item.url,
44
+ title: item.title,
45
+ repo: (_d = (_b = (_a = item.repository) === null || _a === void 0 ? void 0 : _a.nameWithOwner) !== null && _b !== void 0 ? _b : (_c = item.url.match(/github\.com\/([\w.-]+\/[\w.-]+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : '',
46
+ updatedAt: parseMs(item.updatedAt),
47
+ createdAt: parseMs(item.createdAt),
48
+ closedAt: closedAt > 0 ? closedAt : null,
49
+ isDraft: (_e = item.isDraft) !== null && _e !== void 0 ? _e : false,
50
+ status: (_f = ghPrStatus_1.prStatusCache.get(item.url)) !== null && _f !== void 0 ? _f : null,
51
+ liveId: (_g = session === null || session === void 0 ? void 0 : session.liveId) !== null && _g !== void 0 ? _g : null,
52
+ sessionId: (_h = session === null || session === void 0 ? void 0 : session.sessionId) !== null && _h !== void 0 ? _h : null,
53
+ cwd: (_j = session === null || session === void 0 ? void 0 : session.cwd) !== null && _j !== void 0 ? _j : null,
54
+ };
55
+ }
56
+ // Monday 00:00 local time of the week containing `t`
57
+ function weekStartOf(t) {
58
+ const d = new Date(t);
59
+ d.setHours(0, 0, 0, 0);
60
+ d.setDate(d.getDate() - ((d.getDay() + 6) % 7));
61
+ return d.getTime();
62
+ }
63
+ // Your PR is back in your court when a reviewer asked for changes or CI is red
64
+ function isReturned(status) {
65
+ return !!status && status.state === 'OPEN' &&
66
+ (status.reviewDecision === 'CHANGES_REQUESTED' || status.checks === 'failing');
67
+ }
68
+ async function buildInbox() {
69
+ var _a, _b, _c, _d;
70
+ // Merged query spans the stats window (8 weeks); the "Recently merged"
71
+ // section shows only the last 7 days of it
72
+ const mergedSince = new Date(weekStartOf(Date.now()) - (STATS_WINDOW_WEEKS - 1) * 7 * 86400000).toISOString().slice(0, 10);
73
+ const [authoredRes, reviewRes, mergedRes, sessionEntries] = await Promise.allSettled([
74
+ ghSearchPrs(['--author=@me', '--state=open']),
75
+ ghSearchPrs(['--review-requested=@me', '--state=open']),
76
+ ghSearchPrs(['--author=@me', '--merged', `--merged-at=>=${mergedSince}`], MERGED_SEARCH_LIMIT),
77
+ (0, prSessionEntries_1.buildPrSessionEntries)(),
78
+ ]).then(results => results.map(r => r.status === 'fulfilled' ? r.value : null));
79
+ const authored = (_a = authoredRes) !== null && _a !== void 0 ? _a : [];
80
+ const reviewRequested = (_b = reviewRes) !== null && _b !== void 0 ? _b : [];
81
+ const merged = (_c = mergedRes) !== null && _c !== void 0 ? _c : [];
82
+ const sessions = (_d = sessionEntries) !== null && _d !== void 0 ? _d : [];
83
+ const error = authoredRes === null && reviewRes === null
84
+ ? 'gh search failed — check `gh auth status` on the server machine'
85
+ : null;
86
+ const sessionByUrl = new Map(sessions.map(e => [e.prUrl, e]));
87
+ // Fresh review/checks detail for every open PR — this is what decides
88
+ // returned-vs-waiting, so it can't rely on a stale cache
89
+ const openUrls = [...authored, ...reviewRequested].map(i => i.url);
90
+ await (0, ghPrStatus_1.fetchAllPrStatuses)(openUrls);
91
+ const needsReview = [];
92
+ const returned = [];
93
+ const waiting = [];
94
+ const seen = new Set();
95
+ for (const item of reviewRequested) {
96
+ seen.add(item.url);
97
+ needsReview.push(toInboxPr(item, sessionByUrl));
98
+ }
99
+ for (const item of authored) {
100
+ if (seen.has(item.url))
101
+ continue;
102
+ seen.add(item.url);
103
+ const pr = toInboxPr(item, sessionByUrl);
104
+ if (isReturned(pr.status))
105
+ returned.push(pr);
106
+ else
107
+ waiting.push(pr);
108
+ }
109
+ const mergedAll = merged.filter(i => !seen.has(i.url)).map(i => toInboxPr(i, sessionByUrl));
110
+ const mergedRecent = mergedAll.filter(p => { var _a; return ((_a = p.closedAt) !== null && _a !== void 0 ? _a : 0) >= Date.now() - MERGED_SECTION_DAYS * 86400000; });
111
+ // Merged-per-week buckets across the full stats window (zero-filled)
112
+ const thisWeek = weekStartOf(Date.now());
113
+ const mergedByWeek = Array.from({ length: STATS_WINDOW_WEEKS }, (_, i) => ({
114
+ weekStart: thisWeek - (STATS_WINDOW_WEEKS - 1 - i) * 7 * 86400000,
115
+ count: 0,
116
+ }));
117
+ for (const p of mergedAll) {
118
+ if (!p.closedAt)
119
+ continue;
120
+ const bucket = mergedByWeek.find(b => weekStartOf(p.closedAt) === b.weekStart);
121
+ if (bucket)
122
+ bucket.count++;
123
+ }
124
+ const byUpdated = (a, b) => b.updatedAt - a.updatedAt;
125
+ needsReview.sort(byUpdated);
126
+ returned.sort(byUpdated);
127
+ waiting.sort(byUpdated);
128
+ mergedRecent.sort(byUpdated);
129
+ // Session PRs outside the workload, still relevant (open or status unknown)
130
+ const inboxUrls = new Set(Array.from(seen).concat(mergedRecent.map(p => p.url)));
131
+ const fromSessions = sessions.filter(e => !inboxUrls.has(e.prUrl) && (!e.status || e.status.state === 'OPEN'));
132
+ return {
133
+ sections: { needsReview, returned, waiting, mergedRecent },
134
+ fromSessions,
135
+ mergedByWeek,
136
+ mergedWindow: mergedAll.sort((a, b) => { var _a, _b; return ((_a = b.closedAt) !== null && _a !== void 0 ? _a : 0) - ((_b = a.closedAt) !== null && _b !== void 0 ? _b : 0); }),
137
+ fetchedAt: Date.now(),
138
+ error,
139
+ };
140
+ }
141
+ const st = (_a = global.__ghInbox) !== null && _a !== void 0 ? _a : (global.__ghInbox = { cached: null, inFlight: null });
142
+ async function getInbox(force = false) {
143
+ if (!force && st.cached && Date.now() - st.cached.fetchedAt < CACHE_TTL_MS)
144
+ return st.cached;
145
+ if (!st.inFlight) {
146
+ st.inFlight = buildInbox()
147
+ .then(inbox => { st.cached = inbox; return inbox; })
148
+ .finally(() => { st.inFlight = null; });
149
+ }
150
+ return st.inFlight;
151
+ }