claude-code-session-manager 0.137.0 → 0.139.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 (101) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +339 -82
  3. package/dist/assets/{AppSettings-l7NTc0yu.js → AppSettings-CUfWY9vN.js} +2 -2
  4. package/dist/assets/History-DDnqaLyw.js +2 -0
  5. package/dist/assets/HomeClaudeConfig-CGD2Onjv.js +3 -0
  6. package/dist/assets/{Panel-BuInRmA0.js → Panel-Csyd9HbD.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-C-jlYpC_.js +26 -0
  8. package/dist/assets/{Scheduler-B7sn2mUw.js → Scheduler-NLs08fx7.js} +9 -9
  9. package/dist/assets/{SkillReferenceGraph-DwV0Ueyc.js → SkillReferenceGraph-DcscPXAG.js} +1 -1
  10. package/dist/assets/Skills-BpGRKOcY.js +67 -0
  11. package/dist/assets/{TiptapBody-Bl8hDhhS.js → TiptapBody-DSU3769X.js} +60 -54
  12. package/dist/assets/ViewTabs-C0PRZx4_.js +1 -0
  13. package/dist/assets/{VoiceButton-DJx-jY4r.js → VoiceButton-D2rMurNg.js} +1 -1
  14. package/dist/assets/{historyTotals-Cgjm5q24.js → historyTotals-TcIQs2sh.js} +1 -1
  15. package/dist/assets/{index-62tyjEQB.css → index-BCySPdtU.css} +1 -1
  16. package/dist/assets/index-C-d0DCre.js +3124 -0
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +471 -452
  20. package/package.json +13 -5
  21. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
  23. package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
  24. package/plugins/session-manager-dev/skills/develop/SKILL.md +12 -5
  25. package/scripts/README.md +1 -0
  26. package/scripts/scheduler-mcp-server.cjs +161 -18
  27. package/src/main/build-info.json +4 -4
  28. package/src/main/chatRunner.cjs +53 -2
  29. package/src/main/exchanges.cjs +70 -5
  30. package/src/main/historyAggregator.cjs +84 -58
  31. package/src/main/historyDashboard.cjs +18 -13
  32. package/src/main/index.cjs +35 -9
  33. package/src/main/ipcSchemas.cjs +133 -5
  34. package/src/main/lib/claude/effectiveModelInfo.cjs +2 -2
  35. package/src/main/lib/claude/modelPricing.cjs +148 -0
  36. package/src/main/lib/demo-video-kit/checks.cjs +16 -0
  37. package/src/main/lib/epic/epicAdminRoutes.cjs +101 -0
  38. package/src/main/lib/epic/epicAttachments.cjs +143 -0
  39. package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
  40. package/src/main/lib/epic/epicMint.cjs +4 -0
  41. package/src/main/lib/epic/epicOutsideRead.cjs +306 -0
  42. package/src/main/lib/epic/epicOutsideState.cjs +233 -0
  43. package/src/main/lib/epic/epicSettle.cjs +1 -1
  44. package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
  45. package/src/main/lib/epic/externalRef.cjs +37 -0
  46. package/src/main/lib/epic/externalRefIndex.cjs +136 -0
  47. package/src/main/lib/epic/restorableSessions.cjs +151 -17
  48. package/src/main/lib/epic/transcriptUsage.cjs +197 -0
  49. package/src/main/lib/externalContract.cjs +111 -0
  50. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +121 -4
  51. package/src/main/lib/feedback-remote/crossProjectReply.cjs +83 -1
  52. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
  53. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
  54. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
  55. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
  56. package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
  57. package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
  58. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +287 -1
  59. package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
  60. package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
  61. package/src/main/lib/feedback-remote/needsYouStore.cjs +281 -0
  62. package/src/main/lib/feedback-remote/remoteFrameAssembler.cjs +113 -0
  63. package/src/main/lib/historyRollup.cjs +32 -5
  64. package/src/main/lib/mcpToolCatalog.cjs +111 -14
  65. package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
  66. package/src/main/lib/persona-macro/macroLibrary.cjs +7 -0
  67. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  68. package/src/main/lib/process/bootStdioGuard.cjs +32 -0
  69. package/src/main/lib/process/stdioGuard.cjs +115 -0
  70. package/src/main/lib/promptSessionSchema.cjs +4 -0
  71. package/src/main/lib/remoteTranscriptTail.cjs +32 -1
  72. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  73. package/src/main/lib/telemetry/auditEvents.cjs +176 -0
  74. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
  75. package/src/main/loopEfficiencyHandlers.cjs +1 -1
  76. package/src/main/scheduler.cjs +29 -0
  77. package/src/main/templates/PRD_AUTHORING.md +1 -0
  78. package/src/main/transcripts.cjs +62 -7
  79. package/src/main/webRemote.cjs +122 -18
  80. package/src/preload/api.d.ts +98 -9
  81. package/src/preload/apiSurface.cjs +7 -0
  82. package/src/preload/apiSurface.json +415 -83
  83. package/src/preload/index.cjs +17 -3
  84. package/src/seed/agents/demo-video-builder.md +10 -7
  85. package/dist/assets/AgentLibrary-DV0DTZDC.js +0 -2
  86. package/dist/assets/Button-Cmfkgjfa.js +0 -1
  87. package/dist/assets/DocumentEditorPane-MTljV-Uw.js +0 -1
  88. package/dist/assets/Extensions-Cc1Q_8id.js +0 -2
  89. package/dist/assets/History-CFo-1DHo.js +0 -2
  90. package/dist/assets/Library-C_ibFiOx.js +0 -32
  91. package/dist/assets/ListDetail-ByULG209.js +0 -1
  92. package/dist/assets/ProjectClaudeConfig-yqqVtHY7.js +0 -25
  93. package/dist/assets/ProvenanceBadge-CJvnQReI.js +0 -1
  94. package/dist/assets/Settings-DRRSJksU.js +0 -2
  95. package/dist/assets/Skills-DVYHA9gV.js +0 -29
  96. package/dist/assets/SourceChip-DfJ5_5rV.js +0 -1
  97. package/dist/assets/SystemPrompt-f11wGllK.js +0 -1
  98. package/dist/assets/Toggle-DaxeFDFp.js +0 -1
  99. package/dist/assets/ViewTabs-DRtgFKRw.js +0 -1
  100. package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
  101. package/dist/assets/index-iQ6pdyuS.js +0 -3116
@@ -15,6 +15,7 @@ const fsp = require('node:fs/promises');
15
15
  const atomicFs = require('../util/atomicFs.cjs');
16
16
  const schedulerPaths = require('../scheduler/schedulerPaths.cjs');
17
17
  const { resolveFeedbackBase, fromWireType, FEEDBACK_SLUG } = require('./customerFeedbackClient.cjs');
18
+ const { ATTACHMENT_MIMES, sniffImageMime } = require('../epic/epicAttachments.cjs');
18
19
 
19
20
  const STATUSES = /** @type {const} */ (['open', 'in_progress', 'resolved', 'wontfix']);
20
21
  const MAX_NOTE = 500;
@@ -26,13 +27,20 @@ const SCHEMA_VERSION = 1;
26
27
  const NO_TOKEN = 'Feedback owner token not configured';
27
28
  const NO_STATUS_SUPPORT = 'Host does not support feedback status yet (or unknown id)';
28
29
  const HIDDEN = new Set(['archived', 'deleted']);
30
+ const MAX_ITEM_IMAGES = 5;
31
+ const MAX_IMAGE_FETCHES = 20;
32
+ const MAX_DATA_URL_CHARS = 2000000;
33
+ const SAFE_ID_RE = /^[A-Za-z0-9_-]{1,100}$/;
34
+ const DATA_URL_RE = /^data:image\/(png|jpeg|webp|gif);base64,/;
35
+ const BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
29
36
 
30
37
  /**
38
+ * @typedef {{ mime: string, bytes: number, path: string|null }} InboxImage
31
39
  * @typedef {{ id: string, receivedAt: string|number|null, tag: string, title: string, body: string,
32
40
  * clientVersion: string|null, clientPlatform: string|null, moderation: string|null, status: string,
33
- * statusNote: string|null, statusAt: string|number|null, epicId: string|null }} InboxItem
41
+ * statusNote: string|null, statusAt: string|number|null, epicId: string|null, images?: InboxImage[] }} InboxItem
34
42
  * @typedef {{ items: InboxItem[], nextSince: string|null, nextModeratedSince: string|null }} Store
35
- * @typedef {{ fetchImpl?: typeof fetch, storeFile?: string, ownerFile?: string,
43
+ * @typedef {{ fetchImpl?: typeof fetch, storeFile?: string, ownerFile?: string, imagesDir?: string,
36
44
  * env?: Record<string, string|undefined>, now?: () => number }} Deps
37
45
  */
38
46
 
@@ -43,6 +51,7 @@ function ctx(deps) {
43
51
  fetchImpl: d.fetchImpl || globalThis.fetch,
44
52
  storeFile: d.storeFile || path.join(schedulerPaths.schedulerHome(), 'customer-feedback-inbox.json'),
45
53
  ownerFile: d.ownerFile || path.join(schedulerPaths.schedulerHome(), 'customer-feedback-owner.json'),
54
+ imagesDir: d.imagesDir || path.join(schedulerPaths.schedulerHome(), 'customer-feedback-images'),
46
55
  env: d.env || process.env,
47
56
  now: d.now || Date.now,
48
57
  };
@@ -153,12 +162,186 @@ function toItem(w, prev) {
153
162
  statusNote: st && typeof st.note === 'string' ? st.note : null,
154
163
  statusAt: st ? (st.at ?? null) : null,
155
164
  epicId: prev && prev.epicId ? prev.epicId : null,
165
+ images: toImages(w.images, prev),
156
166
  };
157
167
  }
