claude-code-session-manager 0.126.0 → 0.128.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.
- package/bin/cli.cjs +71 -9
- package/bin/supervise.cjs +84 -0
- package/dist/assets/{AgentLibrary-bzeuZN4F.js → AgentLibrary-cNQU5YWy.js} +1 -1
- package/dist/assets/{Button-8dWfDDuQ.js → Button-9dIPAOBg.js} +1 -1
- package/dist/assets/{DataModel-D4ybBPZN.js → DataModel-DrDJ6ysw.js} +1 -1
- package/dist/assets/{History-hsztE6yh.js → History-4rrDdWNP.js} +1 -1
- package/dist/assets/{Hooks-CRmZMQaW.js → Hooks-Bj_jF5Pa.js} +1 -1
- package/dist/assets/{Library-Czt3Bojd.js → Library-D-Wsxrh7.js} +1 -1
- package/dist/assets/{ListDetail-Cr6Ct_WX.js → ListDetail-D7Om0H8j.js} +1 -1
- package/dist/assets/{McpServers-CeXJ2bng.js → McpServers-CbIbSd5o.js} +1 -1
- package/dist/assets/{Memory-caujO8O3.js → Memory-DgQlvQrO.js} +1 -1
- package/dist/assets/{Panel-D64i9tGz.js → Panel-DZHiD8Ar.js} +1 -1
- package/dist/assets/{Permissions-DpWOIrvr.js → Permissions-CfzduF4B.js} +1 -1
- package/dist/assets/{Plugins-Bd1ekP5P.js → Plugins-D-AG5nAo.js} +2 -2
- package/dist/assets/{ProvenanceBadge-B96A_uZf.js → ProvenanceBadge-B9JSEjll.js} +1 -1
- package/dist/assets/{SaveBar-D0Y2t-Ao.js → SaveBar-mVKig6hL.js} +1 -1
- package/dist/assets/{Scheduler-Y5_YbNrC.js → Scheduler-DFTCnh60.js} +1 -1
- package/dist/assets/{ScopeSwitcher-BmWA_dP9.js → ScopeSwitcher-s8J-yr7Z.js} +1 -1
- package/dist/assets/{Settings-Bcf65bpL.js → Settings-BTmxRMaP.js} +1 -1
- package/dist/assets/{SkillReferenceGraph-BeSNXloA.js → SkillReferenceGraph-C5lKqf5y.js} +1 -1
- package/dist/assets/{Skills-DwnQKJVc.js → Skills-CxOacq0k.js} +1 -1
- package/dist/assets/{SystemPrompt-Dih6SCmL.js → SystemPrompt-BCWg5FAz.js} +1 -1
- package/dist/assets/{TagLibrary-BZ-Kp10P.js → TagLibrary-BnF0_PkG.js} +1 -1
- package/dist/assets/{TiptapBody-C2nEUmF7.js → TiptapBody-C2Iu6rZd.js} +1 -1
- package/dist/assets/{Toggle-Dw8-zNQo.js → Toggle-C-oD66BG.js} +1 -1
- package/dist/assets/{ViewTabs-CoYPKGN-.js → ViewTabs-Cs4v7vLY.js} +1 -1
- package/dist/assets/{historyTotals-BbKcNpV7.js → historyTotals-CbRSLD8f.js} +1 -1
- package/dist/assets/{index-BnKaYERU.css → index-DtdWBGrI.css} +1 -1
- package/dist/assets/index-DzY_GXYY.js +3081 -0
- package/dist/assets/{settingsSchema-6doG_61l.js → settingsSchema-bSBfHuan.js} +1 -1
- package/dist/assets/{skillFrontmatter-BYMYWDfb.js → skillFrontmatter-BEseWm8r.js} +1 -1
- package/dist/assets/{useAgentsDirWatch-Cqabjieh.js → useAgentsDirWatch-CdyHxKCI.js} +1 -1
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +343 -341
- package/package.json +1 -1
- package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -2
- package/scripts/scheduler-mcp-server.cjs +209 -7
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +37 -4
- package/src/main/crashDiagnostics.cjs +83 -8
- package/src/main/health.cjs +16 -5
- package/src/main/index.cjs +46 -0
- package/src/main/ipcSchemas.cjs +107 -0
- package/src/main/lib/chatBootRecovery.cjs +136 -0
- package/src/main/lib/chatInflight.cjs +88 -0
- package/src/main/lib/claude/agentModelResolve.cjs +26 -7
- package/src/main/lib/claude/personaToolScope.cjs +40 -2
- package/src/main/lib/demo-video-kit/capture.cjs +113 -0
- package/src/main/lib/demo-video-kit/character.cjs +97 -0
- package/src/main/lib/demo-video-kit/checks.cjs +150 -0
- package/src/main/lib/demo-video-kit/frames.cjs +200 -0
- package/src/main/lib/demo-video-kit/seedKit.cjs +52 -0
- package/src/main/lib/demo-video-kit/sound.cjs +312 -0
- package/src/main/lib/epic/epicDelegationStats.cjs +1 -0
- package/src/main/lib/epic/epicSweepValidator.cjs +60 -6
- package/src/main/lib/epic/epicValidationHook.cjs +31 -3
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +71 -15
- package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +185 -34
- package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +15 -0
- package/src/main/lib/mcpToolCatalog.cjs +93 -14
- package/src/main/lib/opsOwnership.cjs +9 -5
- package/src/main/lib/persona-macro/builtinMacros.cjs +30 -5
- package/src/main/lib/persona-macro/macroJobDispatch.cjs +116 -0
- package/src/main/lib/persona-macro/macroJobIpc.cjs +50 -0
- package/src/main/lib/persona-macro/macroJobStatus.cjs +112 -0
- package/src/main/lib/persona-macro/macroLibrary.cjs +73 -3
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +100 -0
- package/src/main/lib/prd/prdCreate.cjs +17 -2
- package/src/main/lib/prd/prdFrontmatter.cjs +7 -2
- package/src/main/lib/process/childWithLog.cjs +38 -95
- package/src/main/lib/process/memoryScope.cjs +140 -0
- package/src/main/lib/process/ozonePlatform.cjs +15 -0
- package/src/main/lib/process/procIdentity.cjs +10 -3
- package/src/main/lib/process/scopeOomPolicy.cjs +69 -0
- package/src/main/lib/project-pages/pagesLibrary.cjs +171 -0
- package/src/main/lib/project-pages/playerBridge.cjs +129 -0
- package/src/main/lib/scheduler/cpuSample.cjs +147 -0
- package/src/main/lib/scheduler/definitionOfDone.cjs +40 -0
- package/src/main/lib/scheduler/jobLeftovers.cjs +204 -0
- package/src/main/lib/scheduler/jobSupervisorRecord.cjs +2 -1
- package/src/main/lib/scheduler/loadGate.cjs +116 -45
- package/src/main/lib/scheduler/queueStore.cjs +5 -2
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
- package/src/main/lib/scheduler/schedulerBatch.cjs +10 -3
- package/src/main/lib/scheduler/schedulerConfig.cjs +7 -2
- package/src/main/lib/smfileHeaders.cjs +11 -3
- package/src/main/lib/telemetry/crashTelemetry.cjs +8 -4
- package/src/main/projectPages.cjs +107 -30
- package/src/main/promptSessionsIpc.cjs +131 -0
- package/src/main/scheduler/budget.cjs +31 -0
- package/src/main/scheduler/prdParser.cjs +2 -0
- package/src/main/scheduler/prdPaths.cjs +54 -0
- package/src/main/scheduler/reviewLadder.cjs +17 -0
- package/src/main/scheduler/starvation.cjs +22 -0
- package/src/main/scheduler.cjs +548 -77
- package/src/main/seedSchedulerMcp.cjs +10 -1
- package/src/main/templates/PRD_AUTHORING.md +5 -2
- package/src/main/transcripts.cjs +8 -0
- package/src/main/usage.cjs +4 -2
- package/src/main/webRemote.cjs +3 -1
- package/src/preload/api.d.ts +113 -7
- package/src/preload/apiSurface.json +70 -0
- package/src/preload/index.cjs +13 -0
- package/src/seed/agents/demo-video-builder.md +141 -43
- package/src/seed/agents/project-home-builder.md +26 -13
- package/dist/assets/index-DgPUERhe.js +0 -3079
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* shouldFire(ctx) returns true, then calls action(ctx).
|
|
22
22
|
* - action() may call ctx.addTimer(t) to register secondary timers
|
|
23
23
|
* (e.g. SIGTERM → SIGKILL cascades) so they are also cleared on exit.
|
|
24
|
-
* Calls onExit() inside the child 'exit'/'error' handler,
|
|
24
|
+
* Calls onExit() synchronously inside the child 'exit'/'error' handler,
|
|
25
25
|
* before calling closeFd(). Caller may call ctx.safeLog() inside onExit.
|
|
26
26
|
*
|
|
27
27
|
* WatchdogContext:
|
|
@@ -40,10 +40,7 @@
|
|
|
40
40
|
* killedByWatchdog — string | null
|
|
41
41
|
* error — Error | undefined (child 'error' event or sync spawn throw)
|
|
42
42
|
* spawnFailed — boolean, true when the error came from a synchronous spawn throw
|
|
43
|
-
*
|
|
44
|
-
* sweepChildProcessGroup found still alive right before it
|
|
45
|
-
* swept them. [] in the normal case (nothing leaked, or
|
|
46
|
-
* non-Linux, or enumeration failed). See sweepChildProcessGroup.
|
|
43
|
+
* pid — number | null, the child pid (null when spawn threw)
|
|
47
44
|
* safeLog — same safeLog (usable inside onExit for final log lines)
|
|
48
45
|
*
|
|
49
46
|
* Returns { child, cancel } where cancel() clears all timers + SIGKILLs.
|
|
@@ -51,13 +48,10 @@
|
|
|
51
48
|
*/
|
|
52
49
|
|
|
53
50
|
const fs = require('node:fs');
|
|
54
|
-
const { spawn
|
|
51
|
+
const { spawn } = require('node:child_process');
|
|
55
52
|
const { killTree } = require('./killTree.cjs');
|
|
56
53
|
const { feedChildStdin } = require('./childStdin.cjs');
|
|
57
54
|
|
|
58
|
-
// Injectable for tests (enumeration-failure coverage).
|
|
59
|
-
const deps = { execFile };
|
|
60
|
-
|
|
61
55
|
// Grace period between the post-exit SIGTERM sweep and the follow-up SIGKILL
|
|
62
56
|
// sweep of a detached child's process group. See sweepChildProcessGroup below.
|
|
63
57
|
const POST_EXIT_GROUP_SWEEP_GRACE_MS = 5000;
|
|
@@ -145,65 +139,24 @@ function openLog(logPath) {
|
|
|
145
139
|
// a job's descendants must not outlive the job. Killing the job's own process
|
|
146
140
|
// group at the job's own exit is ownership-based and needs no /proc heuristics
|
|
147
141
|
// to distinguish an abandoned descendant from a live one.
|
|
148
|
-
//
|
|
149
|
-
//
|
|
150
|
-
//
|
|
151
|
-
//
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
// ps -eo is Linux-only; on win32 (and macOS) report the empty/unknown result without spawning ps.
|
|
156
|
-
if (process.platform !== 'linux') return Promise.resolve([]);
|
|
157
|
-
if (!pgid || pgid <= 1) return Promise.resolve([]);
|
|
158
|
-
return new Promise((resolve, reject) => {
|
|
159
|
-
try {
|
|
160
|
-
deps.execFile('ps', ['-eo', 'pid,pgrp,pcpu,etimes,comm'], { encoding: 'utf8', timeout: 2000 }, (err, out) => {
|
|
161
|
-
if (err) { reject(err); return; }
|
|
162
|
-
const survivors = [];
|
|
163
|
-
for (const line of String(out).split('\n').slice(1)) {
|
|
164
|
-
const m = line.trim().match(/^(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(.+)$/);
|
|
165
|
-
if (!m) continue;
|
|
166
|
-
const [, pidStr, pgrpStr, pcpuStr, etimesStr, comm] = m;
|
|
167
|
-
if (Number(pgrpStr) !== pgid) continue;
|
|
168
|
-
survivors.push({ pid: Number(pidStr), pcpu: Number(pcpuStr), etimes: Number(etimesStr), comm });
|
|
169
|
-
}
|
|
170
|
-
resolve(survivors);
|
|
171
|
-
});
|
|
172
|
-
} catch (e) { reject(e); }
|
|
173
|
-
});
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
// Returns null when there is nothing to enumerate/sweep (non-detached, missing or
|
|
177
|
-
// invalid pid, our own group) so the caller can finish synchronously. Otherwise
|
|
178
|
-
// returns a promise for the leaked descendants: enumeration runs FIRST so the
|
|
179
|
-
// report reflects what the sweep is about to reap, and SIGTERM (+ the delayed
|
|
180
|
-
// SIGKILL) is issued only once it has SETTLED — resolved or rejected. The 2 s ps
|
|
181
|
-
// timeout bounds that wait. The promise never rejects: a failed enumeration
|
|
182
|
-
// resolves [] after a safeLog line, and the group is still killed.
|
|
183
|
-
function sweepChildProcessGroup(child, detached, safeLog) {
|
|
184
|
-
if (!detached) return null;
|
|
185
|
-
if (!child || !child.pid || child.pid <= 1) return null;
|
|
142
|
+
// Synchronous and fire-and-forget: SIGTERM now, SIGKILL after the grace period.
|
|
143
|
+
// What escaped the group is reported by the job-marker scan (jobLeftovers), not here.
|
|
144
|
+
// No-op when there is nothing to sweep (non-detached, missing or invalid pid, our
|
|
145
|
+
// own group, win32).
|
|
146
|
+
function sweepChildProcessGroup(child, detached) {
|
|
147
|
+
if (!detached) return;
|
|
148
|
+
if (!child || !child.pid || child.pid <= 1) return;
|
|
186
149
|
// Defensive: never target the Session Manager process's own group.
|
|
187
|
-
if (child.pid === process.pid) return
|
|
150
|
+
if (child.pid === process.pid) return;
|
|
188
151
|
// win32 has no process groups; taskkill on an already-exited pid risks hitting a reused pid.
|
|
189
|
-
if (process.platform === 'win32') return
|
|
152
|
+
if (process.platform === 'win32') return;
|
|
190
153
|
|
|
191
154
|
const pid = child.pid;
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
if (t.unref) t.unref();
|
|
198
|
-
};
|
|
199
|
-
|
|
200
|
-
return enumerateProcessGroupSurvivors(pid)
|
|
201
|
-
.then((all) => all.filter((p) => p.pid !== pid))
|
|
202
|
-
.catch((e) => {
|
|
203
|
-
safeLog(`[childWithLog] process-group enumeration failed; leak report omitted: ${e && e.message}\n`);
|
|
204
|
-
return [];
|
|
205
|
-
})
|
|
206
|
-
.then((leaked) => { kill(); return leaked; });
|
|
155
|
+
killTree(pid, 'SIGTERM'); // ESRCH on an empty group is the normal case
|
|
156
|
+
const t = setTimeout(() => {
|
|
157
|
+
killTree(pid, 'SIGKILL');
|
|
158
|
+
}, POST_EXIT_GROUP_SWEEP_GRACE_MS);
|
|
159
|
+
if (t.unref) t.unref();
|
|
207
160
|
}
|
|
208
161
|
|
|
209
162
|
/**
|
|
@@ -272,37 +225,27 @@ function withChildAndLog({ fd, logPath, safeLog, closeFd, spawn: spawnSpec, watc
|
|
|
272
225
|
// calls onExit (caller may still safeLog inside), then closes the fd.
|
|
273
226
|
const handleDone = (exitCode, signal, error, spawnFailed) => {
|
|
274
227
|
clearAllTimers();
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
}
|
|
288
|
-
} catch (e) {
|
|
289
|
-
// Log while the fd is still open (closeFd below makes safeLog a no-op),
|
|
290
|
-
// then rethrow: sync callers see the throw as before PRD 1353; the
|
|
291
|
-
// deferred path contains it below.
|
|
292
|
-
const stack = e && e.stack ? String(e.stack).split('\n').slice(0, 3).join('\n') : '';
|
|
293
|
-
safeLog(`[childWithLog] onExit threw: ${e && e.message}${stack ? `\n${stack}` : ''}\n`);
|
|
294
|
-
throw e;
|
|
295
|
-
} finally {
|
|
296
|
-
closeFd();
|
|
228
|
+
sweepChildProcessGroup(ctx.child, !!spawnSpec.options?.detached);
|
|
229
|
+
try {
|
|
230
|
+
if (onExit) {
|
|
231
|
+
onExit({
|
|
232
|
+
exitCode,
|
|
233
|
+
signal: signal ?? null,
|
|
234
|
+
killedByWatchdog: ctx.killedByWatchdog,
|
|
235
|
+
error,
|
|
236
|
+
spawnFailed: spawnFailed ?? false,
|
|
237
|
+
pid: ctx.child && ctx.child.pid ? ctx.child.pid : null,
|
|
238
|
+
safeLog,
|
|
239
|
+
});
|
|
297
240
|
}
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
241
|
+
} catch (e) {
|
|
242
|
+
// Log while the fd is still open (closeFd below makes safeLog a no-op), then rethrow.
|
|
243
|
+
const stack = e && e.stack ? String(e.stack).split('\n').slice(0, 3).join('\n') : '';
|
|
244
|
+
safeLog(`[childWithLog] onExit threw: ${e && e.message}${stack ? `\n${stack}` : ''}\n`);
|
|
245
|
+
throw e;
|
|
246
|
+
} finally {
|
|
247
|
+
closeFd();
|
|
248
|
+
}
|
|
306
249
|
};
|
|
307
250
|
|
|
308
251
|
// Attempt synchronous spawn. On failure, call handleDone immediately so the
|
|
@@ -337,4 +280,4 @@ function withChildAndLog({ fd, logPath, safeLog, closeFd, spawn: spawnSpec, watc
|
|
|
337
280
|
return { child, cancel };
|
|
338
281
|
}
|
|
339
282
|
|
|
340
|
-
module.exports = { openLog, withChildAndLog, POST_EXIT_GROUP_SWEEP_GRACE_MS
|
|
283
|
+
module.exports = { openLog, withChildAndLog, POST_EXIT_GROUP_SWEEP_GRACE_MS };
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* memoryScope.cjs — wrap a command in a transient systemd user scope with
|
|
5
|
+
* memory limits so a runaway process hits its own cgroup limit instead of the
|
|
6
|
+
* machine's global OOM. Degrades to a plain spawn wherever scopes are
|
|
7
|
+
* unavailable (callers use scopeSupported()).
|
|
8
|
+
*
|
|
9
|
+
* `systemd-run --scope` execs the command in place, so the spawned pid stays
|
|
10
|
+
* the job's own pid and detached process groups keep working.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const childProcess = require('node:child_process');
|
|
14
|
+
const fs = require('node:fs');
|
|
15
|
+
const path = require('node:path');
|
|
16
|
+
|
|
17
|
+
const DEFAULT_MAX_CAP_MB = 10240;
|
|
18
|
+
const DEFAULT_MAX_FRACTION = 0.45;
|
|
19
|
+
const HIGH_FRACTION = 0.85;
|
|
20
|
+
const DEFAULT_SWAP_MAX_MB = 4096;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @param {{ totalRamMb?: number, env?: Record<string, string | undefined> }} [opts]
|
|
24
|
+
* @returns {{ memoryMaxMb: number, memoryHighMb: number, swapMaxMb: number } | null} null = disabled
|
|
25
|
+
*/
|
|
26
|
+
function memoryLimitsFor(opts = {}) {
|
|
27
|
+
const env = opts.env || process.env;
|
|
28
|
+
const raw = env.SM_JOB_MEMORY_MAX_MB;
|
|
29
|
+
let max;
|
|
30
|
+
if (raw !== undefined && raw !== '' && Number.isFinite(Number(raw)) && Number(raw) >= 0) {
|
|
31
|
+
max = Math.floor(Number(raw));
|
|
32
|
+
} else {
|
|
33
|
+
const total = Number(opts.totalRamMb);
|
|
34
|
+
if (!Number.isFinite(total) || total <= 0) return null;
|
|
35
|
+
max = Math.min(DEFAULT_MAX_CAP_MB, Math.floor(total * DEFAULT_MAX_FRACTION));
|
|
36
|
+
}
|
|
37
|
+
if (max <= 0) return null;
|
|
38
|
+
return {
|
|
39
|
+
memoryMaxMb: max,
|
|
40
|
+
memoryHighMb: Math.floor(HIGH_FRACTION * max),
|
|
41
|
+
swapMaxMb: DEFAULT_SWAP_MAX_MB,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** @type {boolean | null} */
|
|
46
|
+
let cachedSupport = null;
|
|
47
|
+
|
|
48
|
+
/** Test hook: forget the cached probe result. */
|
|
49
|
+
function _resetScopeSupportCache() {
|
|
50
|
+
cachedSupport = null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @param {{ platform?: string, spawnSync?: typeof childProcess.spawnSync, fs?: { existsSync: (p: string) => boolean }, env?: Record<string, string | undefined> }} [deps]
|
|
55
|
+
* @returns {boolean}
|
|
56
|
+
*/
|
|
57
|
+
function scopeSupported(deps = {}) {
|
|
58
|
+
if (cachedSupport !== null) return cachedSupport;
|
|
59
|
+
const platform = deps.platform || process.platform;
|
|
60
|
+
const spawnSync = deps.spawnSync || childProcess.spawnSync;
|
|
61
|
+
const fsImpl = deps.fs || fs;
|
|
62
|
+
const env = deps.env || process.env;
|
|
63
|
+
let ok = false;
|
|
64
|
+
try {
|
|
65
|
+
if (platform === 'linux') {
|
|
66
|
+
const dirs = String(env.PATH || '').split(path.delimiter).filter(Boolean);
|
|
67
|
+
const found = dirs.some((d) => fsImpl.existsSync(path.join(d, 'systemd-run')));
|
|
68
|
+
if (found) {
|
|
69
|
+
const r = spawnSync('systemd-run', ['--user', '--scope', '--quiet', '--collect', 'true'], {
|
|
70
|
+
stdio: 'ignore',
|
|
71
|
+
timeout: 5000,
|
|
72
|
+
});
|
|
73
|
+
ok = !!r && !r.error && r.status === 0;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
} catch {
|
|
77
|
+
ok = false;
|
|
78
|
+
}
|
|
79
|
+
cachedSupport = ok;
|
|
80
|
+
return ok;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** @param {string} unit */
|
|
84
|
+
function sanitizeUnit(unit) {
|
|
85
|
+
const s = String(unit == null ? '' : unit).replace(/[^A-Za-z0-9:_.\\-]/g, '-').replace(/\.scope$/, '');
|
|
86
|
+
return s || 'sm-job';
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* @param {{ command: string, args?: string[], unit: string, limits: { memoryMaxMb: number, memoryHighMb: number, swapMaxMb: number }, systemdRunPath?: string }} o
|
|
91
|
+
* @returns {{ command: string, args: string[] }}
|
|
92
|
+
*/
|
|
93
|
+
function wrapInMemoryScope(o) {
|
|
94
|
+
const { command, args = [], unit, limits, systemdRunPath } = o;
|
|
95
|
+
return {
|
|
96
|
+
command: systemdRunPath || 'systemd-run',
|
|
97
|
+
args: [
|
|
98
|
+
'--user',
|
|
99
|
+
'--scope',
|
|
100
|
+
'--quiet',
|
|
101
|
+
'--collect',
|
|
102
|
+
`--unit=${sanitizeUnit(unit)}.scope`,
|
|
103
|
+
'-p', `MemoryHigh=${limits.memoryHighMb}M`,
|
|
104
|
+
'-p', `MemoryMax=${limits.memoryMaxMb}M`,
|
|
105
|
+
'-p', `MemorySwapMax=${limits.swapMaxMb}M`,
|
|
106
|
+
'-p', 'OOMPolicy=continue',
|
|
107
|
+
'--',
|
|
108
|
+
command,
|
|
109
|
+
...args,
|
|
110
|
+
],
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Stop a scope by unit name, fire-and-forget. `--no-block` returns at once so a
|
|
116
|
+
* SIGTERM-ignoring straggler cannot stall the main thread. Never throws.
|
|
117
|
+
* @param {string} unit
|
|
118
|
+
* @param {{ spawn?: typeof childProcess.spawn }} [deps]
|
|
119
|
+
* @returns {void}
|
|
120
|
+
*/
|
|
121
|
+
function stopScope(unit, deps = {}) {
|
|
122
|
+
try {
|
|
123
|
+
const spawn = deps.spawn || childProcess.spawn;
|
|
124
|
+
const child = spawn('systemctl', ['--user', 'stop', '--no-block', `${sanitizeUnit(unit)}.scope`], {
|
|
125
|
+
stdio: 'ignore',
|
|
126
|
+
detached: true,
|
|
127
|
+
});
|
|
128
|
+
if (child && typeof child.on === 'function') child.on('error', () => { /* systemctl missing */ });
|
|
129
|
+
if (child && typeof child.unref === 'function') child.unref();
|
|
130
|
+
} catch { /* never throw */ }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
module.exports = {
|
|
134
|
+
memoryLimitsFor,
|
|
135
|
+
scopeSupported,
|
|
136
|
+
wrapInMemoryScope,
|
|
137
|
+
stopScope,
|
|
138
|
+
sanitizeUnit,
|
|
139
|
+
_resetScopeSupportCache,
|
|
140
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Pick Electron's --ozone-platform. A stalled Wayland client is dropped by the compositor
|
|
3
|
+
// ("Fatal Wayland communication error: Broken pipe", exit 0, no dump); X11/XWayland isn't.
|
|
4
|
+
// SM_OZONE_PLATFORM=x11|wayland wins; auto/unset -> x11 on a Wayland session with DISPLAY.
|
|
5
|
+
// null = leave Electron's default alone.
|
|
6
|
+
function chooseOzonePlatform(env = {}) {
|
|
7
|
+
const override = String(env.SM_OZONE_PLATFORM || '').trim().toLowerCase();
|
|
8
|
+
if (override === 'x11' || override === 'wayland') return override;
|
|
9
|
+
const session = String(env.XDG_SESSION_TYPE || '').trim().toLowerCase();
|
|
10
|
+
const display = String(env.DISPLAY || '').trim();
|
|
11
|
+
if (session === 'wayland' && display) return 'x11';
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
module.exports = { chooseOzonePlatform };
|
|
@@ -16,6 +16,13 @@
|
|
|
16
16
|
* all all read as "not different" — i.e. today's pid-only behaviour, never a
|
|
17
17
|
* false positive that could wrongly break a live lock or veto a real kill.
|
|
18
18
|
*
|
|
19
|
+
* Identity is pid + startTicks ONLY; cmdline is recorded but never compared.
|
|
20
|
+
* Why: exec keeps both pid and start time while replacing the cmdline, and
|
|
21
|
+
* `systemd-run --scope` execs the job in place — the identity taken right
|
|
22
|
+
* after spawn holds systemd-run's cmdline, the live job later holds its own.
|
|
23
|
+
* Comparing cmdline read a LIVE job as a foreign pid after an app restart.
|
|
24
|
+
* A recycled pid cannot repeat the same start time within a boot.
|
|
25
|
+
*
|
|
19
26
|
* SM_PROC_ROOT overrides the /proc root — tests only, so stat/cmdline
|
|
20
27
|
* fixtures can be written under a temp dir instead of touching real /proc.
|
|
21
28
|
*/
|
|
@@ -146,7 +153,8 @@ function identity(pid, { platform = process.platform, execFile = execFileSync }
|
|
|
146
153
|
|
|
147
154
|
/**
|
|
148
155
|
* isDifferentProcess(recorded, live) — true ONLY when both sides are a
|
|
149
|
-
* COMPLETE identity and differ.
|
|
156
|
+
* COMPLETE identity and pid or startTicks differ. cmdline is NOT compared
|
|
157
|
+
* (see header: exec keeps pid + start time). Every other case (missing side, incomplete
|
|
150
158
|
* side, a legacy record with no identity fields) is "not different", i.e.
|
|
151
159
|
* today's pid-only behaviour — the fail-closed default.
|
|
152
160
|
*/
|
|
@@ -154,8 +162,7 @@ function isDifferentProcess(recorded, live) {
|
|
|
154
162
|
if (!recorded || !live) return false;
|
|
155
163
|
if (!recorded.complete || !live.complete) return false;
|
|
156
164
|
return recorded.pid !== live.pid
|
|
157
|
-
|| recorded.startTicks !== live.startTicks
|
|
158
|
-
|| recorded.cmdline !== live.cmdline;
|
|
165
|
+
|| recorded.startTicks !== live.startTicks;
|
|
159
166
|
}
|
|
160
167
|
|
|
161
168
|
module.exports = { identity, isDifferentProcess };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* scopeOomPolicy.cjs — keep one child's OOM-kill from stopping the whole app.
|
|
5
|
+
*
|
|
6
|
+
* Electron runs in a transient systemd user scope
|
|
7
|
+
* (app-claude-code-session-manager-<pid>.scope) with the default OOMPolicy=stop,
|
|
8
|
+
* and every job, chat and pty lives inside it. When the kernel OOM-kills ANY
|
|
9
|
+
* child, systemd stops the entire scope (5 app deaths on 2026-10-31). A user
|
|
10
|
+
* drop-in on the scope-name prefix sets OOMPolicy=continue so a child's death
|
|
11
|
+
* stays that child's death. Written at boot; daemon-reload runs only when the
|
|
12
|
+
* file actually changed.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const nodeFs = require('node:fs');
|
|
16
|
+
const os = require('node:os');
|
|
17
|
+
const path = require('node:path');
|
|
18
|
+
const childProcess = require('node:child_process');
|
|
19
|
+
const atomicFs = require('../util/atomicFs.cjs');
|
|
20
|
+
|
|
21
|
+
const DROPIN_DIR = 'app-claude-code-session-manager-.scope.d';
|
|
22
|
+
const DROPIN_FILE = '10-oom-policy.conf';
|
|
23
|
+
const CONTENT = '[Scope]\nOOMPolicy=continue\n';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @param {object} [opts]
|
|
27
|
+
* @param {string} [opts.platform]
|
|
28
|
+
* @param {string} [opts.configHome]
|
|
29
|
+
* @param {any} [opts.fs] needs readFileSync
|
|
30
|
+
* @param {any} [opts.spawnSync]
|
|
31
|
+
* @param {(msg: string) => void} [opts.log]
|
|
32
|
+
* @param {(file: string, text: string) => void} [opts.writeText] defaults to atomicFs.writeTextAtomicSync
|
|
33
|
+
* @returns {{ applied: boolean, reason: string }}
|
|
34
|
+
*/
|
|
35
|
+
function ensureScopeOomPolicy(opts = {}) {
|
|
36
|
+
const platform = opts.platform || process.platform;
|
|
37
|
+
const fs = opts.fs || nodeFs;
|
|
38
|
+
const spawnSync = opts.spawnSync || childProcess.spawnSync;
|
|
39
|
+
const log = opts.log || (() => {});
|
|
40
|
+
const writeText = opts.writeText || ((f, t) => atomicFs.writeTextAtomicSync(f, t));
|
|
41
|
+
try {
|
|
42
|
+
if (platform !== 'linux') return { applied: false, reason: 'not-linux' };
|
|
43
|
+
const configHome = opts.configHome
|
|
44
|
+
|| process.env.XDG_CONFIG_HOME
|
|
45
|
+
|| path.join(os.homedir(), '.config');
|
|
46
|
+
|
|
47
|
+
const probe = spawnSync('systemctl', ['--user', '--version'], { stdio: 'ignore', timeout: 5000 });
|
|
48
|
+
if (!probe || probe.error || probe.status !== 0) {
|
|
49
|
+
return { applied: false, reason: 'no-systemctl' };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const file = path.join(configHome, 'systemd', 'user', DROPIN_DIR, DROPIN_FILE);
|
|
53
|
+
let existing = null;
|
|
54
|
+
try { existing = fs.readFileSync(file, 'utf8'); } catch { existing = null; }
|
|
55
|
+
if (existing === CONTENT) return { applied: false, reason: 'already-current' };
|
|
56
|
+
|
|
57
|
+
writeText(file, CONTENT);
|
|
58
|
+
const reload = spawnSync('systemctl', ['--user', 'daemon-reload'], { stdio: 'ignore', timeout: 15000 });
|
|
59
|
+
if (!reload || reload.error || reload.status !== 0) {
|
|
60
|
+
log(`scopeOomPolicy: daemon-reload failed (${reload?.error?.message || `status ${reload?.status}`})`);
|
|
61
|
+
return { applied: false, reason: 'daemon-reload-failed' };
|
|
62
|
+
}
|
|
63
|
+
return { applied: true, reason: existing === null ? 'written' : 'updated' };
|
|
64
|
+
} catch (e) {
|
|
65
|
+
return { applied: false, reason: `error: ${e?.message || e}` };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
module.exports = { ensureScopeOomPolicy, DROPIN_DIR, DROPIN_FILE, CONTENT };
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* pagesLibrary.cjs — Project Home library storage. One folder per entry under
|
|
5
|
+
* `project-pages/knowledge/<id>/` and `project-pages/videos/<id>/`, each with
|
|
6
|
+
* `index.html` + `meta.json`. The folder listing IS the library (no manifest).
|
|
7
|
+
* listLibrary() reads it newest-first; migrateLegacy() moves the old single
|
|
8
|
+
* `home.html` and `demo-video/index.html` into it exactly once, keeping the
|
|
9
|
+
* originals as `<name>.migrated`. All writes go through config.writeTextAtomic
|
|
10
|
+
* with writer 'project-home' (single-writer law, opsOwnership.cjs).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const fs = require('node:fs');
|
|
14
|
+
const fsp = require('node:fs/promises');
|
|
15
|
+
const path = require('node:path');
|
|
16
|
+
const crypto = require('node:crypto');
|
|
17
|
+
const config = require('../../config.cjs');
|
|
18
|
+
const { opsPath, assertOpsWrite } = require('../opsOwnership.cjs');
|
|
19
|
+
const { injectPlayerBridge } = require('./playerBridge.cjs');
|
|
20
|
+
|
|
21
|
+
const WRITER = 'project-home';
|
|
22
|
+
const MAX_ENTRIES = 500;
|
|
23
|
+
const SKIP_DIRS = new Set(['_character']);
|
|
24
|
+
const KINDS = /** @type {const} */ (['knowledge', 'videos']);
|
|
25
|
+
|
|
26
|
+
/** opsPath, with the ephemeral-cwd throw mapped to null ("nothing to do"). */
|
|
27
|
+
function pagesPath(realCwd, ...parts) {
|
|
28
|
+
try {
|
|
29
|
+
return opsPath(realCwd, 'project-pages', ...parts);
|
|
30
|
+
} catch (e) {
|
|
31
|
+
if (e && e.ephemeral) return null;
|
|
32
|
+
throw e;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function oneLine(msg) {
|
|
37
|
+
return String(msg).replace(/\s+/g, ' ').trim().slice(0, 200) || 'invalid meta';
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function readEntry(kind, dir, id) {
|
|
41
|
+
const file = path.join(dir, 'index.html');
|
|
42
|
+
let st;
|
|
43
|
+
try {
|
|
44
|
+
st = await fsp.stat(file);
|
|
45
|
+
} catch {
|
|
46
|
+
return null; // folder without index.html is not an entry
|
|
47
|
+
}
|
|
48
|
+
const { schemas } = require('../../ipcSchemas.cjs');
|
|
49
|
+
const schema = kind === 'videos' ? schemas.projectVideoMeta : schemas.projectPageMeta;
|
|
50
|
+
let meta = null;
|
|
51
|
+
let error = null;
|
|
52
|
+
try {
|
|
53
|
+
const raw = await fsp.readFile(path.join(dir, 'meta.json'), 'utf8');
|
|
54
|
+
const parsed = schema.safeParse(JSON.parse(raw));
|
|
55
|
+
if (parsed.success) meta = parsed.data;
|
|
56
|
+
else error = oneLine(`meta.json invalid: ${parsed.error.issues[0]?.path.join('.') || ''} ${parsed.error.issues[0]?.message || ''}`);
|
|
57
|
+
} catch (e) {
|
|
58
|
+
error = oneLine(e && e.code === 'ENOENT' ? 'meta.json missing' : `meta.json unreadable: ${e && e.message}`);
|
|
59
|
+
}
|
|
60
|
+
return { id, path: file, mtimeMs: st.mtimeMs, meta, error };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function listKind(realCwd, kind) {
|
|
64
|
+
const root = pagesPath(realCwd, kind);
|
|
65
|
+
if (!root) return [];
|
|
66
|
+
let dirents;
|
|
67
|
+
try {
|
|
68
|
+
dirents = await fsp.readdir(root, { withFileTypes: true });
|
|
69
|
+
} catch (e) {
|
|
70
|
+
if (e.code === 'ENOENT') return [];
|
|
71
|
+
throw e;
|
|
72
|
+
}
|
|
73
|
+
const dirs = dirents.filter((d) => d.isDirectory() && !SKIP_DIRS.has(d.name)).slice(0, MAX_ENTRIES);
|
|
74
|
+
const entries = (await Promise.all(dirs.map((d) => readEntry(kind, path.join(root, d.name), d.name)))).filter(Boolean);
|
|
75
|
+
const stamp = (e) => {
|
|
76
|
+
const t = e.meta ? Date.parse(e.meta.createdAt) : NaN;
|
|
77
|
+
return Number.isFinite(t) ? t : e.mtimeMs;
|
|
78
|
+
};
|
|
79
|
+
return entries.sort((a, b) => stamp(b) - stamp(a));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** -> { knowledge: Entry[], videos: Entry[] }, newest first. */
|
|
83
|
+
async function listLibrary(realCwd) {
|
|
84
|
+
const [knowledge, videos] = await Promise.all(KINDS.map((k) => listKind(realCwd, k)));
|
|
85
|
+
return { knowledge, videos };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Write `outBuf` into `destDir/index.html` + meta; true only after a byte-equal verified write. */
|
|
89
|
+
async function copyIntoEntry(outBuf, destDir, meta) {
|
|
90
|
+
const dest = path.join(destDir, 'index.html');
|
|
91
|
+
await config.writeTextAtomic(dest, outBuf.toString('utf8'), { writer: WRITER });
|
|
92
|
+
const back = await fsp.readFile(dest);
|
|
93
|
+
if (!back.equals(outBuf)) return false;
|
|
94
|
+
await config.writeTextAtomic(path.join(destDir, 'meta.json'), JSON.stringify(meta, null, 2) + '\n', { writer: WRITER });
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Rename through the same validation + ownership check writeTextAtomic uses. */
|
|
99
|
+
async function renameMigrated(file) {
|
|
100
|
+
const real = config.validatePath(file);
|
|
101
|
+
config.validateWrite(real);
|
|
102
|
+
assertOpsWrite(real, WRITER);
|
|
103
|
+
const target = `${real}.migrated`;
|
|
104
|
+
config.validateWrite(target);
|
|
105
|
+
assertOpsWrite(target, WRITER);
|
|
106
|
+
await fsp.rename(real, target);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function readIfFile(file) {
|
|
110
|
+
try {
|
|
111
|
+
return await fsp.readFile(file);
|
|
112
|
+
} catch (e) {
|
|
113
|
+
if (e.code === 'ENOENT') return null;
|
|
114
|
+
throw e;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function demoLengthS(html) {
|
|
119
|
+
const m = /<meta\s+name=["']sm-demo-duration["']\s+content=["'](\d+(?:\.\d+)?)["']/i.exec(html);
|
|
120
|
+
const n = m ? Math.round(Number(m[1])) : NaN;
|
|
121
|
+
return Number.isFinite(n) && n >= 5 && n <= 60 ? n : 30;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** One-shot move of the legacy home.html / demo-video/index.html into the library. Idempotent. */
|
|
125
|
+
async function migrateLegacy(realCwd) {
|
|
126
|
+
const home = pagesPath(realCwd, 'home.html');
|
|
127
|
+
if (!home) return;
|
|
128
|
+
|
|
129
|
+
// home.html -> knowledge/overview/
|
|
130
|
+
const overviewDir = pagesPath(realCwd, 'knowledge', 'overview');
|
|
131
|
+
const homeBuf = await readIfFile(home);
|
|
132
|
+
if (homeBuf && !fs.existsSync(overviewDir)) {
|
|
133
|
+
const st = await fsp.stat(home);
|
|
134
|
+
const meta = {
|
|
135
|
+
id: 'overview',
|
|
136
|
+
title: 'Overview',
|
|
137
|
+
topic: 'overview',
|
|
138
|
+
createdAt: new Date(st.mtimeMs).toISOString(),
|
|
139
|
+
model: 'unknown',
|
|
140
|
+
};
|
|
141
|
+
if (await copyIntoEntry(homeBuf, overviewDir, meta)) await renameMigrated(home);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// demo-video/index.html -> videos/legacy-<sha10>/
|
|
145
|
+
const demo = pagesPath(realCwd, 'demo-video', 'index.html');
|
|
146
|
+
const demoBuf = await readIfFile(demo);
|
|
147
|
+
if (demoBuf) {
|
|
148
|
+
const st = await fsp.stat(demo);
|
|
149
|
+
const id = `legacy-${crypto.createHash('sha256').update(demoBuf).digest('hex').slice(0, 10)}`;
|
|
150
|
+
// Bridge goes into the migrated copy only; the id hashes the ORIGINAL bytes.
|
|
151
|
+
const bridgedBuf = Buffer.from(injectPlayerBridge(demoBuf.toString('utf8')), 'utf8');
|
|
152
|
+
const meta = {
|
|
153
|
+
id,
|
|
154
|
+
title: 'Demo video',
|
|
155
|
+
kind: 'project-demo',
|
|
156
|
+
style: 'legacy',
|
|
157
|
+
lengthS: demoLengthS(demoBuf.toString('utf8')),
|
|
158
|
+
createdAt: new Date(st.mtimeMs).toISOString(),
|
|
159
|
+
character: null,
|
|
160
|
+
sources: [],
|
|
161
|
+
report: { lufs: null, truePeakDb: null, speechS: null, readingGrade: null, checks: [], bytes: bridgedBuf.length },
|
|
162
|
+
macroVersion: 0,
|
|
163
|
+
seedVersion: 0,
|
|
164
|
+
model: 'unknown',
|
|
165
|
+
effort: 'unknown',
|
|
166
|
+
};
|
|
167
|
+
if (await copyIntoEntry(bridgedBuf, pagesPath(realCwd, 'videos', id), meta)) await renameMigrated(demo);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
module.exports = { listLibrary, migrateLegacy };
|