claude-code-session-manager 0.136.2 → 0.138.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 (60) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/assets/{AgentLibrary-CbvVbzm2.js → AgentLibrary-C1d_D7uQ.js} +1 -1
  3. package/dist/assets/{AppSettings-Blks3xh_.js → AppSettings-CgDhqrsU.js} +1 -1
  4. package/dist/assets/{Button-hPwe-y_4.js → Button-Bk23rEnZ.js} +1 -1
  5. package/dist/assets/{DocumentEditorPane-C_fgkNoa.js → DocumentEditorPane-BqY5Nq6W.js} +1 -1
  6. package/dist/assets/{Extensions-CcDjNq7W.js → Extensions-CXem-uwI.js} +2 -2
  7. package/dist/assets/{History-D4s5ykcm.js → History-BwO3coo4.js} +1 -1
  8. package/dist/assets/{Library-BtJ7gnDM.js → Library-BDV69fSe.js} +1 -1
  9. package/dist/assets/{ListDetail-Bbwwd-HR.js → ListDetail-CD-Fm6mh.js} +1 -1
  10. package/dist/assets/{Panel-8xYPYH7R.js → Panel-CeDiyuNn.js} +1 -1
  11. package/dist/assets/ProjectClaudeConfig-NjdKdwe8.js +25 -0
  12. package/dist/assets/{ProvenanceBadge-COnyY49b.js → ProvenanceBadge-Bu8NmI_R.js} +1 -1
  13. package/dist/assets/{Scheduler-CpmSitKx.js → Scheduler-CkhTvG7C.js} +1 -1
  14. package/dist/assets/{Settings-Blfjp8Bp.js → Settings-COT34hBF.js} +1 -1
  15. package/dist/assets/{SkillReferenceGraph-pYSyx841.js → SkillReferenceGraph-CFMK8NJh.js} +1 -1
  16. package/dist/assets/{Skills-C4fV80-T.js → Skills-BgexoUkQ.js} +1 -1
  17. package/dist/assets/{SourceChip-Bx9marLv.js → SourceChip-BXjcdeb1.js} +1 -1
  18. package/dist/assets/{SystemPrompt-CBvedERn.js → SystemPrompt-CeeH3EeW.js} +1 -1
  19. package/dist/assets/{TiptapBody-BV7WhKYF.js → TiptapBody-D1kTj-tn.js} +1 -1
  20. package/dist/assets/{Toggle-BUPbeHTj.js → Toggle-CENi19iK.js} +1 -1
  21. package/dist/assets/{ViewTabs-oXSVRUrm.js → ViewTabs-DDBb0x96.js} +1 -1
  22. package/dist/assets/{VoiceButton-Ca6X_WNA.js → VoiceButton-CZeyPM31.js} +1 -1
  23. package/dist/assets/{historyTotals-BcJ7QH96.js → historyTotals-B00l64Jw.js} +1 -1
  24. package/dist/assets/index-CgCxpunJ.js +3116 -0
  25. package/dist/index.html +1 -1
  26. package/dist-web/app.js +384 -384
  27. package/package.json +1 -1
  28. package/plugins/CLAUDE.md +1 -0
  29. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  30. package/plugins/session-manager-dev/skills/builder/SKILL.md +1 -0
  31. package/plugins/session-manager-dev/skills/send-feedback/SKILL.md +2 -0
  32. package/scripts/scheduler-mcp-server.cjs +46 -2
  33. package/src/main/build-info.json +4 -4
  34. package/src/main/chatRunner.cjs +51 -0
  35. package/src/main/index.cjs +13 -7
  36. package/src/main/ipcSchemas.cjs +11 -0
  37. package/src/main/lib/CLAUDE.md +2 -0
  38. package/src/main/lib/demo-video-kit/checks.cjs +16 -0
  39. package/src/main/lib/epic/epicAttachments.cjs +143 -0
  40. package/src/main/lib/epic/epicMint.cjs +4 -0
  41. package/src/main/lib/feedback-remote/crossProjectReply.cjs +58 -12
  42. package/src/main/lib/feedback-remote/localAdminHttp.cjs +14 -1
  43. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +169 -1
  44. package/src/main/lib/feedback-remote/remoteFrameAssembler.cjs +113 -0
  45. package/src/main/lib/memoryRefResolve.cjs +64 -2
  46. package/src/main/lib/memoryStale.cjs +111 -18
  47. package/src/main/lib/persona-macro/macroLibrary.cjs +7 -0
  48. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  49. package/src/main/lib/process/bootStdioGuard.cjs +32 -0
  50. package/src/main/lib/process/stdioGuard.cjs +115 -0
  51. package/src/main/memoryAssist.cjs +23 -7
  52. package/src/main/memoryTool.cjs +58 -5
  53. package/src/main/promptSessionsIpc.cjs +1 -1
  54. package/src/main/templates/PRD_AUTHORING.md +3 -1
  55. package/src/preload/api.d.ts +29 -1
  56. package/src/preload/apiSurface.json +7 -0
  57. package/src/preload/index.cjs +2 -0
  58. package/src/seed/agents/demo-video-builder.md +10 -7
  59. package/dist/assets/ProjectClaudeConfig-B9PlbaSV.js +0 -25
  60. package/dist/assets/index-h8BmSc_8.js +0 -3116
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-code-session-manager",
3
- "version": "0.136.2",
3
+ "version": "0.138.0",
4
4
  "description": "Local cockpit for the Claude Code CLI — multi-tab terminal, full config surface, scheduler, voice dictation, and live observability.",