158
168
 
169
+ /** @param {unknown} wireImages @param {InboxItem|undefined} prev @returns {InboxImage[]} */
170
+ function toImages(wireImages, prev) {
171
+ if (!Array.isArray(wireImages)) return [];
172
+ const prevImages = prev && Array.isArray(prev.images) ? prev.images : [];
173
+ return wireImages.slice(0, MAX_ITEM_IMAGES).map((/** @type {any} */ im, i) => {
174
+ const p = prevImages[i];
175
+ return {
176
+ mime: im && typeof im.mime === 'string' ? im.mime : '',
177
+ bytes: im && typeof im.bytes === 'number' && Number.isFinite(im.bytes) ? im.bytes : 0,
178
+ path: p && typeof p.path === 'string' && p.path ? p.path : null,
179
+ };
180
+ });
181
+ }
182
+
183
+ /** @param {string} file */
184
+ async function fileExists(file) {
185
+ try { return (await fsp.stat(file)).isFile(); } catch { return false; }
186
+ }
187
+
188
+ /** @param {InboxItem} item @returns {Promise<boolean>} true when any image lacks a cached file */
189
+ async function needsImages(item) {
190
+ const images = Array.isArray(item.images) ? item.images : [];
191
+ for (const im of images) {
192
+ if (!im.path || !(await fileExists(im.path))) return true;
193
+ }
194
+ return false;
195
+ }
196
+
197
+ /**
198
+ * Validate one wire image entry; returns decoded bytes + mime, or null.
199
+ * @param {any} entry @param {string} declaredMime
200
+ * @returns {{ buf: Buffer, mime: string }|null}
201
+ */
202
+ function decodeImage(entry, declaredMime) {
203
+ const dataUrl = entry && typeof entry.dataUrl === 'string' ? entry.dataUrl : null;
204
+ if (!dataUrl || dataUrl.length > MAX_DATA_URL_CHARS) return null;
205
+ const m = DATA_URL_RE.exec(dataUrl);
206
+ if (!m) return null;
207
+ const mime = `image/${m[1]}`;
208
+ if (declaredMime && declaredMime !== mime) return null;
209
+ if (entry.mime !== undefined && entry.mime !== mime) return null;
210
+ const payload = dataUrl.slice(m[0].length);
211
+ if (!payload || payload.length % 4 !== 0 || !BASE64_RE.test(payload)) return null;
212
+ const buf = Buffer.from(payload, 'base64');
213
+ if (sniffImageMime(buf) !== mime) return null;
214
+ return { buf, mime };
215
+ }
216
+
217
+ /** @param {string|number|null} receivedAt @returns {string|null} */
218
+ function sinceBefore(receivedAt) {
219
+ const t = typeof receivedAt === 'number' ? receivedAt : (typeof receivedAt === 'string' ? Date.parse(receivedAt) : NaN);
220
+ if (!Number.isFinite(t)) return null;
221
+ return new Date(t - 1000).toISOString();
222
+ }
223
+
224
+ /**
225
+ * One image GET (full dataUrls). Returns the wire items array, or null on non-200 / bad JSON.
226
+ * Network errors throw to the caller.
227
+ * @param {ReturnType<typeof ctx>} c @param {string} base @param {string} token @param {string} since @param {number} limit
228
+ * @returns {Promise<any[]|null>}
229
+ */
230
+ async function fetchImagePage(c, base, token, since, limit) {
231
+ const qs = new URLSearchParams({ since, limit: String(limit) });
232
+ const res = await c.fetchImpl(`${base}?${qs.toString()}`, {
233
+ headers: { authorization: `Bearer ${token}` },
234
+ signal: AbortSignal.timeout(TIMEOUT_MS),
235
+ });
236
+ if (res.status !== 200) return null;
237
+ /** @type {any} */
238
+ const j = await res.json().catch(() => null);
239
+ return j && Array.isArray(j.items) ? j.items : null;
240
+ }
241
+
242
+ /**
243
+ * Write one item's missing images from its wire entry `w`.
244
+ * @param {ReturnType<typeof ctx>} c @param {InboxItem} item @param {any} w
245
+ * @returns {Promise<{ paths: (string|null)[], count: number }>}
246
+ */
247
+ async function writeItemImages(c, item, w) {
248
+ let count = 0;
249
+ const images = item.images || [];
250
+ /** @type {(string|null)[]} */
251
+ const paths = images.map((im) => im.path);
252
+ for (let i = 0; i < images.length; i++) {
253
+ if (paths[i] && (await fileExists(/** @type {string} */ (paths[i])))) continue;
254
+ paths[i] = null;
255
+ const dec = decodeImage(w.images[i], images[i].mime);
256
+ if (!dec) continue;
257
+ const ext = /** @type {Record<string, string>} */ (ATTACHMENT_MIMES)[dec.mime];
258
+ if (!ext) continue;
259
+ const file = path.join(c.imagesDir, item.id, `${i + 1}${ext}`);
260
+ try {
261
+ await atomicFs.writeTextAtomic(file, dec.buf, { mode: 0o600 });
262
+ paths[i] = file;
263
+ count++;
264
+ } catch { /* disk error: leave null, retry next pull */ }
265
+ }
266
+ return { paths, count };
267
+ }
268
+
269
+ /**
270
+ * Download + cache images for up to MAX_IMAGE_FETCHES items. Never throws, never logs bytes.
271
+ * Asks for `limit=1` first (the host returns full images for every item after `since`); retries
272
+ * with `limit=MAX_IMAGE_FETCHES` only when the item is missing (several items in the same second).
273
+ * Any uncached item found in any response is cached from it and gets no GET of its own.
274
+ * @param {ReturnType<typeof ctx>} c @param {string} base @param {string} token @param {string[]} fetchedIds
275
+ * @returns {Promise<number>} images written
276
+ */
277
+ async function cacheImages(c, base, token, fetchedIds) {
278
+ const store = await readStore(c.storeFile);
279
+ const fetchedSet = new Set(fetchedIds);
280
+ const ordered = [
281
+ ...store.items.filter((i) => fetchedSet.has(i.id)),
282
+ ...sortItems(store.items).filter((i) => !fetchedSet.has(i.id)),
283
+ ];
284
+ /** @type {InboxItem[]} */
285
+ const todo = [];
286
+ for (const item of ordered) {
287
+ if (todo.length >= MAX_IMAGE_FETCHES) break;
288
+ if (typeof item.id !== 'string' || !SAFE_ID_RE.test(item.id)) continue;
289
+ if (!Array.isArray(item.images) || !item.images.length) continue;
290
+ if (await needsImages(item)) todo.push(item);
291
+ }
292
+ const byId = new Map(todo.map((i) => [i.id, i]));
293
+ /** @type {Set<string>} */
294
+ const done = new Set();
295
+ /** @type {Map<string, (string|null)[]>} */
296
+ const written = new Map();
297
+ let count = 0;
298
+ const has = (/** @type {any[]|null} */ page, /** @type {string} */ id) => !!page && page.some((x) => x && x.id === id);
299
+ for (const item of todo) {
300
+ if (done.has(item.id)) continue;
301
+ try {
302
+ const since = sinceBefore(item.receivedAt);
303
+ if (!since) continue;
304
+ let page = await fetchImagePage(c, base, token, since, 1);
305
+ if (!has(page, item.id)) page = await fetchImagePage(c, base, token, since, MAX_IMAGE_FETCHES);
306
+ if (!page) continue;
307
+ for (const w of page) {
308
+ if (!w || typeof w.id !== 'string' || done.has(w.id) || !Array.isArray(w.images)) continue;
309
+ const target = byId.get(w.id);
310
+ if (!target) continue;
311
+ const r = await writeItemImages(c, target, w);
312
+ written.set(w.id, r.paths);
313
+ count += r.count;
314
+ done.add(w.id);
315
+ }
316
+ } catch { /* network / timeout: leave paths null, retry next pull (error intentionally dropped; no bytes, no token) */ }
317
+ }
318
+ if (written.size) {
319
+ await mutateStore(c.storeFile, (s) => {
320
+ for (const it of s.items) {
321
+ const paths = written.get(it.id);
322
+ if (!paths || !Array.isArray(it.images)) continue;
323
+ it.images = it.images.map((im, i) => ({ ...im, path: paths[i] !== undefined ? paths[i] : im.path }));
324
+ }
325
+ });
326
+ }
327
+ return count;
328
+ }
329
+
330
+ /** Remove cache dirs whose id is no longer in the mirror. @param {ReturnType<typeof ctx>} c */
331
+ async function pruneImages(c) {
332
+ /** @type {import('node:fs').Dirent[]} */
333
+ let entries;
334
+ try { entries = await fsp.readdir(c.imagesDir, { withFileTypes: true }); } catch { return; }
335
+ const ids = new Set((await readStore(c.storeFile)).items.map((i) => i.id));
336
+ for (const e of entries) {
337
+ if (ids.has(e.name)) continue;
338
+ try { await fsp.rm(path.join(c.imagesDir, e.name), { recursive: true, force: true }); } catch { /* best effort */ }
339
+ }
340
+ }
341
+
159
342
  /**
160
343
  * @param {Deps} [deps]
161
- * @returns {Promise<{ ok: true, fetched: number, pages: number } | { ok: false, error: string }>}
344
+ * @returns {Promise<{ ok: true, fetched: number, pages: number, imagesCached: number } | { ok: false, error: string }>}
162
345
  */
