claude-code-session-manager 0.137.0 → 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 (44) hide show
  1. package/dist/assets/{AgentLibrary-DV0DTZDC.js → AgentLibrary-C1d_D7uQ.js} +1 -1
  2. package/dist/assets/{AppSettings-l7NTc0yu.js → AppSettings-CgDhqrsU.js} +1 -1
  3. package/dist/assets/{Button-Cmfkgjfa.js → Button-Bk23rEnZ.js} +1 -1
  4. package/dist/assets/{DocumentEditorPane-MTljV-Uw.js → DocumentEditorPane-BqY5Nq6W.js} +1 -1
  5. package/dist/assets/{Extensions-Cc1Q_8id.js → Extensions-CXem-uwI.js} +2 -2
  6. package/dist/assets/{History-CFo-1DHo.js → History-BwO3coo4.js} +1 -1
  7. package/dist/assets/{Library-C_ibFiOx.js → Library-BDV69fSe.js} +1 -1
  8. package/dist/assets/{ListDetail-ByULG209.js → ListDetail-CD-Fm6mh.js} +1 -1
  9. package/dist/assets/{Panel-BuInRmA0.js → Panel-CeDiyuNn.js} +1 -1
  10. package/dist/assets/{ProjectClaudeConfig-yqqVtHY7.js → ProjectClaudeConfig-NjdKdwe8.js} +1 -1
  11. package/dist/assets/{ProvenanceBadge-CJvnQReI.js → ProvenanceBadge-Bu8NmI_R.js} +1 -1
  12. package/dist/assets/{Scheduler-B7sn2mUw.js → Scheduler-CkhTvG7C.js} +1 -1
  13. package/dist/assets/{Settings-DRRSJksU.js → Settings-COT34hBF.js} +1 -1
  14. package/dist/assets/{SkillReferenceGraph-DwV0Ueyc.js → SkillReferenceGraph-CFMK8NJh.js} +1 -1
  15. package/dist/assets/{Skills-DVYHA9gV.js → Skills-BgexoUkQ.js} +1 -1
  16. package/dist/assets/{SourceChip-DfJ5_5rV.js → SourceChip-BXjcdeb1.js} +1 -1
  17. package/dist/assets/{SystemPrompt-f11wGllK.js → SystemPrompt-CeeH3EeW.js} +1 -1
  18. package/dist/assets/{TiptapBody-Bl8hDhhS.js → TiptapBody-D1kTj-tn.js} +1 -1
  19. package/dist/assets/{Toggle-DaxeFDFp.js → Toggle-CENi19iK.js} +1 -1
  20. package/dist/assets/{ViewTabs-DRtgFKRw.js → ViewTabs-DDBb0x96.js} +1 -1
  21. package/dist/assets/{VoiceButton-DJx-jY4r.js → VoiceButton-CZeyPM31.js} +1 -1
  22. package/dist/assets/{historyTotals-Cgjm5q24.js → historyTotals-B00l64Jw.js} +1 -1
  23. package/dist/assets/index-CgCxpunJ.js +3116 -0
  24. package/dist/index.html +1 -1
  25. package/dist-web/app.js +383 -383
  26. package/package.json +1 -1
  27. package/src/main/build-info.json +4 -4
  28. package/src/main/chatRunner.cjs +51 -0
  29. package/src/main/index.cjs +13 -7
  30. package/src/main/ipcSchemas.cjs +11 -0
  31. package/src/main/lib/demo-video-kit/checks.cjs +16 -0
  32. package/src/main/lib/epic/epicAttachments.cjs +143 -0
  33. package/src/main/lib/epic/epicMint.cjs +4 -0
  34. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +169 -1
  35. package/src/main/lib/feedback-remote/remoteFrameAssembler.cjs +113 -0
  36. package/src/main/lib/persona-macro/macroLibrary.cjs +7 -0
  37. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  38. package/src/main/lib/process/bootStdioGuard.cjs +32 -0
  39. package/src/main/lib/process/stdioGuard.cjs +115 -0
  40. package/src/preload/api.d.ts +27 -1
  41. package/src/preload/apiSurface.json +7 -0
  42. package/src/preload/index.cjs +2 -0
  43. package/src/seed/agents/demo-video-builder.md +10 -7
  44. package/dist/assets/index-iQ6pdyuS.js +0 -3116
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-code-session-manager",
3
- "version": "0.137.0",
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",
@@ -1,8 +1,8 @@
1
1
  {
2
- "version": "0.137.0",
3
- "gitSha": "2ec9176d21aa5c815cbf59feeb935924dcb3342e",
4
- "gitShortSha": "2ec9176d",
2
+ "version": "0.138.0",
3
+ "gitSha": "d3c7957b9d4f52d7fc1aa1df20850550892a7916",
4
+ "gitShortSha": "d3c7957b",
5
5
  "gitBranch": "HEAD",
6
- "builtAt": "2026-11-19T18:18:31.246Z",
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,
@@ -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`
@@ -32,6 +32,18 @@
32
32
  * Every successful save appends one `admin_macro_save` audit event and calls
33
33
  * `onChanged()` exactly once so the Sessions HOT KEYS strip updates live,
34
34
  * matching the IPC handlers in index.cjs.
35
+ *
36
+ * POST /admin/macros/run {cwd, id, inputs?, effort?}
37
+ * -> { ok, epicId, alreadyRunning }
38
+ * Starts a saved macro from a script (e.g. a systemd timer) through the
39
+ * renderer's press path (deps.startExternalNewSession: same persona, tag, AIM
40
+ * prompt and source.macroId, so autoStartTargets apply). Refused (400, no
41
+ * launch) unless a human ticked 'Can be started by a script' (scriptStart)
42
+ * on a visible, non-builtin, non-job macro whose persona is listed. {{inputs}}
43
+ * = the macro's defaults overlaid by `inputs`. While that macro's Epic is
44
+ * still running in the cwd it returns that Epic (alreadyRunning:true) instead
45
+ * of a second start. A launch failure is a 503 with no audit event.
46
+ * curl -s -X POST "http://127.0.0.1:$(jq -r .port ~/.claude/session-manager/admin-api.json)/admin/macros/run" -H "Authorization: Bearer $(jq -r .token ~/.claude/session-manager/admin-api.json)" -H 'Content-Type: application/json' -d '{"cwd":"/abs/project","id":"<macro-id>"}'
35
47
  */
36
48
  'use strict';
37
49
 
@@ -40,6 +52,8 @@ const { resolveCwd } = require('./projectHomeAdminRoutes.cjs');
40
52
  const macroLibrary = require('../persona-macro/macroLibrary.cjs');
41
53
  const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
42
54
  const { findHumanPromptContaining } = require('./humanPromptLedger.cjs');
55
+ const { readActiveIndex } = require('../epic/epicMint.cjs');
56
+ const { PRD_EFFORT_LEVELS } = require('../prd/prdFrontmatter.cjs');
43
57
 
44
58
  const EVERY_PROJECT_RE = /(^|[^a-z0-9])(every|all|each)\s+(of\s+)?(my\s+|the\s+|our\s+)?projects?($|[^a-z0-9])/;
45
59
 
@@ -250,11 +264,165 @@ function deleteHandler(onChanged, libOpts) {
250
264
  };
251
265
  }
252
266
 
253
- function registerAdminRoute(adminHttp, { onChanged } = {}, opts = {}) {
267
+ const RUN_INPUT_MAX_KEYS = 20;
268
+ const RUN_INPUT_MAX_LEN = 2000;
269
+ const RECENT_START_MS = 60_000;
270
+ const OPEN_STATUSES = new Set(['proposed', 'active']);
271
+ /** `${cwd}\u0000${id}` -> { epicId, at } — starts made by this route. */
272
+ const recentRuns = new Map();
273
+ /** `${cwd}\u0000${id}` -> Promise<{ok, epicId?}> — runs still awaiting the renderer. */
274
+ const inProgressRuns = new Map();
275
+
276
+ const SCRIPT_START_HINT = "the human can tick 'Can be started by a script' in the macro editor";
277
+
278
+ /** The open Epic this macro is already running in `cwd`, or null. */
279
+ function findRunningEpic(cwd, id, isTabBusy) {
280
+ const index = readActiveIndex(cwd);
281
+ for (const epic of Object.values(index.sessions)) {
282
+ if (!epic || typeof epic !== 'object' || !OPEN_STATUSES.has(epic.status)) continue;
283
+ const src = epic.source;
284
+ if (!src || src.producer !== 'new-epic-ui' || src.macroId !== id) continue;
285
+ if (typeof epic.id === 'string' && isTabBusy(epic.id)) return epic.id;
286
+ }
287
+ const key = `${cwd}\u0000${id}`;
288
+ const recent = recentRuns.get(key);
289
+ if (recent && Date.now() - recent.at < RECENT_START_MS) {
290
+ const entry = index.sessions[recent.epicId];
291
+ // Not in the index yet = just minted and still being persisted: open.
292
+ const open = entry ? OPEN_STATUSES.has(entry.status) : !index.tombstones[recent.epicId];
293
+ if (open) return recent.epicId;
294
+ } else if (recent) {
295
+ recentRuns.delete(key);
296
+ }
297
+ return null;
298
+ }
299
+
300
+ /** Returns an error string, or null when `inputs` is acceptable for `macro`. */
301
+ function validateRunInputs(inputs, macro) {
302
+ if (inputs === undefined) return null;
303
+ if (inputs === null || typeof inputs !== 'object' || Array.isArray(inputs)) return 'inputs must be an object';
304
+ const keys = Object.keys(inputs);
305
+ if (keys.length > RUN_INPUT_MAX_KEYS) return `inputs: at most ${RUN_INPUT_MAX_KEYS} keys`;
306
+ const declared = new Set((macro.inputs || []).map((i) => i.name));
307
+ for (const k of keys) {
308
+ if (!declared.has(k)) return `inputs: ${k} is not an input of macro ${macro.id}`;
309
+ const v = inputs[k];
310
+ if (typeof v !== 'string') return `inputs: ${k} must be a string`;
311
+ if (v.length > RUN_INPUT_MAX_LEN) return `inputs: ${k} is longer than ${RUN_INPUT_MAX_LEN} characters`;
312
+ }
313
+ return null;
314
+ }
315
+
316
+ function runHandler(deps, libOpts) {
317
+ const listPersonas = deps.listPersonas || ((...a) => require('../../agentLibrary.cjs').listPersonas(...a));
318
+ return async (req, res) => {
319
+ const body = await readJsonBody(req, res);
320
+ if (!body) return;
321
+ const resolved = resolveCwd(body.cwd);
322
+ if (!resolved.ok) {
323
+ sendJson(res, resolved.status, { ok: false, error: resolved.error });
324
+ return;
325
+ }
326
+ const cwd = resolved.cwd;
327
+ const bad = (error) => sendJson(res, 400, { ok: false, error });
328
+ const id = body.id;
329
+ if (typeof id !== 'string' || !id) return bad('id is required');
330
+ if (id.startsWith('builtin-')) return bad('built-in macros cannot be started through this route');
331
+ const macros = await macroLibrary.listMacros(libOpts);
332
+ const macro = macros.find((m) => m.id === id);
333
+ if (!macro) return bad(`macro not found: ${id}`);
334
+ if (!macroLibrary.macroVisibleIn(macro, cwd)) return bad(`macro ${id} is not visible to ${cwd}`);
335
+ if (macro.job) return bad(`macro ${id} runs a job, not a session; it cannot be started through this route`);
336
+ if (macro.scriptStart !== true) {
337
+ return bad(`macro ${id} is not marked 'Can be started by a script'; ${SCRIPT_START_HINT}`);
338
+ }
339
+ const personas = await listPersonas();
340
+ if (!personas.some((a) => a.name === macro.agentName)) return bad(`unknown agent: ${macro.agentName}`);
341
+ const inputsError = validateRunInputs(body.inputs, macro);
342
+ if (inputsError) return bad(inputsError);
343
+ const effort = body.effort;
344
+ if (effort !== undefined && !PRD_EFFORT_LEVELS.includes(effort)) {
345
+ return bad(`effort must be one of: ${PRD_EFFORT_LEVELS.join(', ')}`);
346
+ }
347
+ const rendered = macroLibrary.renderMacroPrompt(macro.prompt, macro.inputs, {
348
+ ...macroLibrary.defaultMacroValues(macro.inputs),
349
+ ...(body.inputs || {}),
350
+ });
351
+ if (!rendered.ok) return bad(rendered.error);
352
+
353
+ const key = `${cwd}\u0000${id}`;
354
+ const pending = inProgressRuns.get(key);
355
+ if (pending) {
356
+ const first = await pending;
357
+ if (first.ok) {
358
+ sendJson(res, 200, { ok: true, epicId: first.epicId, alreadyRunning: true });
359
+ } else {
360
+ sendJson(res, 503, { ok: false, error: first.error || 'launch failed' });
361
+ }
362
+ return;
363
+ }
364
+ const running = findRunningEpic(cwd, id, deps.isTabBusy || (() => false));
365
+ if (running) {
366
+ sendJson(res, 200, { ok: true, epicId: running, alreadyRunning: true });
367
+ return;
368
+ }
369
+
370
+ const payload = {
371
+ cwd,
372
+ agentName: macro.agentName,
373
+ tag: macro.tag,
374
+ title: macro.label,
375
+ prompt: rendered.prompt,
376
+ macroId: macro.id,
377
+ via: 'script',
378
+ ...(effort !== undefined ? { effort } : {}),
379
+ };
380
+ const launch = (async () => {
381
+ try {
382
+ return await deps.startExternalNewSession(payload);
383
+ } catch (e) {
384
+ return { ok: false, reason: 'launch-failed', error: e?.message ?? 'launch failed' };
385
+ }
386
+ })();
387
+ inProgressRuns.set(key, launch);
388
+ let result;
389
+ try {
390
+ result = await launch;
391
+ if (result && result.ok) recentRuns.set(key, { epicId: result.epicId, at: Date.now() });
392
+ } finally {
393
+ inProgressRuns.delete(key);
394
+ }
395
+ if (!result || !result.ok) {
396
+ const error = result?.reason === 'timeout'
397
+ ? 'timed out waiting for the window; the session may still start, check the Sessions queue before retrying'
398
+ : result?.error || 'launch failed';
399
+ sendJson(res, 503, { ok: false, error });
400
+ return;
401
+ }
402
+ appendAuditEvent('admin_macro_run', {
403
+ route: '/admin/macros/run',
404
+ cwd,
405
+ macroId: macro.id,
406
+ epicId: result.epicId,
407
+ alreadyRunning: false,
408
+ });
409
+ sendJson(res, 200, { ok: true, epicId: result.epicId, alreadyRunning: false });
410
+ };
411
+ }
412
+
413
+ /**
414
+ * @param {{ onChanged?: () => void, startExternalNewSession?: (p: object) => Promise<any>,
415
+ * isTabBusy?: (tabId: string) => boolean, listPersonas?: () => Promise<Array<{name: string}>> }} deps
416
+ */
417
+ function registerAdminRoute(adminHttp, deps = {}, opts = {}) {
418
+ const { onChanged } = deps;
254
419
  const libOpts = opts.filePath ? { filePath: opts.filePath } : undefined;
255
420
  adminHttp.registerRoute('GET', '/admin/macros', listHandler(onChanged, libOpts));
256
421
  adminHttp.registerRoute('POST', '/admin/macros/save', saveHandler(onChanged, libOpts));
257
422
  adminHttp.registerRoute('POST', '/admin/macros/delete', deleteHandler(onChanged, libOpts));
423
+ if (typeof deps.startExternalNewSession === 'function') {
424
+ adminHttp.registerRoute('POST', '/admin/macros/run', runHandler(deps, libOpts));
425
+ }
258
426
  }
259
427
 
260
428
  module.exports = {
@@ -0,0 +1,113 @@
1
+ 'use strict'
2
+
3
+ // Inbound twin of remoteIpcDispatch.cjs's chunkFrames: rebuilds a browser→desktop
4
+ // message that arrived as several E2E-boxed `e2e:frame` envelopes (the bilko.run
5
+ // relay drops any socket message over 256 KB, so large uploads are split into
6
+ // ≤180 KB frames). Pure, per-client state with hard memory bounds — a buggy or
7
+ // hostile browser cannot exhaust desktop memory: bounded frames per message,
8
+ // bounded bytes per message, bounded concurrent messages per client, idle TTL.
9
+
10
+ const { joinFrames } = require('./remoteIpcDispatch.cjs')
11
+
12
+ const FRAME_LIMITS = Object.freeze({
13
+ maxMessageBytes: 25 * 1024 * 1024,
14
+ maxInflightPerClient: 2,
15
+ maxFrames: 200,
16
+ idleTtlMs: 60000,
17
+ })
18
+
19
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
20
+
21
+ function createFrameAssembler({
22
+ maxMessageBytes = FRAME_LIMITS.maxMessageBytes,
23
+ maxInflightPerClient = FRAME_LIMITS.maxInflightPerClient,
24
+ maxFrames = FRAME_LIMITS.maxFrames,
25
+ idleTtlMs = FRAME_LIMITS.idleTtlMs,
26
+ now = Date.now,
27
+ } = {}) {
28
+ /** @type {Map<string, Map<string, { total: number, frames: Map<number, string>, bytes: number, lastAt: number }>>} */
29
+ const clients = new Map()
30
+
31
+ function free(clientKey, msgId) {
32
+ const msgs = clients.get(clientKey)
33
+ if (!msgs) return
34
+ msgs.delete(msgId)
35
+ if (msgs.size === 0) clients.delete(clientKey)
36
+ }
37
+
38
+ function refuse(clientKey, msgId, reason) {
39
+ if (msgId !== undefined) free(clientKey, msgId)
40
+ return { status: 'refused', reason }
41
+ }
42
+
43
+ function sweep() {
44
+ const t = now()
45
+ for (const [clientKey, msgs] of clients) {
46
+ for (const [msgId, entry] of msgs) {
47
+ if (t - entry.lastAt > idleTtlMs) msgs.delete(msgId)
48
+ }
49
+ if (msgs.size === 0) clients.delete(clientKey)
50
+ }
51
+ }
52
+
53
+ function dropClient(clientKey) {
54
+ clients.delete(clientKey)
55
+ }
56
+
57
+ function accept(clientKey, payload) {
58
+ sweep()
59
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return refuse(clientKey, undefined, 'malformed')
60
+ const { msgId, seq, total, data } = payload
61
+ if (
62
+ typeof msgId !== 'string' || !UUID_RE.test(msgId) ||
63
+ !Number.isInteger(total) || total < 1 || total > maxFrames ||
64
+ !Number.isInteger(seq) || seq < 0 || seq >= total ||
65
+ typeof data !== 'string'
66
+ ) {
67
+ return refuse(clientKey, undefined, 'malformed')
68
+ }
69
+
70
+ let msgs = clients.get(clientKey)
71
+ let entry = msgs && msgs.get(msgId)
72
+ if (!entry) {
73
+ if (msgs && msgs.size >= maxInflightPerClient) return refuse(clientKey, undefined, 'too_many_inflight')
74
+ if (data.length > maxMessageBytes) return refuse(clientKey, undefined, 'too_large')
75
+ entry = { total, frames: new Map(), bytes: 0, lastAt: now() }
76
+ if (!msgs) {
77
+ msgs = new Map()
78
+ clients.set(clientKey, msgs)
79
+ }
80
+ msgs.set(msgId, entry)
81
+ } else {
82
+ if (entry.total !== total) return refuse(clientKey, msgId, 'total_mismatch')
83
+ if (entry.frames.has(seq)) return refuse(clientKey, msgId, 'duplicate_seq')
84
+ if (entry.bytes + data.length > maxMessageBytes) return refuse(clientKey, msgId, 'too_large')
85
+ }
86
+
87
+ entry.frames.set(seq, data)
88
+ entry.bytes += data.length
89
+ entry.lastAt = now()
90
+ if (entry.frames.size < entry.total) return { status: 'partial' }
91
+
92
+ free(clientKey, msgId)
93
+ const ordered = []
94
+ for (let i = 0; i < entry.total; i++) ordered.push({ seq: i, total: entry.total, data: entry.frames.get(i) })
95
+ let envelope
96
+ try {
97
+ envelope = joinFrames(ordered)
98
+ } catch {
99
+ return { status: 'refused', reason: 'bad_json' }
100
+ }
101
+ if (
102
+ !envelope || typeof envelope !== 'object' || Array.isArray(envelope) ||
103
+ typeof envelope.type !== 'string' || envelope.type.startsWith('e2e:')
104
+ ) {
105
+ return { status: 'refused', reason: 'bad_inner' }
106
+ }
107
+ return { status: 'complete', envelope }
108
+ }
109
+
110
+ return { accept, dropClient, sweep }
111
+ }
112
+
113
+ module.exports = { createFrameAssembler, FRAME_LIMITS }