5
5
  "type": "module",
6
6
  "main": "src/main/index.cjs",
package/plugins/CLAUDE.md CHANGED
@@ -15,6 +15,7 @@ Two manifests: root [`.claude-plugin/marketplace.json`](../.claude-plugin/market
15
15
  declares the one plugin (`source: "./plugins/session-manager-dev"`); the plugin's own
16
16
  [`session-manager-dev/.claude-plugin/plugin.json`](session-manager-dev/.claude-plugin/plugin.json)
17
17
  carries the `description` shown in the marketplace UI — list only shipped skills.
18
+ Bumping a plugin's `plugin.json` version requires bumping its entry in `.claude-plugin/marketplace.json` in the same PRD (PRD 3140 was refuted for missing it).
18
19
 
19
20
  `src/main/seedDevPlugin.cjs` is the first-boot offline installer — installs this plugin from its
20
21
  bundled marketplace (no GitHub/registry call) as a default on a fresh machine, then marks
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "session-manager-dev",
3
3
  "description": "The default end-to-end development skillset for the Claude Code Session Manager: decompose work into scheduler PRDs and track them to a validated finish (/develop), publish releases to npm (/builder), hand a finding to another project on this machine (/send-feedback), and review or drift-check a project's CLAUDE.md/markdown network (/maintaining-md-network). Together with the session-manager scheduler these form a develop → queue → validate → release loop.",
4
- "version": "0.4.2",
4
+ "version": "0.4.3",
5
5
  "author": {
6
6
  "name": "Bilko Bibitkov",
7
7
  "email": "BilkoBibitkov2000@gmail.com",
@@ -90,6 +90,7 @@ have no `release.yml`) always use steps 5-11:
90
90
  paths as fixtures and fail there.
91
91
  6. In the worktree: `npm ci`, then the gates again (step 3), then the project's build. Check
92
92
  every `files` entry in `package.json` exists before publishing; stop on any failure.
93
+ A cold `test:unit` in a fresh publish worktree can time out under load; rerun the failed files, then the full suite, before calling the gate red — never publish on the partial rerun.
93
94
  7. `npm publish` from inside the worktree, so `prepublishOnly` builds there too.
94
95
  A 403 saying two-factor authentication or a bypass-2FA granular token is required is not a
95
96
  login problem (`npm whoami` can succeed). Don't retry `npm login` or `npm publish`: run
@@ -42,6 +42,8 @@ round-trip, not a wrong write.
42
42
  Routing a finding is the **default action, not a question**: a proposal starts
43
43
  nothing until a human there approves it. Send it, then report what you delivered.
44
44
 
45
+ `scheduler_create_prd` resolves its Epic against the CALLING project (a foreign `cwd` only narrows the search), so cross-project work always goes through `feedback_open_session`, never `create_prd`.
46
+
45
47
  ## Steps
46
48
 
47
49
  ### 1. Confirm it's really theirs
@@ -168,6 +168,37 @@ function resolveCwdArg(args) {
168
168
  return process.env.SM_PROJECT_ROOT || process.cwd();
169
169
  }
170
170
 
171
+ // This server is registered from a checkout that can be newer than the
172
+ // running app; its version goes into the version-skew message below.
173
+ const MCP_SERVER_VERSION = (() => {
174
+ try { return require('../package.json').version; } catch { return 'unknown'; }
175
+ })();
176
+
177
+ // The transport's own unknown-route 404 (localAdminHttp handleRequest). Apps
178
+ // up to v0.136.2 send exactly { ok:false, error:'not found' }; newer ones add
179
+ // unknownRoute. Route handlers' own 'not found' replies use HTTP 200
180
+ // (reset-job) or other error text (GET /admin/scheduler/prd), so they never match.
181
+ function isUnknownRouteReply(status, body) {
182
+ if (status !== 404 || !body || typeof body !== 'object' || Array.isArray(body)) return false;
183
+ if (body.ok !== false) return false;
184
+ if (typeof body.unknownRoute === 'string') return true;
185
+ return Object.keys(body).length === 2 && body.error === 'not found';
186
+ }
187
+
188
+ function unknownRouteError(method, urlPath, body) {
189
+ const pathname = String(urlPath).split('?')[0];
190
+ const appVersion = body && typeof body.appVersion === 'string' && body.appVersion
191
+ ? ` (running app: v${body.appVersion})` : '';
192
+ const err = new Error(
193
+ `the running Session Manager app has no route ${method} ${pathname}: the app${appVersion} is older than `
194
+ + `this MCP server (v${MCP_SERVER_VERSION}). Restart Session Manager (Command Palette: 'Reboot app (drain first)') `
195
+ + 'and call again.',
196
+ );
197
+ // Tagged so callers can add a tool-specific hint (feedback_reply does).
198
+ err.code = 'SM_UNKNOWN_ROUTE';
199
+ return err;
200
+ }
201
+
171
202
  async function readAdminConfig() {
172
203
  const raw = await fsp.readFile(adminTokenPath(), 'utf8');
173
204
  const parsed = JSON.parse(raw);
@@ -198,11 +229,14 @@ async function adminRequest(method, urlPath, body) {
198
229
  if (err?.cause?.code === 'ECONNREFUSED') throw new Error(NOT_RUNNING_ERROR);
199
230
  throw new Error(busyError(err?.cause?.code || err?.name || 'unknown'));
200
231
  }
232
+ let json;
201
233
  try {
202
- return await res.json();
234
+ json = await res.json();
203
235
  } catch {
204
236
  throw new Error(`admin API answered HTTP ${res.status} with a non-JSON body`);
205
237
  }
238
+ if (isUnknownRouteReply(res.status, json)) throw unknownRouteError(method, urlPath, json);
239
+ return json;
206
240
  }
207
241
 
208
242
  // session_manager_help's live half. The catalog/recipes below are static and
@@ -1089,7 +1123,17 @@ async function handleCallTool(request) {
1089
1123
  payload.originProjectRoot = process.env.SM_PROJECT_ROOT;
1090
1124
  }
1091
1125
  payload.fromCwd = process.cwd();
1092
- const result = await adminRequest('POST', '/admin/feedback/reply', payload);
1126
+ let result;
1127
+ try {
1128
+ result = await adminRequest('POST', '/admin/feedback/reply', payload);
1129
+ } catch (err) {
1130
+ if (err && err.code === 'SM_UNKNOWN_ROUTE') {
1131
+ return errorResult(`${err.message} feedback_reply needs Session Manager v0.136.0 or later. `
1132
+ + 'Until the app is restarted, send your answer with feedback_open_session to the asking project; '
1133
+ + 'it opens there as a new proposed session.');
1134
+ }
1135
+ throw err;
1136
+ }
1093
1137
  // Say only where the reply landed — never that the other project acted.
1094
1138
  let note = '';
1095
1139
  if (result?.ok !== false) {
@@ -1,8 +1,8 @@
1
1
  {
2
- "version": "0.136.2",
3
- "gitSha": "72952588d5ecbaa87f1436faf6af6363a3daf8f2",
4
- "gitShortSha": "72952588",
2
+ "version": "0.138.0",
3
+ "gitSha": "d3c7957b9d4f52d7fc1aa1df20850550892a7916",
4
+ "gitShortSha": "d3c7957b",
5
5
  "gitBranch": "HEAD",
6
- "builtAt": "2026-11-16T21:21:13.145Z",
6
+ "builtAt": "2026-11-22T01:19:06.929Z",
7
7
  "dirty": false
8
8
  }
@@ -1219,6 +1219,49 @@ function requestExternalNewSession(payload) {
1219
1219
  broadcast('chat:external-new-session', payload);
1220
1220
  }
1221
1221
 
1222
+ // Awaited sibling of requestExternalNewSession for the admin route
1223
+ // (POST /admin/macros/run): tags the payload with a requestId and resolves
1224
+ // once the renderer reports which Epic it minted. Never rejects.
1225
+ const EXTERNAL_NEW_SESSION_TIMEOUT_MS = 30000;
1226
+ const pendingExternalNewSessions = new Map(); // requestId -> { resolve, timer }
1227
+
1228
+ /**
1229
+ * @returns {Promise<{ ok: true, epicId: string } | { ok: false, reason: 'no-window'|'timeout'|'launch-failed', error: string }>}
1230
+ */
1231
+ function startExternalNewSession(payload) {
1232
+ if (!hasLiveWindow()) {
1233
+ return Promise.resolve({ ok: false, reason: 'no-window', error: 'Session Manager window is not open' });
1234
+ }
1235
+ const requestId = require('node:crypto').randomUUID();
1236
+ return new Promise((resolve) => {
1237
+ const timer = setTimeout(() => {
1238
+ pendingExternalNewSessions.delete(requestId);
1239
+ resolve({ ok: false, reason: 'timeout', error: 'renderer did not report the new session in time' });
1240
+ }, EXTERNAL_NEW_SESSION_TIMEOUT_MS);
1241
+ timer.unref?.();
1242
+ pendingExternalNewSessions.set(requestId, { resolve, timer });
1243
+ broadcast('chat:external-new-session', { ...payload, requestId });
1244
+ });
1245
+ }
1246
+
1247
+ function settleExternalNewSession({ requestId, ok, epicId, error }) {
1248
+ const entry = pendingExternalNewSessions.get(requestId);
1249
+ if (!entry) return;
1250
+ clearTimeout(entry.timer);
1251
+ pendingExternalNewSessions.delete(requestId);
1252
+ if (ok && epicId) entry.resolve({ ok: true, epicId });
1253
+ else entry.resolve({ ok: false, reason: 'launch-failed', error: error || 'renderer could not start the session' });
1254
+ }
1255
+
1256
+ // Read-only: is a chat turn for this tab running, being dispatched, parked
1257
+ // behind a worktree mint, or queued?
1258
+ function isTabBusy(tabId) {
1259
+ return inFlight.has(tabId)
1260
+ || dispatching.has(tabId)
1261
+ || pendingStart.has(tabId)
1262
+ || waiting.some((w) => w.tabId === tabId);
1263
+ }
1264
+
1222
1265
  /**
1223
1266
  * Registers the admin-HTTP entry point for enqueueExternalPrompt, mirroring
1224
1267
  * prdCreate.cjs's registerAdminRoute pattern (auth is the injected transport's
@@ -1294,6 +1337,10 @@ function registerChatHandlers() {
1294
1337
  settleExternalSend(payload);
1295
1338
  }));
1296
1339
 
1340
+ ipcMain.handle('chat:external-new-session-result', validated(schemas.chatExternalNewSessionResult, async (payload) => {
1341
+ settleExternalNewSession(payload);
1342
+ }));
1343
+
1297
1344
  ipcMain.handle('chat:cancel', async (_e, payload) => {
1298
1345
  let tabId;
1299
1346
  try { tabId = schemas.chatCancel.parse(payload).tabId; } catch { return; }
@@ -1332,5 +1379,9 @@ module.exports = {
1332
1379
  settleExternalSend,
1333
1380
  EXTERNAL_SEND_ACK_TIMEOUT_MS,
1334
1381
  requestExternalNewSession,
1382
+ startExternalNewSession,
1383
+ settleExternalNewSession,
1384
+ isTabBusy,
1385
+ EXTERNAL_NEW_SESSION_TIMEOUT_MS,
1335
1386
  registerAdminRoute,
1336
1387
  };
@@ -1,3 +1,8 @@
1
+ // Dead-stdio guard — must be the first statement. After the launching terminal
2
+ // closes, writes to the inherited stdout/stderr fail EIO/EPIPE and would surface
3
+ // as one uncaughtException per console line. The notice goes to the file logger
4
+ // (required lazily: logs.cjs pulls in electron's app), never to the dead stream.
5
+ try { require('./lib/process/bootStdioGuard.cjs').installBootStdioGuard(); } catch { /* the guard must never stop boot */ }
1
6
  // Boot diagnostic (SM_BOOT_DIAG=1, set by the packaged smoke): one stderr line that
2
7
  // shows whether `electron` resolved to the built-in module or ran in node mode.
3
8
  if (process.env.SM_BOOT_DIAG === '1') {
@@ -91,7 +96,11 @@ scheduler.registerAdminRoutes(adminHttp);
91
96
  prdCreate.registerAdminRoute(adminHttp, scheduler.remote);
92
97
  prdAdminRoutes.registerAdminRoute(adminHttp, scheduler.remote);
93
98
  projectHomeAdminRoutes.registerAdminRoute(adminHttp);
94
- macroAdminRoutes.registerAdminRoute(adminHttp, { onChanged: () => broadcastMacrosChanged() });
99
+ macroAdminRoutes.registerAdminRoute(adminHttp, {
100
+ onChanged: () => broadcastMacrosChanged(),
101
+ startExternalNewSession: chatRunner.startExternalNewSession,
102
+ isTabBusy: chatRunner.isTabBusy,
103
+ });
95
104
  chatRunner.registerAdminRoute(adminHttp);
96
105
  // Project-to-project feedback conduit — the app is the only process holding
97
106
  // several projects' operations roots open, so it performs the cross-folder
@@ -1339,12 +1348,9 @@ app.whenReady().then(async () => {
1339
1348
  console.error(`[insideHome] SELF-CHECK FAILED: ${bootHomeSelfCheck.error}; sessions will not be able to spawn`);
1340
1349
  }
1341
1350
 
1342
- process.on('uncaughtException', (err) => {
1343
- try {
1344
- require('./lib/telemetry/telemetryClient.cjs').reportError({ name: 'uncaughtException', msg: err?.message, stack: err?.stack });
1345
- } catch { /* telemetry must never break the existing handling below */ }
1346
- logs.writeLine({ scope: 'main', level: 'error', message: 'uncaughtException', meta: { error: err?.message, stack: err?.stack } });
1347
- });
1351
+ // A dead-stdio write error (EIO/EPIPE after the terminal closed) is reported
1352
+ // and logged at most once per process; every other error as before.
1353
+ process.on('uncaughtException', require('./lib/process/bootStdioGuard.cjs').createUncaughtExceptionHandler({ reportError: (p) => require('./lib/telemetry/telemetryClient.cjs').reportError(p), writeLine: (e) => logs.writeLine(e) }));
1348
1354
  process.on('unhandledRejection', (reason) => {
1349
1355
  const r = reason instanceof Error ? { error: reason.message, stack: reason.stack } : { reason: String(reason) };
1350
1356
  try {
@@ -1203,6 +1203,16 @@ const chatExternalSendResult = z.object({
1203
1203
  reason: z.enum(['terminal-attached', 'completed', 'unknown-target', 'empty-prompt']).optional(),
1204
1204
  });
1205
1205
 
1206
+ // Renderer's report of what it did with a chat:external-new-session that
1207
+ // carried a requestId (POST /admin/macros/run). Mirrors
1208
+ // ChatExternalNewSessionResult in preload/api.d.ts.
1209
+ const chatExternalNewSessionResult = z.object({
1210
+ requestId: z.string().min(1).max(64),
1211
+ ok: z.boolean(),
1212
+ epicId: z.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/).optional(),
1213
+ error: z.string().max(500).optional(),
1214
+ }).strict();
1215
+
1206
1216
  // Phone drill-down reads. cwd is re-checked against the open tabs in
1207
1217
  // webRemote.cjs; sessionKey becomes a transcript filename lookup so it is
1208
1218
  // restricted to a session-id charset (no '/', so no traversal).
@@ -1621,6 +1631,7 @@ module.exports = {
1621
1631
  chatClassifyTicket,
1622
1632
  chatExternalSend,
1623
1633
  chatExternalSendResult,
1634
+ chatExternalNewSessionResult,
1624
1635
  remoteSessionCreate,
1625
1636
  remoteProjectSessions,
1626
1637
  remoteSessionTranscript,
@@ -50,3 +50,5 @@ Pin `--model` on every `claude -p` spawn.
50
50
 
51
51
  - Never `path.join` an agent cwd to build an ops path — use `opsPath`.
52
52
  - No private process caps, no hand-rolled tmp+rename, no new `JSON.parse(readFileSync)` fallbacks.
53
+ - Never call `activeSessions.cjs` `allProjectCwds`/`activeProjectCwds` on an IPC, boot or timer hot path: they scan `~/.claude/projects` synchronously (7k+ dirs, 0.3-4 s; the 2026-10-25 OOM crashes).
54
+ - `ipcSchemas.cjs` `validated()` passes the zod-parsed payload, which strips unknown keys: an IPC key rename the schema misses silently drops the key (2026-11-07 persona wipe). Rename keys and schema in one PRD; prefer `.strict()`.
@@ -111,6 +111,20 @@ function checkBlankFrames(frames, threshold = DEFAULT_BLANK_STDDEV) {
111
111
  bad.length ? `blank frame(s) at ${bad.map((f) => `${f.t}s`).join(', ')}` : `${list.length} frame(s) non-blank`);
112
112
  }
113
113
 
114
+ // Project Home's VideoPlayer draws the only control bar; a video that draws its own
115
+ // shows a second one under it. The injected player bridge script is not the video's.
116
+ const PLAYER_BRIDGE_BLOCK_RE = /<script\b[^>]*\bdata-sm-player-bridge\b[^>]*>[\s\S]*?<\/script\s*>/gi;
117
+ const CONTROL_PATTERNS = [
118
+ ['button', /<button\b/i],
119
+ ['input', /<input\b/i],
120
+ ['audio controls', /<audio\b[^>]*\scontrols\b/i],
121
+ ['video controls', /<video\b[^>]*\scontrols\b/i],
122
+ ];
123
+ function ownPlaybackControls(html) {
124
+ const h = String(html || '').replace(PLAYER_BRIDGE_BLOCK_RE, '');
125
+ return CONTROL_PATTERNS.filter(([, re]) => re.test(h)).map(([what]) => what);
126
+ }
127
+
114
128
  function checkHtmlLimits({ html, bytes, lengthS } = {}) {
115
129
  const h = String(html || '');
116
130
  const size = Number.isFinite(bytes) ? bytes : Buffer.byteLength(h);
@@ -122,6 +136,8 @@ function checkHtmlLimits({ html, bytes, lengthS } = {}) {
122
136
  if (!dur) problems.push('sm-demo-duration meta missing');
123
137
  else if (Number(dur[1]) !== Number(lengthS)) problems.push(`sm-demo-duration ${dur[1]} != ${lengthS}`);
124
138
  if (!/window\.smDemo\s*=/.test(h) || !/scenes\s*:/.test(h)) problems.push('window.smDemo with scenes missing');
139
+ const controls = ownPlaybackControls(h);
140
+ if (controls.length) problems.push(`own playback controls: ${controls.join(', ')}`);
125
141
  return result('htmlLimits', problems.length === 0, problems.length ? problems.join('; ') : `${size} bytes within cap ${cap}`);
126
142
  }
127
143
 
@@ -0,0 +1,143 @@
1
+ 'use strict';
2
+ // @ts-check
3
+
4
+ /**
5
+ * epicAttachments.cjs — validate + save base64 images sent from the phone
6
+ * remote into the same dir the desktop Epic composer uses
7
+ * (<project>/session-manager-operations/prompt-sessions/attachments/), and
8
+ * compose the prompt with the same `Attached: <abs path>` lines
9
+ * (EpicComposer.tsx) so Claude reads them with its Read tool.
10
+ *
11
+ * Writes go through config.cjs writeBinaryAtomic under writer 'epics'
12
+ * (single-writer law). config.cjs is required lazily — it pulls Electron.
13
+ */
14
+
15
+ const path = require('node:path');
16
+ const crypto = require('node:crypto');
17
+ const fsp = require('node:fs/promises');
18
+ const { opsPath } = require('../opsOwnership.cjs');
19
+
20
+ const ATTACHMENT_MIMES = Object.freeze({
21
+ 'image/png': '.png',
22
+ 'image/jpeg': '.jpg',
23
+ 'image/gif': '.gif',
24
+ 'image/webp': '.webp',
25
+ });
26
+ const MAX_IMAGES = 6;
27
+ const MAX_IMAGE_BYTES = 3 * 1024 * 1024;
28
+ const MAX_TOTAL_BYTES = 12 * 1024 * 1024;
29
+ const BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
30
+
31
+ /** sniffImageMime(buf) → one of ATTACHMENT_MIMES' keys, or null. */
32
+ function sniffImageMime(buf) {
33
+ if (!Buffer.isBuffer(buf)) return null;
34
+ if (buf.length >= 8 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47
35
+ && buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a) return 'image/png';
36
+ if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'image/jpeg';
37
+ if (buf.length >= 6) {
38
+ const sig = buf.subarray(0, 6).toString('latin1');
39
+ if (sig === 'GIF87a' || sig === 'GIF89a') return 'image/gif';
40
+ }
41
+ if (buf.length >= 12 && buf.subarray(0, 4).toString('latin1') === 'RIFF'
42
+ && buf.subarray(8, 12).toString('latin1') === 'WEBP') return 'image/webp';
43
+ return null;
44
+ }
45
+
46
+ /** safeAttachmentName(name, mime) → sanitized basename with the mime's extension. */
47
+ function safeAttachmentName(name, mime) {
48
+ const ext = ATTACHMENT_MIMES[mime] || '';
49
+ let base = typeof name === 'string' ? name : '';
50
+ base = base.split(/[\\/]/).pop() || '';
51
+ const dot = base.lastIndexOf('.');
52
+ if (dot > 0) base = base.slice(0, dot);
53
+ else if (dot === 0) base = base.slice(1);
54
+ base = base.replace(/[^A-Za-z0-9._-]/g, '-').slice(0, 60);
55
+ if (!base || /^[.-]+$/.test(base)) base = 'image';
56
+ return `${base}${ext}`;
57
+ }
58
+
59
+ function attachmentsDir(projectCwd) {
60
+ return opsPath(projectCwd, 'prompt-sessions', 'attachments');
61
+ }
62
+
63
+ /**
64
+ * saveChatImages({ projectCwd, images }, deps?) →
65
+ * { ok: true, paths, names } | { ok: false, reason }
66
+ * images: [{ name, mime, data (base64) }]. Validates all before writing any.
67
+ */
68
+ async function saveChatImages({ projectCwd, images }, deps = {}) {
69
+ const list = Array.isArray(images) ? images : [];
70
+ if (list.length > MAX_IMAGES) return { ok: false, reason: 'too-many' };
71
+ const decoded = [];
72
+ let total = 0;
73
+ for (const img of list) {
74
+ if (!img || typeof img !== 'object') return { ok: false, reason: 'bad-data' };
75
+ const { name, mime, data } = img;
76
+ if (typeof mime !== 'string' || !Object.prototype.hasOwnProperty.call(ATTACHMENT_MIMES, mime)) {
77
+ return { ok: false, reason: 'bad-type' };
78
+ }
79
+ if (typeof data !== 'string' || data.length === 0 || data.length % 4 !== 0 || !BASE64_RE.test(data)) {
80
+ return { ok: false, reason: 'bad-data' };
81
+ }
82
+ // Cheap pre-decode size bound so a huge payload is refused before allocation.
83
+ if (Math.floor((data.length * 3) / 4) - 2 > MAX_IMAGE_BYTES) return { ok: false, reason: 'too-large' };
84
+ const buf = Buffer.from(data, 'base64');
85
+ if (buf.length === 0) return { ok: false, reason: 'bad-data' };
86
+ if (buf.length > MAX_IMAGE_BYTES) return { ok: false, reason: 'too-large' };
87
+ total += buf.length;
88
+ if (total > MAX_TOTAL_BYTES) return { ok: false, reason: 'too-large' };
89
+ if (sniffImageMime(buf) !== mime) return { ok: false, reason: 'bad-type' };
90
+ decoded.push({ buf, fileName: `${crypto.randomUUID().slice(0, 8)}-${safeAttachmentName(name, mime)}` });
91
+ }
92
+
93
+ const writeBinary = deps.writeBinary || require('../../config.cjs').writeBinaryAtomic;
94
+ const paths = [];
95
+ try {
96
+ const dir = attachmentsDir(projectCwd);
97
+ for (const { buf, fileName } of decoded) {
98
+ const dest = path.join(dir, fileName);
99
+ await writeBinary(dest, buf, { writer: 'epics' });
100
+ paths.push(dest);
101
+ }
102
+ } catch {
103
+ await removeSavedAttachments(projectCwd, paths, deps);
104
+ return { ok: false, reason: 'write-failed' };
105
+ }
106
+ return { ok: true, paths, names: paths.map((p) => path.basename(p)) };
107
+ }
108
+
109
+ /** composeAttachedPrompt(text, paths) — identical to EpicComposer.tsx. */
110
+ function composeAttachedPrompt(text, paths) {
111
+ const trimmed = typeof text === 'string' ? text.trim() : '';
112
+ const list = Array.isArray(paths) ? paths : [];
113
+ if (!list.length) return trimmed;
114
+ const lines = list.map((p) => `Attached: ${p}`).join('\n');
115
+ return trimmed ? `${trimmed}\n\n${lines}` : lines;
116
+ }
117
+
118
+ /** removeSavedAttachments(projectCwd, paths, deps?) — unlinks only files inside
119
+ * the project's attachments dir; never throws. */
120
+ async function removeSavedAttachments(projectCwd, paths, deps = {}) {
121
+ const unlink = deps.unlink || fsp.unlink;
122
+ let dir;
123
+ try { dir = attachmentsDir(projectCwd); } catch { return; }
124
+ const prefix = dir + path.sep;
125
+ for (const p of Array.isArray(paths) ? paths : []) {
126
+ if (typeof p !== 'string') continue;
127
+ const abs = path.resolve(p);
128
+ if (!abs.startsWith(prefix)) continue;
129
+ try { await unlink(abs); } catch { /* already gone */ }
130
+ }
131
+ }
132
+
133
+ module.exports = {
134
+ ATTACHMENT_MIMES,
135
+ MAX_IMAGES,
136
+ MAX_IMAGE_BYTES,
137
+ MAX_TOTAL_BYTES,
138
+ sniffImageMime,
139
+ safeAttachmentName,
140
+ saveChatImages,
141
+ composeAttachedPrompt,
142
+ removeSavedAttachments,
143
+ };
@@ -15,6 +15,10 @@
15
15
  * caller is join-only and throws rather than conjuring an Epic. Agents that
16
16
  * are sure work is needed run /develop inside the Epic they are already in;
17
17
  * agents that are not sure say so and let the human open an Epic.
18
+ * A script start of a macro a human marked 'Can be started by a script'
19
+ * (POST /admin/macros/run) reaches this mint through the renderer's New Epic
20
+ * UI path (the same IPC handler as a press) and adds no mint authority —
21
+ * MINT_AUTHORITIES stays two.
18
22
  *
19
23
  * The Epic registry is the renderer's own store: the per-cwd
20
24
  * `session-manager-operations/prompt-sessions/active-index.json`
@@ -17,6 +17,9 @@
17
17
  * never for scheduler jobs) — never from an agent-supplied Epic id;
18
18
  * - Y must be a cross-project-feedback Epic carrying a complete replyTo;
19
19
  * anything else is a NEW request, which is feedback_open_session's job;
20
+ * - LEGACY: a request Epic minted before reply threads (no replyTo, no
21
+ * replyOf) threads to source.fromEpicId in source.fromCwd, without the
22
+ * Claude-session check;
20
23
  * - the target is replyTo.epicId and nothing else (toEpicId may only
21
24
  * restate it);
22
25
  * - at most MAX_REPLIES_PER_THREAD replies per Y, serialized per Y in
@@ -212,16 +215,11 @@ async function sendFeedbackReply(input, deps = {}) {
212
215
  if (!y) return bad(403, 'no Epic in the calling project owns this chat session — cannot reply');
213
216
 
214
217
  // 3. Thread.
215
- const src = y.source || {};
216
- const rt = src.replyTo;
217
- const threadComplete = src.producer === 'cross-project-feedback' && rt && typeof rt === 'object'
218
- && typeof rt.cwd === 'string' && rt.cwd
219
- && typeof rt.epicId === 'string' && rt.epicId
220
- && typeof rt.claudeSessionId === 'string' && rt.claudeSessionId;
221
- if (!threadComplete) {
222
- return bad(400, 'this session is not answering a cross-project request with a reply thread — '
223
- + 'a new request to another project goes through feedback_open_session');
224
- }
218
+ const resolved = resolveThread(y.source || {});
219
+ if (!resolved.ok) return bad(400, resolved.error);
220
+ const rt = resolved.thread;
221
+ const legacy = resolved.legacy;
222
+ const threadField = legacy ? { thread: 'legacy' } : {};
225
223
  if (input.toEpicId !== undefined && input.toEpicId !== null && input.toEpicId !== rt.epicId) {
226
224
  return bad(403, `this session may only reply to Epic ${rt.epicId}, the one that asked`);
227
225
  }
@@ -229,7 +227,7 @@ async function sendFeedbackReply(input, deps = {}) {
229
227
  try {
230
228
  targetCwd = config.validatePath(path.resolve(rt.cwd));
231
229
  } catch (e) {
232
- return bad(400, `replyTo.cwd rejected: ${e.message}`);
230
+ return bad(400, `${legacy ? 'source.fromCwd' : 'replyTo.cwd'} rejected: ${e.message}`);
233
231
  }
234
232
  if (!feedbackConduit().isSessionManagerProject(targetCwd)) {
235
233
  return bad(400, `${targetCwd} is not a Session Manager project`);
@@ -296,6 +294,7 @@ async function sendFeedbackReply(input, deps = {}) {
296
294
  toEpicId: rt.epicId,
297
295
  fallbackEpicId: opened.epicId,
298
296
  receiptOnAskingEpic,
297
+ ...threadField,
299
298
  ...receiptFields(receipt),
300
299
  repliesUsed: sent + 1,
301
300
  repliesLeft: MAX_REPLIES_PER_THREAD - sent - 1,
@@ -306,7 +305,10 @@ async function sendFeedbackReply(input, deps = {}) {
306
305
  const x = readActiveIndex(targetCwd).sessions[rt.epicId];
307
306
  if (!x) return fallback('missing');
308
307
  if (x.status !== 'active') return fallback('not-active');
309
- if (x.claudeSessionId !== rt.claudeSessionId) return fallback('session-mismatch');
308
+ // Legacy threads carry no session pin; X's own (1:1, life-long) session is the one that asked.
309
+ if (legacy ? !(typeof x.claudeSessionId === 'string' && x.claudeSessionId) : x.claudeSessionId !== rt.claudeSessionId) {
310
+ return fallback('session-mismatch');
311
+ }
310
312
 
311
313
  const prompt = composeReplyPrompt({
312
314
  fromCwd: replierCwd,
@@ -349,6 +351,7 @@ async function sendFeedbackReply(input, deps = {}) {
349
351
  fromEpicId: yId,
350
352
  outcome,
351
353
  delivery,
354
+ ...threadField,
352
355
  });
353
356
 
354
357
  return {
@@ -356,6 +359,7 @@ async function sendFeedbackReply(input, deps = {}) {
356
359
  delivery,
357
360
  toCwd: targetCwd,
358
361
  toEpicId: x.id,
362
+ ...threadField,
359
363
  ...receiptFields(receipt),
360
364
  repliesUsed: sent + 1,
361
365
  repliesLeft: MAX_REPLIES_PER_THREAD - sent - 1,
@@ -364,6 +368,48 @@ async function sendFeedbackReply(input, deps = {}) {
364
368
  });
365
369
  }
366
370
 
371
+ const nonEmpty = (v) => typeof v === 'string' && v.length > 0;
372
+
373
+ /**
374
+ * resolveThread(src) — pure. The thread a replying Epic's `source` names:
375
+ * { ok: true, thread: { cwd, epicId, claudeSessionId }, legacy } or { ok: false, error }.
376
+ * A complete replyTo → legacy false. A pre-reply-thread request Epic (no
377
+ * replyTo key, no replyOf, fromCwd + fromEpicId set) → legacy true, no
378
+ * session pin. Every refusal says why and points at feedback_open_session.
379
+ */
380
+ function resolveThread(src) {
381
+ const s = src && typeof src === 'object' ? src : {};
382
+ const isRequest = s.producer === 'cross-project-feedback';
383
+ const rt = s.replyTo;
384
+ if (isRequest && rt && typeof rt === 'object'
385
+ && nonEmpty(rt.cwd) && nonEmpty(rt.epicId) && nonEmpty(rt.claudeSessionId)) {
386
+ return { ok: true, thread: { cwd: rt.cwd, epicId: rt.epicId, claudeSessionId: rt.claudeSessionId }, legacy: false };
387
+ }
388
+ if (s.replyOf) {
389
+ return {
390
+ ok: false,
391
+ error: 'this session is itself a reply that could not be delivered, so it has no thread to answer — '
392
+ + 'a new request to another project goes through feedback_open_session',
393
+ };
394
+ }
395
+ const hasReplyTo = Object.prototype.hasOwnProperty.call(s, 'replyTo');
396
+ if (isRequest && !hasReplyTo && nonEmpty(s.fromCwd)) {
397
+ if (nonEmpty(s.fromEpicId)) {
398
+ return { ok: true, thread: { cwd: s.fromCwd, epicId: s.fromEpicId, claudeSessionId: null }, legacy: true };
399
+ }
400
+ return {
401
+ ok: false,
402
+ error: 'the sending session was not identified when this request was opened, so there is no thread to answer — '
403
+ + `send a new request to ${s.fromCwd} with feedback_open_session`,
404
+ };
405
+ }
406
+ return {
407
+ ok: false,
408
+ error: 'this session is not answering a cross-project request with a reply thread — '
409
+ + 'a new request to another project goes through feedback_open_session',
410
+ };
411
+ }
412
+
367
413
  /** Registers POST /admin/feedback/reply on the loopback admin transport —
368
414
  * mirrors crossProjectFeedback.registerAdminRoute; auth is the transport's. */
369
415
  function registerAdminRoute(adminHttp, deps) {
@@ -38,6 +38,11 @@ const fsp = require('node:fs/promises');
38
38
  const config = require('../../config.cjs');
39
39
  const schedulerPaths = require('../scheduler/schedulerPaths.cjs');
40
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; }
45
+
41
46
  /**
42
47
  * Mode-aware token file path, resolved fresh on every call (never cached at
43
48
  * module load) so a dev/e2e launch never collides with a production
@@ -145,7 +150,15 @@ function createAdminHttp() {
145
150
  try {
146
151
  const handler = routes.get(`${req.method} ${urlObj.pathname}`);
147
152
  if (!handler) {
148
- sendJson(res, 404, { ok: false, error: 'not found' });
153
+ // Keep error 'not found' so older MCP servers still see the same key;
154
+ // unknownRoute marks this as transport-level (version skew), not a
155
+ // route handler's own 'not found'.
156
+ sendJson(res, 404, {
157
+ ok: false,
158
+ error: 'not found',
159
+ unknownRoute: `${req.method} ${urlObj.pathname}`,
160
+ ...(APP_VERSION ? { appVersion: APP_VERSION } : {}),
161
+ });
149
162
  return;
150
163
  }
151
164
  await handler(req, res, urlObj.searchParams);