163
346
  async function pull(deps) {
164
347
  const cfg = loadOwnerConfig(deps);
@@ -204,7 +387,37 @@ async function pull(deps) {
204
387
  store.nextSince = finalSince;
205
388
  store.nextModeratedSince = finalModerated;
206
389
  });
207
- return { ok: true, fetched: fetched.length, pages };
390
+ let imagesCached = 0;
391
+ try {
392
+ imagesCached = await cacheImages(c, base, cfg.token, fetched.map((w) => w.id));
393
+ } catch { /* image caching never fails the pull */ }
394
+ await pruneImages(c);
395
+ return { ok: true, fetched: fetched.length, pages, imagesCached };
396
+ }
397
+
398
+ /**
399
+ * Read one cached image back as a data URL (owner only).
400
+ * @param {string} id @param {number} index 0-based @param {Deps} [deps]
401
+ * @returns {Promise<{ ok: true, dataUrl: string } | { ok: false, error: string }>}
402
+ */
403
+ async function readCachedImage(id, index, deps) {
404
+ if (!loadOwnerConfig(deps)) return { ok: false, error: NO_TOKEN };
405
+ if (typeof id !== 'string' || !SAFE_ID_RE.test(id)) return { ok: false, error: 'Invalid feedback id.' };
406
+ if (typeof index !== 'number' || !Number.isInteger(index) || index < 0 || index >= MAX_ITEM_IMAGES) {
407
+ return { ok: false, error: 'Invalid image index.' };
408
+ }
409
+ const c = ctx(deps);
410
+ const item = (await readStore(c.storeFile)).items.find((i) => i.id === id);
411
+ const im = item && Array.isArray(item.images) ? item.images[index] : undefined;
412
+ const file = im && typeof im.path === 'string' ? path.resolve(im.path) : null;
413
+ const root = path.resolve(c.imagesDir, id) + path.sep;
414
+ if (!file || !file.startsWith(root)) return { ok: false, error: 'Image not cached.' };
415
+ /** @type {Buffer} */
416
+ let buf;
417
+ try { buf = await fsp.readFile(file); } catch { return { ok: false, error: 'Image not cached.' }; }
418
+ const mime = sniffImageMime(buf);
419
+ if (!mime) return { ok: false, error: 'Cached file is not an image.' };
420
+ return { ok: true, dataUrl: `data:${mime};base64,${buf.toString('base64')}` };
208
421
  }
209
422
 
210
423
  /**
@@ -283,4 +496,5 @@ module.exports = {
283
496
  list,
284
497
  setStatus,
285
498
  linkEpic,
499
+ readCachedImage,
286
500
  };
@@ -14,11 +14,25 @@ function getClient() {
14
14
  }
15
15
 
16
16
  /**
17
- * Exactly the panel's submit call. @param {{ title: string, body: string, tag: string }} p
17
+ * The one submit path for the panel IPC and the admin route: prepares any
18
+ * attached images (renderer data URLs and/or absolute file paths) once via
19
+ * feedbackImages.prepareFeedbackImages, then calls client.submit. A prepare
20
+ * error resolves { ok: false, error } without submitting; otherwise the
21
+ * client's result (including any `warning`) is returned unchanged.
22
+ * @param {{ title: string, body: string, tag: string, images?: { dataUrl: string }[], imagePaths?: string[] }} p
18
23
  * @param {any} [client]
24
+ * @param {(inputs: { dataUrl?: string, path?: string }[]) => Promise<any>} [prepare]
19
25
  */
20
- function submitFeedback(p, client = getClient()) {
21
- return client.submit(p);
26
+ async function submitFeedback(p, client = getClient(), prepare = require('./feedbackImages.cjs').prepareFeedbackImages) {
27
+ const inputs = [
28
+ ...(p.images || []).map((i) => ({ dataUrl: i.dataUrl })),
29
+ ...(p.imagePaths || []).map((x) => ({ path: x })),
30
+ ];
31
+ const prepared = await prepare(inputs);
32
+ if (!prepared || !prepared.ok) {
33
+ return { ok: false, error: prepared && typeof prepared.error === 'string' ? prepared.error : 'Images could not be prepared.' };
34
+ }
35
+ return client.submit({ title: p.title, body: p.body, tag: p.tag, images: prepared.images });
22
36
  }
23
37
 
24
38
  /**
@@ -42,6 +56,8 @@ function registerCustomerFeedbackHandlers(deps = {}) {
42
56
  ipcMain.handle('customerFeedback:inbox-list', v(s.customerFeedbackInboxList, ({ includeHidden }) => inbox.list({ includeHidden })));
43
57
  ipcMain.handle('customerFeedback:inbox-set-status', v(s.customerFeedbackInboxSetStatus, ({ id, status, note }) => inbox.setStatus(id, status, note)));
44
58
  ipcMain.handle('customerFeedback:inbox-link-epic', v(s.customerFeedbackInboxLinkEpic, ({ id, epicId }) => inbox.linkEpic(id, epicId)));
59
+ // Returns the cached image's data URL to the renderer only — never log it.
60
+ ipcMain.handle('customerFeedback:inbox-image', v(s.customerFeedbackInboxImage, ({ id, index }) => inbox.readCachedImage(id, index)));
45
61
 
46
62
  // One-shot deferred refresh so users see resolutions without opening anything.
47
63
  try {
@@ -0,0 +1,171 @@
1
+ // @ts-check
2
+ /**
3
+ * feedbackImages — the single preparation point for images attached to a customer feedback item.
4
+ *
5
+ * Turns up to MAX_FEEDBACK_IMAGES inputs (an absolute file path, or a data URL) into validated,
6
+ * size-capped `{ dataUrl, mime, bytes }` entries ready for the bilko.run feedback POST, which
7
+ * checks each data URL against ^data:image/(png|jpeg|webp|gif);base64, and caps one at 2,000,000
8
+ * chars. Oversize PNG/JPEG are downscaled to JPEG through Electron's nativeImage (injectable).
9
+ *
10
+ * Errors are plain sentences naming the 1-based image index (plus at most a file basename) —
11
+ * never file contents.
12
+ */
13
+ 'use strict';
14
+
15
+ const path = require('node:path');
16
+ const fsp = require('node:fs/promises');
17
+ const { sniffImageMime } = require('../epic/epicAttachments.cjs');
18
+
19
+ const MAX_FEEDBACK_IMAGES = 5;
20
+ const MAX_IMAGE_DATAURL_CHARS = 1900000;
21
+ const MAX_TOTAL_DATAURL_CHARS = 8000000;
22
+ const MAX_RAW_IMAGE_BYTES = 26214400;
23
+
24
+ const DATA_URL_RE = /^data:image\/(png|jpeg|webp|gif);base64,/;
25
+ const BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
26
+ const DOWNSCALE_EDGES = [2000, 1600, 1280, 1024];
27
+ const DOWNSCALE_QUALITIES = [85, 70];
28
+
29
+ /**
30
+ * @typedef {{ path?: string, dataUrl?: string }} FeedbackImageInput
31
+ * @typedef {{ dataUrl: string, mime: string, bytes: number }} PreparedImage
32
+ * @typedef {{ isEmpty: () => boolean, getSize: () => { width: number, height: number },
33
+ * resize: (opts: { width?: number, height?: number, quality?: string }) => NativeImageLike,
34
+ * toJPEG: (quality: number) => Buffer }} NativeImageLike
35
+ * @typedef {{ createFromBuffer: (buf: Buffer) => NativeImageLike }} NativeImageModule
36
+ * @typedef {{ stat?: (p: string) => Promise<{ isFile: () => boolean, size: number }>,
37
+ * readFile?: (p: string) => Promise<Buffer>, nativeImage?: NativeImageModule }} Deps
38
+ * @typedef {{ ok: true, images: PreparedImage[] } | { ok: false, error: string }} PrepareResult
39
+ */
40
+
41
+ /** @returns {NativeImageModule} */
42
+ function defaultNativeImage() {
43
+ // Lazy: electron is only resolvable inside the app, and only needed for an oversize image.
44
+ const electron = /** @type {{ nativeImage: NativeImageModule }} */ (/** @type {unknown} */ (require('electron')));
45
+ return electron.nativeImage;
46
+ }
47
+
48
+ /** @param {string} mime @param {Buffer} buf */
49
+ function toDataUrl(mime, buf) {
50
+ return `data:${mime};base64,${buf.toString('base64')}`;
51
+ }
52
+
53
+ /**
54
+ * Downscale a PNG/JPEG to a JPEG whose data URL fits MAX_IMAGE_DATAURL_CHARS.
55
+ * @param {Buffer} buf @param {NativeImageModule} nativeImage
56
+ * @returns {Buffer|null}
57
+ */
58
+ function downscaleToJpeg(buf, nativeImage) {
59
+ const img = nativeImage.createFromBuffer(buf);
60
+ if (!img || img.isEmpty()) return null;
61
+ const { width, height } = img.getSize();
62
+ for (const edge of DOWNSCALE_EDGES) {
63
+ let scaled = img;
64
+ if (Math.max(width, height) > edge) {
65
+ scaled = width >= height
66
+ ? img.resize({ width: edge, quality: 'good' })
67
+ : img.resize({ height: edge, quality: 'good' });
68
+ }
69
+ for (const quality of DOWNSCALE_QUALITIES) {
70
+ const out = scaled.toJPEG(quality);
71
+ if (Buffer.isBuffer(out) && out.length > 0
72
+ && toDataUrl('image/jpeg', out).length <= MAX_IMAGE_DATAURL_CHARS) return out;
73
+ }
74
+ }
75
+ return null;
76
+ }
77
+
78
+ /**
79
+ * @param {FeedbackImageInput[]|undefined} inputs
80
+ * @param {Deps} [deps]
81
+ * @returns {Promise<PrepareResult>}
82
+ */
83
+ async function prepareFeedbackImages(inputs, deps = {}) {
84
+ if (inputs === undefined || inputs === null) return { ok: true, images: [] };
85
+ if (!Array.isArray(inputs)) return { ok: false, error: 'Images must be a list.' };
86
+ if (inputs.length === 0) return { ok: true, images: [] };
87
+ if (inputs.length > MAX_FEEDBACK_IMAGES) {
88
+ return { ok: false, error: `You can attach at most ${MAX_FEEDBACK_IMAGES} images to one feedback item.` };
89
+ }
90
+ const stat = deps.stat || ((/** @type {string} */ p) => fsp.stat(p));
91
+ const readFile = deps.readFile || ((/** @type {string} */ p) => fsp.readFile(p));
92
+
93
+ /** @type {PreparedImage[]} */
94
+ const images = [];
95
+ let total = 0;
96
+ for (let i = 0; i < inputs.length; i++) {
97
+ const n = i + 1;
98
+ const input = inputs[i] || {};
99
+ const hasPath = typeof input.path === 'string' && input.path.length > 0;
100
+ const hasData = typeof input.dataUrl === 'string' && input.dataUrl.length > 0;
101
+ if (hasPath === hasData) {
102
+ return { ok: false, error: `Image ${n} must have exactly one of a file path or a data URL.` };
103
+ }
104
+
105
+ /** @type {Buffer} */
106
+ let buf;
107
+ /** @type {string} */
108
+ let mime;
109
+ if (hasPath) {
110
+ const p = /** @type {string} */ (input.path);
111
+ const name = path.basename(p);
112
+ if (!path.isAbsolute(p)) return { ok: false, error: `Image ${n} (${name}) must be an absolute file path.` };
113
+ let st;
114
+ try { st = await stat(p); } catch {
115
+ return { ok: false, error: `Image ${n} (${name}) could not be found.` };
116
+ }
117
+ if (!st.isFile()) return { ok: false, error: `Image ${n} (${name}) is not a regular file.` };
118
+ if (st.size > MAX_RAW_IMAGE_BYTES) {
119
+ return { ok: false, error: `Image ${n} (${name}) is larger than ${Math.round(MAX_RAW_IMAGE_BYTES / 1048576)} MB.` };
120
+ }
121
+ try { buf = await readFile(p); } catch {
122
+ return { ok: false, error: `Image ${n} (${name}) could not be read.` };
123
+ }
124
+ const sniffed = sniffImageMime(buf);
125
+ if (!sniffed) return { ok: false, error: `Image ${n} (${name}) is not a PNG, JPEG, WebP or GIF file.` };
126
+ mime = sniffed;
127
+ } else {
128
+ const url = /** @type {string} */ (input.dataUrl);
129
+ const m = DATA_URL_RE.exec(url);
130
+ if (!m) return { ok: false, error: `Image ${n} is not a PNG, JPEG, WebP or GIF data URL.` };
131
+ const b64 = url.slice(m[0].length);
132
+ if (!b64 || !BASE64_RE.test(b64)) return { ok: false, error: `Image ${n} has invalid base64 data.` };
133
+ if (b64.length > Math.ceil(MAX_RAW_IMAGE_BYTES / 3) * 4) {
134
+ return { ok: false, error: `Image ${n} is larger than ${Math.round(MAX_RAW_IMAGE_BYTES / 1048576)} MB.` };
135
+ }
136
+ buf = Buffer.from(b64, 'base64');
137
+ const declared = `image/${m[1]}`;
138
+ if (sniffImageMime(buf) !== declared) {
139
+ return { ok: false, error: `Image ${n} content does not match its declared type ${declared}.` };
140
+ }
141
+ mime = declared;
142
+ }
143
+
144
+ let dataUrl = toDataUrl(mime, buf);
145
+ if (dataUrl.length > MAX_IMAGE_DATAURL_CHARS) {
146
+ if (mime !== 'image/png' && mime !== 'image/jpeg') {
147
+ return { ok: false, error: `Image ${n} is too large; WebP and GIF images cannot be shrunk automatically.` };
148
+ }
149
+ let out = null;
150
+ try { out = downscaleToJpeg(buf, deps.nativeImage || defaultNativeImage()); } catch { out = null; }
151
+ if (!out) return { ok: false, error: `Image ${n} is too large and could not be shrunk to fit.` };
152
+ buf = out;
153
+ mime = 'image/jpeg';
154
+ dataUrl = toDataUrl(mime, buf);
155
+ }
156
+ total += dataUrl.length;
157
+ if (total > MAX_TOTAL_DATAURL_CHARS) {
158
+ return { ok: false, error: 'The attached images are too large in total; attach fewer or smaller images.' };
159
+ }
160
+ images.push({ dataUrl, mime, bytes: buf.length });
161
+ }
162
+ return { ok: true, images };
163
+ }
164
+
165
+ module.exports = {
166
+ MAX_FEEDBACK_IMAGES,
167
+ MAX_IMAGE_DATAURL_CHARS,
168
+ MAX_TOTAL_DATAURL_CHARS,
169
+ MAX_RAW_IMAGE_BYTES,
170
+ prepareFeedbackImages,
171
+ };
@@ -37,11 +37,9 @@ const crypto = require('node:crypto');
37
37
  const fsp = require('node:fs/promises');
38
38
  const config = require('../../config.cjs');
39
39
  const schedulerPaths = require('../scheduler/schedulerPaths.cjs');
40
-
41
- // Reported on unknown-route 404s so a newer scheduler-mcp-server.cjs can tell
42
- // the agent which app version lacks the route. Read once; omitted if unreadable.
43
- let APP_VERSION = null;
44
- try { APP_VERSION = require('../../../../package.json').version || null; } catch { APP_VERSION = null; }
40
+ // App + outside-contract version, reported on the health route, unknown-route
41
+ // 404s and in the token file so outside callers never probe for a route.
42
+ const { contractInfo } = require('../externalContract.cjs');
45
43
 
46
44
  /**
47
45
  * Mode-aware token file path, resolved fresh on every call (never cached at
@@ -109,14 +107,14 @@ function createAdminHttp() {
109
107
  async function ensureToken() {
110
108
  token = crypto.randomBytes(32).toString('hex');
111
109
  const tokenPath = resolveTokenPath();
112
- await config.writeJson(tokenPath, { port: null, token });
110
+ await config.writeJson(tokenPath, { port: null, token, ...contractInfo() });
113
111
  try { await fsp.chmod(tokenPath, 0o600); } catch { /* best-effort on platforms without POSIX perms */ }
114
112
  return token;
115
113
  }
116
114
 
117
115
  async function persistPort(port) {
118
116
  const tokenPath = resolveTokenPath();
119
- await config.writeJson(tokenPath, { port, token });
117
+ await config.writeJson(tokenPath, { port, token, ...contractInfo() });
120
118
  try { await fsp.chmod(tokenPath, 0o600); } catch { /* */ }
121
119
  }
122
120
 
@@ -144,7 +142,7 @@ function createAdminHttp() {
144
142
  // /admin/scheduler/prds?cwd=&epicId=&status=).
145
143
  const urlObj = new URL(req.url, 'http://127.0.0.1');
146
144
  if (req.method === 'GET' && urlObj.pathname === HEALTH_PATH) {
147
- sendJson(res, 200, { ok: true });
145
+ sendJson(res, 200, { ok: true, ...contractInfo() });
148
146
  return;
149
147
  }
150
148
  try {
@@ -152,12 +150,15 @@ function createAdminHttp() {
152
150
  if (!handler) {
153
151
  // Keep error 'not found' so older MCP servers still see the same key;
154
152
  // unknownRoute marks this as transport-level (version skew), not a
155
- // route handler's own 'not found'.
153
+ // route handler's own 'not found'. appVersion is always present
154
+ // (null when unreadable) so outside callers see one shape.
155
+ const { appVersion, contractVersion } = contractInfo();
156
156
  sendJson(res, 404, {
157
157
  ok: false,
158
158
  error: 'not found',
159
159
  unknownRoute: `${req.method} ${urlObj.pathname}`,
160
- ...(APP_VERSION ? { appVersion: APP_VERSION } : {}),
160
+ appVersion: appVersion ?? null,
161
+ contractVersion,
161
162
  });
162
163
  return;
163
164
  }